import React, { useContext, useEffect, useRef, useState } from "react";
import GlobalStateContext from "../../../Contexts/GlobalStateContext";
import {
  Box,
  HStack,
  Input,
  Text,
  Table,
  Tbody,
  Th,
  Tr,
  Avatar,
  useDisclosure,
  Button,
  Badge,
} from "@chakra-ui/react";
import { OPACITY_ON_LOAD } from "../../../Layout/animations";
import Pagination from "../../../Components/Pagination";
import NormalTable from "../../../Components/DataTable/NormalTable";
import CustomAlertDialog from "../../../Components/CustomAlertDialog";
import { formatDatee } from "../../../Components/FormField";
import { AddIcon } from "@chakra-ui/icons";
import AddIONav from "./AddIONav";
import { formatDate } from "../../Master/Sponser/Sponsers";
import { LuFileSpreadsheet } from "react-icons/lu";
import { exportToExcel, exportToExcelNew } from "../../../Constants/Constants";

const IONAVDetails = () => {
  const { navDetails, setNavDetails, IODetails } =
    useContext(GlobalStateContext);
  const firstField = useRef();
  const { isOpen, onOpen, onClose } = useDisclosure();
  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("");

  console.log(IODetails?.ioNAVHistory);

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

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

  // Table setup
  const tableHeadRow = [
    // "Sr.No",
    "Valuation Date",
    "NAV",
    "Last NAV update",
    "Investment Closed",
    "Comments",
    "Update by ",
    // "Update On",
  ];

  // Table filter
  const filteredData = IODetails?.ioNAVHistory
    ?.filter((item) => {
      const name = item.transactionType;
      const searchLower = searchTerm.toLowerCase();
      const nameMatches = name.toLowerCase().includes(searchLower);
      return nameMatches;
    })
    .reverse()
    // .sort((b, a) => new Date(a.transactionDate) - new Date(b.transactionDate));

  const extractedArray = filteredData?.map((item, index) => ({
    id: item?.id,
    "Sr.No": index + 1,
    "Valuation Date": (
      <Text
        justifyContent={"center"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {/* {/ {formatDatee(item.transactionDate)} /} */}
        {formatDate(item?.transactionDate)}
      </Text>
    ),
    NAV: (
      <Text
        justifyContent={"center"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        
        className="d-flex align-items-center web-text-small"
      >
        {/* {/ {`${item.transactionAmount}`} /} */}
        <Badge ms={1} colorScheme="green" me={1}>$</Badge>
        {`${parseFloat(item.transactionAmount || 0).toLocaleString()}`}
      </Text>
    ),
    "Last NAV update": (
      <Text
        justifyContent={"center"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {item.previousNAVvalue && `${item.previousNAVvalue}`}
      </Text>
    ),
    "Investment Closed": (
      <Text
        justifyContent={"center"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {item.initialNAVvalue && `${item.initialNAVvalue}`}
      </Text>
    ),
    Comments: (
      // <Text
      //   justifyContent={"center"}
      //   as={"span"}
      //   color={"teal.900"}
      //   fontWeight={"500"}
      //   className="d-flex align-items-center web-text-small"
      // >
      //   {item.comments}
      // </Text>
      <Text
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        maxWidth="200px" // Adjust width as needed
        display="block" // Ensure block display for proper truncation
        overflow="hidden"
        isTruncated
        textOverflow="ellipsis"
      >
        {item.comments}
      </Text>
    ),
    "Update by ": (
      <Text
        justifyContent={"center"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        gap={2}
        className="d-flex align-items-center web-text-small"
      >
        <Avatar
          size="sm"
          name={item.creator?.firstName}
          src={item.creator?.profilePhoto}
        />
        {item.creator?.firstName}
      </Text>
    ),
    "Update On": (
      <Text
        justifyContent={"center"} 
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {formatDate(item.updatedAt)}
      </Text>
    ),
  }));

  const customHeaders = [
    { label: "ID", key: "id" },
    { label: "Valuation Date", key: "transactionDate" },
    { label: "NAV", key: "transactionAmount" },
    { label: "Last NAV update", key: "previousNAVvalue" },

    { label: "Investment Closed", key: "initialNAVvalue" },
    { label: "Comments", key: "comments" },

    // { label: "Update by", key: "creator" },
    { label: "Transaction Type", key: "transactionType" },
    // { label: "Comments", key: "comments" },
    // Add more headers as needed
  ];

  console.log(IODetails?.ioNAVHistory);
  const ioNavExport = IODetails?.ioNAVHistory?.map((item, index) => ({
    "ID": item?.id, // Keep as integer if it's already a number
    "Valuation Date": formatDate(item?.transactionDate), // Assuming this is a date, no conversion needed
    "NAV": parseFloat(item?.transactionAmount) || 0, // Convert to float
    "Last NAV update": parseFloat(item?.previousNAVvalue) || 0, // Convert to float
    "Investment Closed": parseFloat(item?.initialNAVvalue) || 0, // Convert to float
    "Comments": item?.comments, // Keep as string
    "Transaction Type": item?.transactionType, // Keep as string
    "Update by ": item?.creator?.firstName, // Keep as string
    // "Update On": formatDate(item?.updatedAt) // Assuming this is a date, no conversion needed
  }));

  const handleDelete = () => {
    const updatedNav = navDetails.filter((sponsor) => sponsor.id !== actionId);

    setTimeout(() => {
      setNavDetails(updatedNav);
      setDeleteAlert(false);
      setIsLoading(false);
    }, 100);
    setIsLoading(true);
  };

  const handleExport = () => {};

  return (
    <Box {...OPACITY_ON_LOAD} pb={0}>
      <Box bg="white.500">
        <HStack
          display={"flex"}
          justifyContent={"space-between"}
          pb={3}
          spacing="24px"
        >
          <Input
            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"}>
            <Button
              onClick={() =>
                exportToExcelNew(ioNavExport, "Io Nav details")
              }
              leftIcon={<LuFileSpreadsheet />}
              colorScheme="forestGreen"
              size={"sm"}
              variant={"outline"}
              rounded={"sm"}
              fontSize={"xs"}
              isDisabled={ioNavExport?.length === 0}
            >
              Export xls
            </Button>

            {IODetails?.isInvestedAmount ? (
              <Button
                onClick={onOpen}
                leftIcon={<AddIcon />}
                colorScheme="forestGreen"
                size={"sm"}
                rounded={"sm"}
                fontSize={"xs"}
              >
                Add IO Nav
              </Button>
            ) : null}
          </HStack>
        </HStack>
      </Box>

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

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

      <AddIONav isOpen={isOpen} onClose={onClose} firstField={firstField} />
    </Box>
  );
};

export default IONAVDetails;
