import {
  Badge,
  Box,
  HStack,
  Input,
  Select,
  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 ToastBox from "../../../../Components/ToastBox";
import { TABLE_PAGINATION } from "../../../../Constants/Paginations";
import GlobalStateContext from "../../../../Contexts/GlobalStateContext";
import { OPACITY_ON_LOAD } from "../../../../Layout/animations";
import { useGetbanInvestorQuery } from "../../../../Services/ban.investor.service";
import { debounce } from "../../../Master/Sponser/AddSponser";
import ReasonBanModal from "./ReasonBanModal";
import Pagination from "../../../../Components/Pagination";

const formatDate = (date) => new Date(date).toLocaleDateString(); // Simple date formatter

const BankInvestor = () => {
  const navigate = useNavigate();
  const toast = useToast();
  const thirdField = useRef();
  const { bankInvestor, setBankInvestor, 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: isOpen, onOpen: onOpen, onClose: onClose } = useDisclosure();

  const formatDate = (date) => {
    return new Date(date).toLocaleDateString("en-GB", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
    });
  };

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

  const [status, setStatus] = useState("");
  const [kyc, setKyc] = useState("");
  const [country, setCountry] = 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,
    isLoading: unbanLoading,
    error,
    refetch,
  } = useGetbanInvestorQuery(
    {
      page: debouncedSearchTerm ? undefined : currentPage, // Omit pagination for search
      size: debouncedSearchTerm ? undefined : pageSize, // Omit pagination for search
      search: debouncedSearchTerm,
      KYCStatus: kyc,
      country_xid: country,
    },
    {
      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 N/O",
    "Date",
    "Client ID",
    "First Name",
    "Last Name",
    "Country",
    "Phone Number",
    "E-mail ID",
    "KYC Status",
    "Action",
  ];

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

  // ====================================================[Table Filter]================================================================
  const filteredData = data?.data?.rows?.filter((item) => {
    // Filter by name (case insensitive)
    const name = item?.clientReference_id;
    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 extractedArray = data?.data?.rows?.map((item) => ({
    id: item?.id,
    "Sr N/O": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"gray.600"}
        className="d-flex align-items-center fw-bold web-text-small"
      >
        {item.id}
      </Text>
    ),
    Date: (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {formatDate(item?.date)}
        </Text>
      </Box>
    ),
    "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?.firstName}
        </Text>
      </Box>
    ),
    "Last Name": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item?.lastName}
        </Text>
      </Box>
    ),
    Country: (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item?.country}
        </Text>
      </Box>
    ),
    "Phone Number": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item?.phoneNumber}
        </Text>
      </Box>
    ),
    "E-mail ID": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item?.emailAddress}
        </Text>
      </Box>
    ),
    "KYC Status": (
      <Box w={"auto"} isTruncated={true}>
        <Badge
          fontWeight={"500"}
          textTransform={"none"}
          color={item?.KYCStatus === false ? "red" : "blue"}
          px={2}
          py={0.5}
          variant={"ghost"}
        >
          {item?.KYCStatus === true ? "Completed" : "Incompleted"}
        </Badge>
      </Box>
    ),
    Action: (
      <Box w={"auto"} isTruncated={true}>
        <Badge
          cursor={"pointer"}
          fontWeight={"500"}
          textTransform={"none"}
          colorScheme={"red"}
          px={2}
          py={0.5}
          onClick={() => {
            setActionId(item?.id);
            onOpen();
          }}
        >
          Ban Investor
        </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();
  };

  return (
    <Box {...OPACITY_ON_LOAD}>
      <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={unbanLoading}
              pageSize={pageSize}
              setPageSize={setPageSize}
              currentPage={currentPage}
              setCurrentPage={setCurrentPage}
              totalItems={data?.data?.totalItems}
            />
            {/* <Select
              focusBorderColor="green.500"
              size={"sm"}
              fontSize={"xs"}
              cursor={"pointer"}
              onChange={(e) => setStatus(e.target.value)}
              value={status}
            >
              <option value="" defaultValue={""} disabled hidden>
                Status
              </option>

              <option value="">Status</option>
              <option value="0">Ban</option>
              <option value="1">UnBan</option>
            </Select> */}

            <Select
              focusBorderColor="green.500"
              size={"sm"}
              fontSize={"xs"}
              cursor={"pointer"}
              onChange={(e) => setKyc(e.target.value)}
              value={kyc}
            >
              <option value="" defaultValue={""} disabled hidden>
                KYC Status
              </option>
              <option value="">KYC Status</option>
              <option value="0">Incompleted</option>
              <option value="1">Completed</option>
            </Select>

            <Select
              focusBorderColor="green.500"
              size={"sm"}
              fontSize={"xs"}
              cursor={"pointer"}
              onChange={(e) => setCountry(e.target.value)}
              value={country}
            >
              <option value="" defaultValue={""} disabled hidden>
                Country
              </option>
              <option value="">All</option>
              <option value="1">Behrain</option>
              <option value="2">Kuwait</option>
              <option value="3">Oman</option>
              <option value="4">Qatar</option>
              <option value="5">Saudi arabia</option>
              <option value="6">United arab emirates</option>
            </Select>
          </HStack>
        </HStack>
      </Box>

      <NormalTable
        emptyMessage={`We don't have any Sponers `}
        tableHeadRow={tableHeadRow}
        data={extractedArray}
        isLoading={isLoading}
        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}
      />
      <ReasonBanModal isOpen={isOpen} onClose={onClose} id={actionId} />
    </Box>
  );
};

export default BankInvestor;
