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';

const Destribution = () => {
  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);
    
    const formatDate = (date) => {
      return new Date(date).toLocaleDateString('en-GB', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
      });
    };
    
  useEffect(() => {
    // Simulate loading
    const timer = setTimeout(() => {
      setIsLoading(false);
    }, 1500);

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

    // Table setup
    const tableHeadRow = [
      // "Sr.No",
      "Date",
      "Amount",
      "% of Investment"
    ];

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

  const  extractedArray=filteredData?.map((item, index) => ({
    id: item?.id,
    "Sr.No":  <Text
    justifyContent={"start"}
    as={"span"}
    color={"teal.900"}
    fontWeight={"500"}
    className="d-flex align-items-start web-text-small"
  >{item?.id}</Text>,
    "Date": (
      <Text
        justifyContent={"center"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {formatDate(item.transactionDate)}
      </Text>
    ),
    "Amount": (
      <Text
        justifyContent={"center"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        <Badge ms={1} colorScheme="green" me={1}>$</Badge>
        {`${parseFloat(item.transactionAmount || 0).toLocaleString(undefined, {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
          })}`}
      </Text>
    ),
    "% of Investment": (
      <Text
        justifyContent={"center"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {parseFloat(item.percentage).toFixed(2)}%
      </Text>
    ),
  }));



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

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


  const Total = () => {
    return (
      <Table size="sm">
        <Tbody>
          <Tr  backgroundColor="gray.50">
            <Th
              textAlign={"center"}
              p={3}
              width="60px"
              color={"#004118"}
              whiteSpace="normal"
              wordBreak="normal"
              overflowWrap="normal"
            >
              Total
            </Th>
            <Th
              textAlign={"center"}
              p={3}
              width="90px"
              color={"#004118"}
              whiteSpace="normal"
              wordBreak="normal"
              overflowWrap="normal"
            >
              
            <Badge ms={1} colorScheme="green" me={1}>$</Badge>{IODetails?.total_distributeToInvestor_amt?.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
            </Th>
            <Th
              textAlign={"center"}
              p={3}
              width="100px"
              color={"#004118"}
              whiteSpace="normal"
              wordBreak="normal"
              overflowWrap="normal"
            >
              {" "}
            </Th>
          </Tr>
        </Tbody>
      </Table>
    );
  };




  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>
    </Box>

    <NormalTable
      centered={true}
      emptyMessage={`We don't have any Sponers`}
      tableHeadRow={tableHeadRow}
      data={extractedArray} 
      isLoading={isLoading}
      viewActionId={actionId}
      setViewActionId={setActionId}
      total={<Total/>}
      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 Destribution