import {
  Avatar,
  Badge,
  Box,
  Button,
  HStack,
  Input,
  Menu,
  MenuButton,
  MenuItem,
  MenuList,
  Portal,
  Select,
  Switch,
  Tag,
  Text,
  Tooltip,
  useToast,
} from "@chakra-ui/react";
import React, { useContext, useEffect, useState } from "react";
import { OPACITY_ON_LOAD } from "../../../Layout/animations";
import NormalTable from "../../../Components/DataTable/NormalTable";
import { HiDotsVertical } from "react-icons/hi";
import {
  Link,
  Navigate,
  Link as RouterLink,
  useParams,
} from "react-router-dom";
import {
  AddIcon,
  DeleteIcon,
  EditIcon,
  EmailIcon,
  ViewIcon,
} from "@chakra-ui/icons";
import Pagination from "../../../Components/Pagination";
import GlobalStateContext from "../../../Contexts/GlobalStateContext";
import CustomAlertDialog from "../../../Components/CustomAlertDialog";
import ToastBox from "../../../Components/ToastBox";
import { debounce } from "../../Master/Sponser/AddSponser";
import { useGetInvestorsDetailsById_InInvCurQuery } from "../../../Services/investor.details.service";

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

const ViewInvestorDetails = () => {
  const toast = useToast();
  const { viewInvestor, setViewInvestor, slideFromRight, InvestorWallet } =
    useContext(GlobalStateContext);
  const [searchTerm, setSearchTerm] = useState("");
  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 [isSwitchOn, setIsSwitchOn] = useState(false);
  const params = useParams();
  const id = params?.id;

  const { data, errors, refetch } = useGetInvestorsDetailsById_InInvCurQuery(
    { id, currencyIn: !isSwitchOn },
    {
      skip: !id,
    }
  );

  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",
    // "Deal Name",
    "IO Name",
    "Sponsor Name",
    "Investment Type",
    "Investment Amount",
    "Percentage",
    "Market Value",
    "Return on Investment",
    "Distribution",
    "Distribution Percent",
    "Total return",
    "Total return on Investment",
    "Status",
    // "Action",
  ];

  // ====================================================[Table Filter]================================================================
  const filteredData = viewInvestor?.filter((item) => {
    // Filter by name (case insensitive)
    const name = item.sponsorName;
    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 = filteredData?.map((item, index) => ({
    id: item?.id,
    "Sr N/O": (
      <Text
        w={"50px"}
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"gray.600"}
        className="d-flex align-items-center fw-bold web-text-small"
      >
        {index + 1}.
      </Text>
    ),
    "IO Name": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item.investmentNameEnglish}
        </Text>
      </Box>
    ),
    "Sponsor Name": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item.sponsorName}
        </Text>
      </Box>
    ),
    "Investment Type": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item.investmentTypeName}
        </Text>
      </Box>
    ),
    "Investment Amount": (
      <Box
        display={"flex"}
        justifyContent={isSwitchOn ? "end" : "start"}
        w={"auto"}
        isTruncated={true}
      >
        <Text as={"span"} color={"teal.900"}>
          {isSwitchOn ? (
            <>
              {parseFloat(item?.investedAmount || 0).toLocaleString(undefined, {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2,
              })}
              <Badge ms={1} colorScheme="green" me={1}>
                {InvestorWallet?.currencyCode_InCur}
              </Badge>
            </>
          ) : (
            <>
              <Badge ms={1} colorScheme="green" me={1}>
                $
              </Badge>
              {parseFloat(item?.investedAmount || 0).toLocaleString(undefined, {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2,
              })}
            </>
          )}
        </Text>
      </Box>
    ),
    Percentage: (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item?.Investor_Holidings} %
        </Text>
      </Box>
    ),
    "Market Value": (
      <Box
        display={"flex"}
        justifyContent={isSwitchOn ? "end" : "start"}
        w={"auto"}
        isTruncated={true}
      >
        <Text as={"span"} color={"teal.900"}>
          {isSwitchOn ? (
            <>
              {parseFloat(item?.MarketValue || 0).toLocaleString(undefined, {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2,
              })}
              <Badge ms={1} colorScheme="green" me={1}>
                {InvestorWallet?.currencyCode_InCur}
              </Badge>
            </>
          ) : (
            <>
              <Badge ms={1} colorScheme="green" me={1}>
                $
              </Badge>
              {parseFloat(item?.MarketValue || 0).toLocaleString(undefined, {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2,
              })}
            </>
          )}
        </Text>
      </Box>
    ),
    "Return on Investment": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item.MarketValue_Per} %
        </Text>
      </Box>
    ),
    Distribution: (
      <Box
        display={"flex"}
        justifyContent={isSwitchOn ? "end" : "start"}
        w={"auto"}
        isTruncated={true}
      >
        <Text as={"span"} color={"teal.900"}>
          {isSwitchOn ? (
            <>
              {parseFloat(item?.DistributionAmountReceived || 0).toLocaleString(
                undefined,
                {
                  minimumFractionDigits: 2,
                  maximumFractionDigits: 2,
                }
              )}
              <Badge ms={1} colorScheme="green" me={1}>
                {InvestorWallet?.currencyCode_InCur}
              </Badge>
            </>
          ) : (
            <>
              <Badge ms={1} colorScheme="green" me={1}>
                $
              </Badge>
              {parseFloat(item?.DistributionAmountReceived || 0).toLocaleString(
                undefined,
                {
                  minimumFractionDigits: 2,
                  maximumFractionDigits: 2,
                }
              )}
            </>
          )}
        </Text>
      </Box>
    ),
    "Distribution Percent": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item?.Distribution_Per} %
        </Text>
      </Box>
    ),
    "Total return": (
      <Box
        display={"flex"}
        justifyContent={isSwitchOn ? "end" : "start"}
        w={"auto"}
        isTruncated={true}
      >
        <Text as={"span"} color={"teal.900"}>
          {isSwitchOn ? (
            <>
              {parseFloat(item?.TotalReturn || 0).toLocaleString(undefined, {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2,
              })}
              <Badge ms={1} colorScheme="green" me={1}>
                {InvestorWallet?.currencyCode_InCur}
              </Badge>
            </>
          ) : (
            <>
              <Badge ms={1} colorScheme="green" me={1}>
                $
              </Badge>
              {parseFloat(item?.TotalReturn || 0).toLocaleString(undefined, {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2,
              })}
            </>
          )}
        </Text>
      </Box>
    ),
    "Total return on Investment": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item.TotalReturn_Per} %
        </Text>
      </Box>
    ),
    Status: (
      <Badge
        rounded={"full"}
        pt={1}
        pb={1}
        ps={4}
        pe={4}
        mt={1.5}
        mb={1.5}
        textTransform={"none"}
        // variant={"solid"}
        colorScheme={
          item?.statusAdmin === "Draft"
            ? "gray"
            : item?.statusAdmin === "Processing"
            ? "yellow"
            : item?.statusAdmin === "Open"
            ? "blue"
            : item?.statusAdmin === "Closed"
            ? "green"
            : item?.statusAdmin === "Exited"
            ? "red"
            : item?.statusAdmin === "Canclled"
            ? "orange"
            : "purple"
        }
        boxShadow={"0 4px 6px rgba(0, 0, 0, 0.1)"} // Adjusted shadow
      >
        {item?.statusAdmin}
      </Badge>
    ),
    Action: (
      <Box display={"flex"} justifyContent={"space-between"}>
        <Tooltip
          rounded={"sm"}
          fontSize={"xs"}
          label="View"
          bg="#fff"
          color={"green.500"}
          placement="top"
        >
          <Button
            _hover={{ color: "green.500" }}
            // transition={"0.5s all"}
            color="green.300"
            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);
  };

  const switchOnChangeHandle = () => {
    setIsSwitchOn(!isSwitchOn); // Toggle the switch state
    setViewInvestor(data?.data?.portfolio);
  };

  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
            type="search"
            width={300}
            placeholder="Search..."
            size="sm"
            rounded="sm"
            focusBorderColor="green.500"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
          
          {/* 
          <Box
            as="button"
            display="flex"
            alignItems="center"
            justifyContent={isSwitchOn ? "flex-end" : "flex-start"} // Use this if needed
            width="155px"
            height="30px"
            borderRadius="20px"
            backgroundColor={isSwitchOn ? "#004118" : "#ef0000"}
            onClick={switchOnChangeHandle} // Correct handler name
            position="relative"
            fontSize="13px"
            fontWeight="100"
            transition="background-color 0.2s"
            _before={{
              content: '""',
              position: "absolute",
              width: "20px",
              height: "20px",
              borderRadius: "50%",
              backgroundColor: "#FFF",
              boxShadow: "0 2px 4px rgba(0, 0, 0, 0.2)",
              transform: isSwitchOn ? "translateX(128px)" : "translateX(0)",
              transition: "transform 0.2s",
              left: "4px",
            }}
          >
            <Text
              fontWeight="400"
              zIndex={1}
              position="absolute"
              mb={0}
              color="#fff"
              left={isSwitchOn ? "10px" : "auto"}
              right={isSwitchOn ? "auto" : "10px"}
            >
              {isSwitchOn ? "Investor Currency" : "Investor Currency"}
            </Text>
          </Box> */}
          {/* <HStack display={"flex"} alignItems={"center"}>
            <Pagination totalItems={10} />
          </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}
      />
    </Box>
  );
};

export default ViewInvestorDetails;
