import React from "react";
  import { useNavigate } from "react-router-dom";
  import { capitalize } from "Utils/utils";
  import { Spinner } from "Assets/svgs";
  import { colors } from "Utils/config";
  import { LazyLoad } from "Components/LazyLoad";
  import MkdListTableRow from "./MkdListTableRow";
  import MkdListTableHead from "./MkdListTableHead";
  import { ModalPrompt } from "Components/Modal";
  import { EyeIcon, PencilIcon, TrashIcon } from "@heroicons/react/24/solid";
  
  const MkdListTable = ({
    table,
    tableTitle,
    onSort,
    loading,
    columns,
    actions,
    actionPostion,
    tableRole,
    deleteItem,
    deleteLoading,
    actionId = "id",
    showDeleteModal,
    currentTableData,
    setShowDeleteModal,
    handleTableCellChange,
    setSelectedItems,
  }) => {
    const [deleteId, setIdToDelete] = React.useState(null);
    const [isOneOrMoreRowSelected, setIsOneOrMoreRowSelected] =
      React.useState(false);
    const [areAllRowsSelected, setAreAllRowsSelected] = React.useState(false);
    const [selectedIds, setSelectedIds] = React.useState([]);
  
    function handleSelectRow(id) {
      setIsOneOrMoreRowSelected(true);
      const tempIds = selectedIds;
  
      if (actions?.select?.multiple) {
        if (tempIds.includes(id)) {
          const newIds = tempIds.filter((selectedId) => selectedId !== id);
          setSelectedIds(() => [...newIds]);
          setSelectedItems(newIds);
        } else {
          const newIds = [...tempIds, id];
          setSelectedIds(() => [...newIds]);
          setSelectedItems(newIds);
        }
      } else {
        if (tempIds.includes(id)) {
          const newIds = tempIds.filter((selectedId) => selectedId !== id);
          setSelectedIds(() => [...newIds]);
          setSelectedItems(newIds);
        } else {
          const newIds = [id];
          setSelectedIds(() => [...newIds]);
          setSelectedItems(newIds);
        }
      }
      console.log(id);
    }
  
    const handleSelectAll = () => {
      setAreAllRowsSelected((prevSelectAll) => !prevSelectAll);
      if (!areAllRowsSelected) {
        const allIds = currentTableData.map((item) => item[actionId]);
        setSelectedIds(allIds);
        setSelectedItems(allIds);
      } else {
        setSelectedIds([]);
        setSelectedItems([]);
      }
    };
  
    const handleDeleteAll = async (id) => {
      setShowDeleteModal(true);
      setIdToDelete(id);
    };
  
    const navigate = useNavigate();
  
    const setDeleteId = async (id) => {
      console.log("id >>", id);
      setShowDeleteModal(true);
      setIdToDelete(id);
    };
  
    React.useEffect(() => {
      if (selectedIds.length <= 0) {
        setIsOneOrMoreRowSelected(false);
        setAreAllRowsSelected(false);
      }
      if (selectedIds.length === currentTableData.length) {
        setAreAllRowsSelected(true);
        setIsOneOrMoreRowSelected(true);
      }
      if (
        selectedIds.length < currentTableData.length &&
        selectedIds.length > 0
      ) {
        setAreAllRowsSelected(false);
      }
    }, [selectedIds, currentTableData]);
    //  console.log("currentTableData")
    //  console.log(currentTableData)
    //  console.log(columns)
    return (
      <>
        <div
          className={`${
            loading ? "" : "overflow-x-auto"
          } border-b border-gray-200 shadow`}
        >
          {loading ? (
            <div
              className={`flex max-h-fit min-h-fit min-w-fit max-w-full items-center justify-center  py-5`}
            >
              <Spinner size={50} color={colors.primary} />
            </div>
          ) : (
            <>
              {/* <div
                className="flex items-center space-x-3 border bg-gray-300 p-3 transition-all"
                style={{
                  transform: isOneOrMoreRowSelected
                    ? "translateX(0)"
                    : "translateX(-100%)",
                  visibility: isOneOrMoreRowSelected ? "visible" : "hidden",
                }}
              >
                <div className="mr-3 flex flex-col items-center justify-center">
                  <input
                    type="checkbox"
                    id="select_all_rows"
                    checked={areAllRowsSelected}
                    onChange={handleSelectAll}
                  />
                  <label for="select_all_rows">Select All</label>
                </div>
                <TrashIcon
                  className={`h-[1rem] w-[1rem] cursor-pointer text-red-500 group-hover: text-white`}
                  onClick={() => handleDeleteAll(selectedIds)}
                />
              </div> */}
  
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <LazyLoad>
                    <MkdListTableHead
                      onSort={onSort}
                      columns={columns}
                      actions={actions}
                      actionPostion={actionPostion}
                      areAllRowsSelected={areAllRowsSelected}
                      handleSelectAll={handleSelectAll}
                    />
                  </LazyLoad>
                </thead>
                <tbody className="divide-y divide-gray-200 bg-white">
                  {currentTableData.map((row, i) => {
                    return (
                      <LazyLoad key={i}>
                        <MkdListTableRow
                          key={i}
                          i={i}
                          row={row}
                          columns={columns}
                          actions={actions}
                          actionPostion={actionPostion}
                          actionId={actionId}
                          handleTableCellChange={handleTableCellChange}
                          handleSelectRow={handleSelectRow}
                          selectedIds={selectedIds}
                          setDeleteId={setDeleteId}
                        />
                      </LazyLoad>
                    );
                  })}
                </tbody>
              </table>
            </>
          )}
        </div>
  
        <LazyLoad>
          <ModalPrompt
            open={showDeleteModal}
            actionHandler={() => {
              deleteItem(deleteId);
            }}
            closeModalFunction={() => {
              setIdToDelete(null);
              setShowDeleteModal(false);
            }}
            title={`Delete ${capitalize(table)} `}
            message={`You are about to delete ${capitalize(
              table
            )} ${deleteId}, note that this action is irreversible`}
            acceptText={`DELETE`}
            rejectText={`CANCEL`}
            loading={deleteLoading}
          />
        </LazyLoad>
      </>
    );
  };
  
  export default MkdListTable;  
