import { useUploadController } from "./controller_admin_upload";
import FileDropzone from "../../../components/FileDropzone";
import { Link } from "react-router-dom";

export default function ViewsAdminUploadStep1() {
  const {
    loading,
    file,
    result,
    selectedTable,
    setSelectedTable,
    handleFileSelect,
    handleUpload,
    handleNextPdf,
  } = useUploadController();

  return (
    <div className="max-w-4xl mx-auto py-10">
      <div className="mb-6 flex justify-between items-center">
        <h1 className="text-2xl font-bold text-gray-800">Upload Data</h1>
        <p className="text-lg text-gray-600">
          <Link to="/admin/upload/rules" className="text-blue-600 hover:underline">
            Panduan upload →
          </Link>
        </p>
      </div>

      <FileDropzone onFileSelect={handleFileSelect} />
      {file && (
        <div className="mt-3">
          <p className="text-gray-700 text-sm">File terpilih: {file.name}</p>
          <button
            onClick={handleUpload}
            disabled={loading}
            className="mt-3 px-5 py-2 rounded-lg bg-blue-600 text-white hover:bg-blue-700 disabled:bg-gray-400"
          >
            {loading ? "Mengunggah..." : "Upload"}
          </button>
        </div>
      )}

      {result && result.file_type === ".pdf" && result.tables?.length > 1 && (
        <div className="mt-6">
          <h2 className="text-lg font-semibold mb-2 text-gray-700">Hasil Analisis Backend</h2>
          <ul className="border rounded-lg divide-y overflow-hidden">
            {result.tables.map((t, i) => (
              <li
                key={i}
                onClick={() => setSelectedTable(t)}
                className={`flex items-center gap-2 p-3 cursor-pointer hover:bg-blue-50 transition ${
                  selectedTable?.title === t.title ? "bg-blue-100 font-semibold" : ""
                }`}
              >
                <span className={`text-green-600 ${selectedTable?.title === t.title ? "" : "opacity-0"}`}>✅</span>
                <span>{t.title}</span>
              </li>
            ))}
          </ul>
          <button
            onClick={handleNextPdf}
            disabled={!selectedTable}
            className="mt-4 px-5 py-2 bg-green-600 text-white rounded hover:bg-green-700 disabled:bg-gray-300"
          >
            Lanjut ke Validasi →
          </button>
        </div>
      )}
    </div>
  );
}
