import { ViewIcon } from "@chakra-ui/icons";
import {
  Badge,
  Box,
  Button,
  HStack,
  Input,
  Select,
  Text,
  Tooltip,
  useDisclosure,
  useToast,
} from "@chakra-ui/react";
import React, { useContext, useEffect, useRef, useState } from "react";
import { LuFileSpreadsheet } from "react-icons/lu";
import { useNavigate } from "react-router-dom";
import CustomAlertDialog from "../../../Components/CustomAlertDialog";
import NormalTable from "../../../Components/DataTable/NormalTable";
import Pagination from "../../../Components/Pagination";
import {
  exportToExcelNew,
  generateSerialNumber,
} from "../../../Constants/Constants";
import { INVESTOR_TABLE_PAGINATION } from "../../../Constants/Paginations";
import GlobalStateContext from "../../../Contexts/GlobalStateContext";
import { OPACITY_ON_LOAD } from "../../../Layout/animations";
import { useGetInvestorsQuery } from "../../../Services/investor.details.service";
import InvestmentDetailsEdit from "./InvestmentDetailsEdit";

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

const InvestorDetails = () => {
  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(INVESTOR_TABLE_PAGINATION?.size);
  const [currentPage, setCurrentPage] = useState(
    INVESTOR_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: investorDetails,
    isLoading: investorDetailsLoading,
    error,
  } = useGetInvestorsQuery(
    {
      page: debouncedSearchTerm ? undefined : currentPage, // Omit pagination for search
      size: debouncedSearchTerm ? undefined : pageSize, // Omit pagination for search userStatus KYCStatus investorType_xid
      search: debouncedSearchTerm,
      userStatus: status,
      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 No",
    "Client ID",
    "First Name",
    "Last Name",
    "Country",
    "Phone Number",
    "E-mail ID",
    // "Type",
    "Wallet Balance",
    "Investor Portfolio",
    "KYC Status",
    // "Status",
    "Action",
  ];

  // ====================================================[Table Filter]================================================================
  const exportInvestor = investorDetails?.data?.rows?.map((item) => ({
    Id: parseInt(item?.id, 10) || item?.id, // Convert to integer, fallback to string if conversion fails
    "Client ID": item?.clientReference_id, // This is likely a string
    "First Name": item?.principal?.firstName,
    "Last Name": item?.principal?.lastName,
    Country: item?.country?.countryName,
    "Phone Number": item?.principal?.mobileNumber, // Skipping integer conversion, as this is likely a string
    "E-mail ID": item?.principal?.emailAddress,
    "Wallet Balance":parseFloat(item?.WalletBalance_InInvCur || 0).toLocaleString(undefined, {
      minimumFractionDigits: 2, 
      maximumFractionDigits: 2, 
    }), // Skipping integer conversion, as this is likely a string
    "Investor Portfolio": parseFloat(item?.Portfolio_InInvCur || 0).toLocaleString(undefined, {
      minimumFractionDigits: 2, 
      maximumFractionDigits: 2, 
    }),
    // Type: item?.investor_type?.investorTypeName,
    // Status: item.ioStatus ? "Ban" : "Unban",
    "KYC Status": item.KYCStatus ? "Completed" : "Not complete",
  }));

  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>
    // ),
    // Status: (
    //   <Box w={"auto"} isTruncated={true}>
    //     <Badge
    //       fontWeight={"700"}
    //       textTransform={"none"}
    //       colorScheme={item.ioStatus ? "red" : "green"}
    //       px={2}
    //       py={0.5}
    //     >
    //       {item.ioStatus ? "Ban" : "Unban"}
    //     </Badge>
    //   </Box>
    // ),
    "Wallet Balance": (
      <Box
        display={"flex"}
        justifyContent={"end"}
        w={"130px"}
        isTruncated={true}
      >
        <Text as={"span"} color={"teal.900"}>
          {/* {formatCurrency(removeTrailingZeros(item?.investorAmount))}  */}
          {parseFloat(item?.WalletBalance_InInvCur || 0).toLocaleString(
            undefined,
            {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            }
          )}
          <Badge ms={1} colorScheme="green">
            {item?.currencyCode}
          </Badge>
        </Text>
      </Box>
    ),
    "Investor Portfolio": (
      <Box
        display={"flex"}
        justifyContent={"end"}
        w={"130px"}
        isTruncated={true}
      >
        <Text as={"span"} color={"teal.900"}>
          {parseFloat(item?.Portfolio_InInvCur || 0).toLocaleString(undefined, {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
          })}
          <Badge ms={1} colorScheme="green">
            {item?.currencyCode}
          </Badge>
        </Text>
      </Box>
    ),
    "KYC Status": (
      <Box w={"auto"} display={"flex"} alignItems={"center"} isTruncated={true}>
        <Text
          as={"span"}
          fontWeight={"700"}
          textTransform={"none"}
          color={item?.KYCStatus === true ? "green" : "yellow.500"}
          px={2}
          py={0.5}
          variant={"solid"}
        >
          {/* {item.KYCStatus ? "Completed" : "Not complete"} */}
          {item?.KYCStatus === true ? "Completed" : "Not Completed"}
        </Text>
      </Box>
    ),
    Action: (
      <Box display={"flex"} justifyContent={"center"} gap={2}>
        <Tooltip
          rounded={"sm"}
          fontSize={"xs"}
          label="View"
          bg="#fff"
          color={"green.500"}
          placement="top"
        >
          <Button
            isDisabled={item.ioStatus}
            onClick={() => {
              navigate(`/investor-details/profile-view/${item.id}`);
            }}
            // _hover={{ color: "green.500" }}
            // transition={"0.5s all"}
            // color="green.300"
            colorScheme="green"
            rounded={"sm"}
            size={"xs"}
          >
            <ViewIcon />
          </Button>
        </Tooltip>
      </Box>
    ),
  }));

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

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

  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 className="col" display={"flex"} alignItems={"center"}>
            <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">Not Completed</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">Bahrain</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>

            <Pagination
              isLoading={investorDetailsLoading}
              pageSize={pageSize}
              setPageSize={setPageSize}
              currentPage={currentPage}
              setCurrentPage={setCurrentPage}
              totalItems={investorDetails?.data?.totalItems}
            />
          </HStack>

          <Button
            onClick={() => exportToExcelNew(exportInvestor, "Investor Details")}
            leftIcon={<LuFileSpreadsheet />}
            colorScheme="forestGreen"
            size={"sm"}
            variant={"outline"}
            rounded={"sm"}
            fontSize={"xs"}
            w={100}
            me={2}
            isDisabled={exportInvestor?.length === 0}
          >
            Export xls
          </Button>
        </HStack>
        <InvestmentDetailsEdit
          id={actionId}
          isOpen={isEditOpen}
          onClose={onEditClose}
          thirdField={thirdField}
        />
      </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 InvestorDetails;
