import {
  Box,
  Button,
  HStack,
  Input,
  Text,
  Tooltip,
  useDisclosure,
  Image,
  useToast,
} from "@chakra-ui/react";
import React, { useContext, useEffect, useRef, useState } from "react";
import InvestmentDocuments from "../InvestmentDocuments";
import DataTable from "../../../Components/DataTable/DataTable";
import CustomAlertDialog from "../../../Components/CustomAlertDialog";
import GlobalStateContext from "../../../Contexts/GlobalStateContext";
import { debounce } from "../../Master/Sponser/AddSponser";
import { formatDate } from "../../../Components/Functions/UTCConvertor";
import {
  AddIcon,
  DeleteIcon,
  DownloadIcon,
  EditIcon,
  ViewIcon,
} from "@chakra-ui/icons";
import KeyMeritsAdd from "../KeyMeritsAdd";
import { useParams } from "react-router-dom";
import {
  useDeleteKeyMeritsMutation,
  useGetKeyMeritsQuery,
} from "../../../Services/io.service";
import FullscreenLoaders from "../../../Components/Loaders/FullscreenLoaders";
import ToastBox from "../../../Components/ToastBox";
import KeyMeritsEdit from "../KeyMeritsEdit";
import SetDisplayOrder from "./SetDisplayOrder";

