import { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { setFile, setResult, setValidatedData, setPdfPageCount, setSelectedPages } from "../../../store/slices/uploadSlice";
import { uploadFile, uploadPdf, saveToDatabase } from "./service_admin_upload";
import { useNavigate } from "react-router-dom";
import * as pdfjsLib from "pdfjs-dist";
pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
  "pdfjs-dist/build/pdf.worker.mjs",
  import.meta.url
).toString();

import * as XLSX from 'xlsx';

export function useUploadController() {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { file, result, pdfPageCount, selectedPages } = useSelector((state) => state.upload);

  const [loading, setLoading] = useState(false);
  const [selectedTable, setSelectedTable] = useState(null);
  // const [selectedPages, setSelectedPages] = useState("");
  const [tableTitle, setTableTitle] = useState("");
  // const [pdfPageCount, setPdfPageCount] = useState(null);
  const [selectedSheet, setSelectedSheet] = useState(null);
  const [sheetCount, setSheetCount] = useState(null);
  const [sheetNames, setSheetNames] = useState([]);

  // 🔹 handle drop file
  const handleFileSelect = async (f) => {
    dispatch(setFile(f));
    const ext = f.name.split(".").pop().toLowerCase();

    if (ext === "pdf") {
      try {
        const reader = new FileReader();
        reader.onload = async (e) => {
          const typedArray = new Uint8Array(e.target.result);
          const pdf = await pdfjsLib.getDocument({ data: typedArray }).promise;
          // setPdfPageCount(pdf.numPages);
          dispatch(setPdfPageCount(pdf.numPages));
          console.log(`📄 PDF terdeteksi dengan ${pdf.numPages} halaman`);
        };
        reader.readAsArrayBuffer(f);
      } catch (err) {
        console.error("Gagal membaca PDF:", err);
      }
    } 
    else if (ext === "xlsx" || ext === "xls") {
      const data = await f.arrayBuffer();
      const workbook = XLSX.read(data, { type: 'array' });
      const sheetNames = workbook.SheetNames;

      setSheetCount(sheetNames.length);
      setSheetNames(sheetNames);
    }
    else {
      // setPdfPageCount(null);
      dispatch(setPdfPageCount(null));
    }
  };

  // 🔹 upload file
  const handleUpload = async () => {
    if (!file) return;
    setLoading(true);
    try {
      console.log(selectedPages);
      const res = await uploadFile(file, selectedPages, selectedSheet);
      dispatch(setResult(res));
      
      if (res.file_type !== ".pdf" || (res.file_type === ".pdf" && !res.tables)) {
        navigate("/admin/upload/validate");
      }
    } finally {
      setLoading(false);
    }
  };

  const handleNextPdf = async () => {
    if (!selectedTable) return;
    setLoading(true);
    try {
      const res = await uploadPdf(selectedTable);
      dispatch(setResult(res));
      navigate("/admin/upload/validate");
    } finally {
      setLoading(false);
    }
  };

  const handleConfirmUpload = async () => {
    setLoading(true);
    try {
      const data = {
        title: tableTitle,
        columns: result.columns,
        rows: result.preview,
      };
      const res = await saveToDatabase(data);
      dispatch(setValidatedData(res));
      navigate("/admin/upload/success");
    } finally {
      setLoading(false);
    }
  };

  return {
    loading,
    file,
    result,
    tableTitle,
    selectedTable,
    selectedPages,
    pdfPageCount,
    sheetCount,
    sheetNames,
    selectedSheet,
    setSelectedTable,
    setSelectedPages,
    setSelectedSheet,
    setTableTitle,
    handleFileSelect,
    handleUpload,
    handleNextPdf,
    handleConfirmUpload,
  };
}
