import { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { setFile, setResult, setValidatedData, reset } from "../../../store/slices/uploadSlice";
import { uploadFile, uploadPdf, saveToDatabase } from "./service_admin_upload";
import { useNavigate } from "react-router-dom";

export function useUploadController() {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { file, result } = useSelector((state) => state.upload);
  const [loading, setLoading] = useState(false);
  const [selectedTable, setSelectedTable] = useState(null);
  const [tableTitle, setTableTitle] = useState("");

  const handleFileSelect = (f) => {
    dispatch(setFile(f));
  };

  const handleUpload = async () => {
    if (!file) return;
    setLoading(true);
    try {
      const res = await uploadFile(file);
      dispatch(setResult(res));
      if (res.file_type !== ".pdf" || (res.file_type === ".pdf" && res.tables.length === 1)) {
        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,
    selectedTable,
    setSelectedTable,
    tableTitle,
    setTableTitle,
    handleFileSelect,
    handleUpload,
    handleNextPdf,
    handleConfirmUpload,
  };
}
