import DataTable, { TableColumn } from "react-data-table-component";
import "./assets/css/styles.css";
import { faEye } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Dispatch, SetStateAction, useEffect, useState } from "react";
import { PointOfInterest } from "../../../../data/datasource/api/entities/poi";
import { usePlace } from "../../../../domain/useCase/usePlace";
import { usePointOfInterest } from "../../../../domain/useCase/usePointOfInterest";
import { LoadingScreen } from "../../../components/loading_screen/loading_screen";
import { LoadingSpinner } from "../../../components/loading_spinner/loading_spinner";

// Define the props interface for the component
interface props {
  idTown: number;
  isWindowActive: boolean;
  setActualPoint: Dispatch<SetStateAction<PointOfInterest | undefined>>;
  setWindowVisibilityViewer: (visibility: boolean) => void;
  setBinaryData: Dispatch<SetStateAction<string>>;
  setIsPDFViewerActive: Dispatch<SetStateAction<boolean>>;
}

// Main component for the Admin Panel POI List
export const AdminPanelPoiList = ({
  idTown,
  isWindowActive,
  setActualPoint,
  setWindowVisibilityViewer,
  setBinaryData,
  setIsPDFViewerActive,
}: props) => {
  // State variables
  const [isLoading, setIsLoading] = useState(false);
  const [isPDFLoading, setIsPDFLoading] = useState(false);
  const [printButtonActive, setPrintButtonActive] = useState(false);
  const [selectedRows, setSelectedRows] = useState<number[]>([]);
  const [actualPlaceId, setActualPlaceId] = useState(0);
  const { getPdfById } = usePointOfInterest();

  // Handle row selection in the data table
  const handleRowSelected = (selected: {
    allSelected: boolean;
    selectedCount: number;
    selectedRows: PointOfInterest[];
  }) => {
    setSelectedRows(
      selected.selectedRows.map((element) => {
        return element.idPoint || -1;
      })
    );
  };

  // Effect to toggle print button based on selected rows
  useEffect(() => {
    if (selectedRows.length > 0) {
      setPrintButtonActive(true);
    } else {
      setPrintButtonActive(false);
    }
  }, [selectedRows]);

  // Handle click on the print button
  const handleClickPrintButton = () => {
    const fetchPdf = async () => {
      setIsPDFLoading(true);
      const res = await getPdfById(actualPlaceId, selectedRows);
      if (res !== null) {
        setIsPDFViewerActive(true);
        setBinaryData(res);
      }
      setIsPDFLoading(false);
    };
    fetchPdf();
  };

  const { placeList, updatePlacesByTown } = usePlace();
  const { pending, updatePOIByPlace, poiList } = usePointOfInterest();

  // Handle viewing a selected point of interest
  const handleViewSelectedPoint = (point: PointOfInterest) => {
    setActualPoint(point);
    setWindowVisibilityViewer(true);
  };

  // Define columns for the data table
  const columns: TableColumn<PointOfInterest>[] = [
    {
      name: "Identificador",
      selector: (row) => row.idPoint || -1,
      sortable: true,
    },
    {
      name: "Nombre",
      selector: (row) => row.name.substring(0, 40),
      sortable: true,
    },
    {
      name: "Acciones",
      cell: (row) => {
        return (
          <FontAwesomeIcon
            style={{ cursor: "pointer" }}
            icon={faEye}
            onClick={() => {
              if (!isWindowActive) {
                handleViewSelectedPoint(row);
              }
            }}
          />
        );
      },
    },
  ];

  // Effect to update places by town on component mount
  useEffect(() => {
    setIsLoading(true);
    updatePlacesByTown(idTown);
    setIsLoading(false);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Refresh the list of points of interest by place
  const refreshList = (idPlace: number) => {
    updatePOIByPlace(idPlace);
  };

  // Show loading spinner if data is loading
  if (isLoading) return <LoadingSpinner />;

  return (
    <div className="poi_list_cnt">
      <div className="poi_list_header">
        Lugar
        <select
          disabled={isWindowActive}
          name="place_select"
          onChange={(event) => {
            const index = Number(event.target.value);
            const place = placeList[index];
            setActualPlaceId(place.idPlace || 0);
            refreshList(place.idPlace || 0);
          }}
        >
          {placeList === null || placeList.length === 0 ? (
            <option disabled defaultValue="" value="">
              No hay lugares
            </option>
          ) : (
            <>
              <option disabled selected value={0}>
                Selecciona el lugar
              </option>
              {placeList.map((place, index) => {
                return (
                  <option key={place.idPlace} value={index}>
                    {place.name}
                  </option>
                );
              })}
            </>
          )}
        </select>
        <button
          disabled={!printButtonActive}
          onClick={handleClickPrintButton}
          className="print_btn"
        >
          Imprimir
        </button>
      </div>
      <div className="poi_list_body">
        <DataTable
          noDataComponent="No hay puntos de interés que mostrar"
          progressPending={pending}
          disabled={isWindowActive}
          progressComponent={<LoadingSpinner style={{ display: "flex" }} />}
          onSelectedRowsChange={handleRowSelected}
          columns={columns}
          data={poiList}
          selectableRows
          className="data_table"
        />
      </div>
      {isPDFLoading && <LoadingScreen />}
    </div>
  );
};