const KeyMerits = ({ enableNextTab, index, data: prepopData }) => {
  const toast = useToast();
  const params = useParams();

  // =====================[ variables ] 
  const id = params?.id;
  // const { data, isLoading, error } = useGetKeyMeritsQuery(id, {
  //   skip: !id,
  // });

  const { IODetails} = useContext(GlobalStateContext);

  
  

  const firstField = useRef();
  const [searchTerm, setSearchTerm] = useState("");
  const [deleteAlert, setDeleteAlert] = useState(false);
  const [actionId, setActionId] = useState(false);
  const [mouseEntered, setMouseEntered] = useState(false);
  const [isBtnLoading, setIsBtnLoading] = useState(false);
  const [mouseEnteredId, setMouseEnteredId] = useState("");
  const { isOpen, onOpen, onClose } = useDisclosure();
  const {
    isOpen: isEditOpen,
    onOpen: onEditOpen,
    onClose: onEditCloseOpen,
  } = useDisclosure();
  const [deleteKeyMerits] = useDeleteKeyMeritsMutation();

  const tableHeadRow = ["Sr.no", "Title", "Sub title", "Icon", "Action"];



  const filteredData = IODetails?.keyMerits?.filter((item) => {
    // Filter by name (case insensitive)
    const name = item.meritsHeader;
    const searchLower = searchTerm.toLowerCase();
    const nameMatches = name.toLowerCase().includes(searchLower);

    return nameMatches;
  });

  // console.log(filteredData);
  const sortedData = filteredData?.sort(
    (a, b) => a.displayOder - b.displayOder
  );

  const handleDelete = async () => {
    setIsBtnLoading(true);
    try {
      const res = await deleteKeyMerits(actionId);
      if (res?.data?.statusCode === 200) {
        toast({
          render: () => <ToastBox message={res?.data?.message} />,
        });
        setIsBtnLoading(false);
        setDeleteAlert(false);
      }
    } catch (error) {}
  };

  const extractedArray = sortedData?.map((item, index) => ({
    id: item.id,
    "Sr.no": (
      <Text
        justifyContent={"left"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {index + 1}
      </Text>
    ),
    Title: (
      <Text
        justifyContent={"left"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {item.meritsHeader}
      </Text>
    ),
    "Sub title": (
      <Box w={"300px"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          {item.meritsDescription}
        </Text>
      </Box>
    ),
    Icon: item?.icon?.iconFilePath && (
      <Image
        rounded={"md"}
        // bg={"#003B14"}
        display={"flex"}
        p={1}
        justifyContent={"center"}
        alignItems={"center"}
        src={" https://tanami.betadelivery.com/" + item?.icon?.iconFilePath}
        w={8}
        h={8}
      />
    ),

    // https://tanami.betadelivery.com/public/icons/linkedin.png
    Action: (
      <Box display={"flex"} justifyContent={"center"} gap={2}>
        {/* <Tooltip
          rounded={"sm"}
          fontSize={"xs"}
          label="View"
          bg="#fff"
          color={"green.500"}
          placement="top"
        >
          <Button
            _hover={{ color: "green.500" }}
            // transition={"0.5s all"}
            onClick={() => {
              navigate(`view-investment/${item.id}`);
            }}
            color="green.300"
            rounded={"sm"}
            size={"xs"}
          >
            <ViewIcon />
          </Button>
        </Tooltip> */}
        <Tooltip
          rounded={"sm"}
          fontSize={"xs"}
          label="Edit"
          bg="#fff"
          color={"blue.500"}
          placement="top"
        >
          <Button
            _hover={{ color: "blue.500" }}
            // transition={"0.5s all"}
            color="blue.400"
            rounded={"sm"}
            onClick={() => {
              setActionId(item?.id);
              onEditOpen();
            }}
            size={"xs"}
          >
            <EditIcon />
          </Button>
        </Tooltip>
        <Tooltip
          rounded={"sm"}
          fontSize={"xs"}
          label="Delete"
          bg="#fff"
          color={"red.500"}
          placement="top"
        >
          <Button
            onClick={() => {
              setActionId(item?.id);
              setDeleteAlert(true);
            }}
            _hover={{ color: "red.500" }}
            // transition={"0.5s all"}
            color="red.300"
            rounded={"sm"}
            size={"xs"}
          >
            <DeleteIcon />
          </Button>
        </Tooltip>
      </Box>
    ),
  }));

  return false ? (
    <FullscreenLoaders />
  ) : (
    <Box>
      <Box display={"flex"} justifyContent={"end"} mb={4}>
        {/* <Input
          type="search"
          width={300}
          placeholder="Search..."
          size="sm"
          rounded="sm"
          focusBorderColor="green.500"
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
        /> */}

        <Box display={"flex"} gap={2} as="span">
          <SetDisplayOrder data={filteredData} />
          <Button
            leftIcon={<AddIcon />}
            onClick={onOpen}
            size={"sm"}
            // width={"44.5%"}
            fontSize={"xs"}
            rounded={"sm"}
            colorScheme="forestGreen"
          >
            Add key merits
          </Button>
        </Box>
        <KeyMeritsAdd
          icons={prepopData?.icons}
          id={id}
          isOpen={isOpen}
          onClose={onClose}
          firstField={firstField}
        />

        <KeyMeritsEdit
          icons={prepopData?.icons}
          id={id}
          actionId={actionId}
          isOpen={isEditOpen}
          onClose={onEditCloseOpen}
          firstField={firstField}
          data={IODetails?.keyMerits}
        />
      </Box>
      <DataTable
        emptyMessage={`We don't have any key merit `}
        tableHeadRow={tableHeadRow}
        data={extractedArray}
        // setData={setExtractedArray}
        isLoading={false}
        viewActionId={actionId}
        setViewActionId={setActionId}
        // totalPages={10}

        setMouseEnteredId={setMouseEnteredId}
        setMouseEntered={setMouseEntered}
      />

      {/* <HStack justifyContent={"flex-end"}>
        <Button
          ps={8}
          pe={8}
          colorScheme="forestGreen"
          size={"sm"}
          rounded={"sm"}
          onClick={() => enableNextTab(index)}
        >
          Next
        </Button>
      </HStack> */}
      <CustomAlertDialog
        onClose={() => setDeleteAlert(false)}
        isOpen={deleteAlert}
        message={"Are you sure you want to delete key merit?"}
        alertHandler={handleDelete}
        isLoading={isBtnLoading}
      />
    </Box>
  );
};

export default KeyMerits;
