import DataTable, { TableColumn } from "react-data-table-component";
import "./assets/css/styles.css";
import { LoadingSpinner } from "../../../components/loading_spinner/loading_spinner";
import { useCategory } from "../../../../domain/useCase/useCategory";
import { Category } from "../../../../data/datasource/api/entities/category";
import { faTrash } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Dispatch, SetStateAction, useEffect, useState } from "react";
import { ConfirmationDialog } from "../../../components/confirmation_dialog_box/confirmation_dialog";
import { toast } from "react-toastify";

// Define the props interface for the component
interface props {
  isWindowActive: boolean;
  setIsWindowActive: Dispatch<SetStateAction<boolean>>;
}

// Main component for displaying the category list
export const SuperAdminPanelCategoryList = ({
  isWindowActive,
  setIsWindowActive,
}: props) => {
  // Custom hook to fetch categories and handle deletion
  const { categoriesList, pending, deleteCategory } = useCategory();
  // State variables for managing dialog and deletion
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [dialogMessage, setDialogMessage] = useState("");
  const [categoryDeleted, setCategoryDeleted] = useState<Category | null>(null);
  const [deleteCategoryBool, setDeleteCategoryBool] = useState(false);

  // Function to delete the selected category with a toast notification
  const deleteSelectedCategory = (category: Category) => {
    toast.promise(deleteCategory(category), {
      pending: "Eliminando categoría...",
      success: "La categoría se ha eliminado correctamente",
      error: "No se pudo eliminar la categoría",
    });
  };

  // Effect to handle category deletion when deleteCategoryBool changes
  useEffect(() => {
    if (deleteCategoryBool && categoryDeleted) {
      deleteSelectedCategory(categoryDeleted);
      setDeleteCategoryBool(false);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [deleteCategoryBool]);

  // Function to handle the delete action and open the confirmation dialog
  const handleDeleteSelectedCategory = (category: Category) => {
    setDialogMessage(`¿Desea eliminar la categoría ${category.nameES}?`);
    setCategoryDeleted(category);
    setIsDialogOpen(true);
    setIsWindowActive(true);
  };

  // Function to close the confirmation dialog
  const handleToClose = () => {
    setIsWindowActive(false);
    setIsDialogOpen(false);
  };

  // Define the columns for the DataTable
  const columns: TableColumn<Category>[] = [
    {
      name: "Identificador",
      selector: (row) => row.idCategory || 0,
      sortable: true,
    },
    {
      name: "Nombre en español",
      selector: (row) => row.nameES,
      sortable: true,
    },
    {
      name: "Nombre en Inglés",
      selector: (row) => row.nameEN,
      sortable: true,
    },
    {
      name: "Acciones",
      cell: (row) => {
        return (
          <FontAwesomeIcon
            style={isWindowActive ? { color: "gray" } : { cursor: "pointer" }}
            icon={faTrash}
            onClick={() => {
              if (!isWindowActive) {
                handleDeleteSelectedCategory(row);
              }
            }}
          />
        );
      },
    },
  ];

  // Render the DataTable and ConfirmationDialog components
  return (
    <div className="category_list_cnt">
      <DataTable
        noDataComponent="No hay categorías que mostrar"
        progressPending={pending}
        progressComponent={<LoadingSpinner style={{ display: "flex" }} />}
        disabled={isWindowActive}
        columns={columns}
        data={categoriesList}
        className="data_table"
      />
      {isDialogOpen && (
        <ConfirmationDialog
          handleToClose={handleToClose}
          setAnswer={setDeleteCategoryBool}
          message={dialogMessage}
        />
      )}
    </div>
  );
};
