import {
  Badge,
  Box,
  HStack,
  Input,
  Text,
  useDisclosure,
  useToast
} from "@chakra-ui/react";
import React, { useContext, useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import CustomAlertDialog from "../../Components/CustomAlertDialog";
import NormalTable from "../../Components/DataTable/NormalTable";
import Pagination from "../../Components/Pagination";
import ToastBox from "../../Components/ToastBox";
import GlobalStateContext from "../../Contexts/GlobalStateContext";
import { OPACITY_ON_LOAD } from "../../Layout/animations";
import { debounce } from "../Master/Sponser/AddSponser";
// import InvestmentDetailsEdit from "./InvestmentDetailsEdit";
import { generateSerialNumber } from "../../Constants/Constants";
import { TABLE_PAGINATION } from "../../Constants/Paginations";
import { useGetInvestorsQuery } from "../../Services/investor.details.service";

const FawateerRequest = () => {
  const navigate = useNavigate();
  const toast = useToast();
  const thirdField = useRef();
  const { InvestorDetails, setInvestorDetails, slideFromRight } =
    useContext(GlobalStateContext);
  const [isLoading, setIsLoading] = useState(true);
  const [deleteAlert, setDeleteAlert] = useState(false);
  const [actionId, setActionId] = useState(false);
  const [mouseEntered, setMouseEntered] = useState(false);
  const [mouseEnteredId, setMouseEnteredId] = useState("");
  const {
    isOpen: isEditOpen,
    onOpen: onEditOpen,
    onClose: onEditClose,
  } = useDisclosure();
  const btnRef = React.useRef();

  // =========================== [Use State] =============================
  const [pageSize, setPageSize] = useState(TABLE_PAGINATION?.size);
  const [currentPage, setCurrentPage] = useState(TABLE_PAGINATION?.page);
  const [searchTerm, setSearchTerm] = useState("");
  const [debouncedSearchTerm, setDebouncedSearchTerm] = useState("");

  // Debounce the search term to avoid making a request on every keystroke
  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedSearchTerm(searchTerm);
    }, 500); // Adjust delay as needed
    return () => {
      clearTimeout(handler);
    };
  }, [searchTerm]);

  const {
    data: investorDetails,
    isLoading: investorDetailsLoading,
    error,
  } = useGetInvestorsQuery(
    {
      page: debouncedSearchTerm ? undefined : currentPage, // Omit pagination for search
      size: debouncedSearchTerm ? undefined : pageSize, // Omit pagination for search
      search: debouncedSearchTerm,
    },
    {
      skip: debouncedSearchTerm === "" && searchTerm !== "", // Skip if search is empty and it's not the initial request
    }
  );

  useEffect(() => {
    // Simulate loading
    const timer = setTimeout(() => {
      setIsLoading(false);
    }, 1500);

    // Cleanup the timer on component unmount
    return () => clearTimeout(timer);
  }, []);

  // ====================================================[Table Setup]================================================================
  const tableHeadRow = [
    "Sr No",
    "Client ID",
    "First Name",
    "Last Name",
    "Country",
    "Phone Number",
    "E-mail ID",
    // "Type",
    // "KYC Status",
    "Approval Status",
  ];

  const handleUpdateStatus = debounce((id) => {
    setInvestorDetails((prevData) =>
      prevData.map((InvestorDetails) =>
        InvestorDetails.id === id ? { ...InvestorDetails } : InvestorDetails
      )
    );
    toast({
      render: () => <ToastBox message={"Status changed succesfully.!"} />,
    });
  }, 300);

  // ====================================================[Table Filter]================================================================
  const filteredData = investorDetails?.data?.rows?.filter((item) => {
    // Filter by name (case insensitive)
    const name = [
      item?.principal?.firstName,
      item?.principal?.lastName,
      item?.country?.countryName,
      item?.principal?.mobileNumber,
      item?.principal?.emailAddress,
    ]
      .filter(Boolean)
      .join(" ");
    const searchLower = searchTerm.toLowerCase();
    const nameMatches = name?.toLowerCase().includes(searchLower);

    // Filter by status
    // const status = item.status;
    // const statusLower = status ? "active" : "inactive";

    // const statusMatches =
    //   statusFilter === "all" ||
    //   (statusFilter === "active" && status === true) ||
    //   (statusFilter === "inactive" && status === false);

    return nameMatches;
  });

  const customHeaders = [
    { label: "ID", key: "id" },
    { label: "Client ID", key: "clientReference_id" },
    { label: "First Name", key: "principal.firstName" }, // Nested property
    { label: "Last Name", key: "principal.lastName" }, // Nested property
    { label: "Country", key: "country.countryName" }, // Nested property
    { label: "Phone Number", key: "principal.mobileNumber" }, // Nested property
    { label: "E-mail ID", key: "principal.emailAddress" }, // Nested property
    { label: "Type", key: "investor_type.investorTypeName" }, // Nested property
    { label: "Status", key: "ioStatus" }, // Simple property
    { label: "KYC Status", key: "KYCStatus" }, // Simple property
  ];

  const extractedArray = investorDetails?.data?.rows?.map((item, idx) => ({
    id: item?.id,
    "Sr No": (
      <Text
        w={"24px"}
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"gray.600"}
        className="d-flex align-items-center fw-bold web-text-small"
      >
        {/* {item.id} */}
        {generateSerialNumber(idx, currentPage, pageSize)}
      </Text>
    ),
    "Client ID": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item.clientReference_id}
        </Text>
      </Box>
    ),
    "First Name": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item?.principal?.firstName}
        </Text>
      </Box>
    ),
    "Last Name": (
      <Box w={"70px"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item?.principal?.lastName}
        </Text>
      </Box>
    ),
    Country: (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item?.country?.countryName}
        </Text>
      </Box>
    ),
    "Phone Number": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item?.principal?.mobileNumber}
        </Text>
      </Box>
    ),
    "E-mail ID": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item?.principal?.emailAddress}
        </Text>
      </Box>
    ),
    Type: (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"}>
          <Badge
            color={"forestGreen.500"}
            variant={"ghost"}
            fontWeight={"700"}
            px={2}
            py={0.5}
          >
            {item?.investor_type?.investorTypeName}
          </Badge>
        </Text>
      </Box>
    ),
    "Approval Status": (
      <Box w={"auto"} isTruncated={true}>
        <Badge
          fontWeight={"700"}
          textTransform={"none"}
          colorScheme={item.ioStatus ? "red" : "purple"}
          px={2}
          py={0.5}
        >
          Approved
        </Badge>
      </Box>
    ),
  }));

  const handleDelete = () => {
    const updatedInvestorDetails = InvestorDetails.filter(
      (sponsor) => sponsor.id !== actionId
    );

    setTimeout(() => {
      setInvestorDetails(updatedInvestorDetails);
      setDeleteAlert(false);
      setIsLoading(false);
    }, 100);
    setIsLoading(true);
  };

  const handleEdit = (id) => {
    setActionId(id);
    onEditOpen();
  };

  console.log(investorDetails?.data?.totalItems);

  return (
    <Box {...OPACITY_ON_LOAD} overflowY={"scroll"} height={"100vh"} pb={38}>
      <Box bg="white.500">
        <HStack
          display={"flex"}
          justifyContent={"space-between"}
          ps={1}
          pe={1}
          pb={4}
          pt={4}
          spacing="24px"
        >
          <Input
            mt={1}
            type="search"
            width={300}
            placeholder="Search..."
            size="sm"
            rounded="sm"
            focusBorderColor="green.500"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />

          <HStack display={"flex"} alignItems={"center"}>
            <Pagination
              isLoading={investorDetailsLoading}
              pageSize={pageSize}
              setPageSize={setPageSize}
              currentPage={currentPage}
              setCurrentPage={setCurrentPage}
              totalItems={investorDetails?.data?.totalItems}
            />

            {/* 
          <Button
              leftIcon={<AddIcon />}
              colorScheme="forestGreen"
              size={"sm"}
              rounded={"sm"}
              fontSize={"xs"}
              onClick={()=> navigate('create-request')}
            >
              Create request
            </Button> */}
          </HStack>
        </HStack>
      </Box>

      <NormalTable
        // centered={true}
        emptyMessage={`We don't have any Sponers `}
        tableHeadRow={tableHeadRow}
        data={extractedArray}
        isLoading={investorDetailsLoading}
        viewActionId={actionId}
        setViewActionId={setActionId}
        setMouseEnteredId={setMouseEnteredId}
        setMouseEntered={setMouseEntered}
      />

      <CustomAlertDialog
        onClose={() => setDeleteAlert(false)}
        isOpen={deleteAlert}
        message={"Are you sure you want to delete sponers?"}
        alertHandler={handleDelete}
        isLoading={isLoading}
      />
    </Box>
  );
};

export default FawateerRequest;
