import { Badge, Box, HStack, Input, Select, Text, useToast } from "@chakra-ui/react";
import React, { useContext, useEffect, useState } from "react";
import { OPACITY_ON_LOAD } from "../../Layout/animations";
import GlobalStateContext from "../../Contexts/GlobalStateContext";
import CustomAlertDialog from "../../Components/CustomAlertDialog";
import NormalTable from "../../Components/DataTable/NormalTable";
import { useGetDashboardMasterQuery } from "../../Services/dashboard.service";
import { generateSerialNumber } from "../../Constants/Constants";

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

const InvestmentOpportunities = ({ showSearch = true, selectStyle = {} }) => {
  const toast = useToast();
  const { opportunities, setOpportunities, slideFromRight } =
    useContext(GlobalStateContext);
  const [searchTerm, setSearchTerm] = useState("");
  const [isLoading, setIsLoading] = useState(true);
  const [deleteAlert, setDeleteAlert] = useState(false);
  const [actionId, setActionId] = useState(null);
  const [filter, setFilter] = useState(null);

  const { data, error } = useGetDashboardMasterQuery();

  useEffect(() => {
    const timer = setTimeout(() => setIsLoading(false), 1500);
    return () => clearTimeout(timer);
  }, []);

  const tableHeadRow = [
    "Sr No",
    "Investors",
    "Amount Remaining %",
    "Total Deal Size",
    "No of Views",
  ];

  const filteredData =
    data?.data?.investmentOpportunity?.openOpportunityDetails?.filter((item) =>
      item?.Investment_name?.toLowerCase().includes(searchTerm.toLowerCase())
    );

  const extractedArray = filteredData?.map((item, index) => ({
    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"
      >
        {index + 1}
      </Text>
    ),
    Investors: (
      <Box w={"auto"} isTruncated>
        <Text as={"span"} color={"teal.900"}>
          {item?.Investment_name}
        </Text>
      </Box>
    ),
    "Amount Remaining %": (
      <Box w={"90px"} textAlign={'end'} isTruncated>
        <Text as={"span"} color={"teal.900"}>
          {parseFloat(item?.Amount_remaining_per || 0).toLocaleString(
            undefined,
            {
              minimumFractionDigits: 2,
              maximumFractionDigits: 2,
            }
          )}<Badge ms={1} colorScheme="green">%</Badge>
        </Text>
      </Box>
    ),
    "Total Deal Size": (
      <Box w={"auto"} isTruncated>
        <Text as={"span"} color={"teal.900"}>
          <Badge me={1} ms={1} colorScheme="green">$</Badge>{parseFloat(item?.Deal_size || 0).toLocaleString(undefined, {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
          })}
        </Text>
      </Box>
    ),
    "No of Views": (
      <Box w={"auto"} isTruncated>
        <Text as={"span"} color={"teal.900"}>
          {filter === "last30days"
            ? item?.Views_mtd
            : filter === "last7days"
            ? item?.Views_last_7_days
            : item?.Views_today}
        </Text>
      </Box>
    ),
  }));

  return (
    <Box {...OPACITY_ON_LOAD} overflowY={"scroll"}>
      <Box bg="white.500" display="flex" justifyContent="space-between">
        {showSearch && (
          <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>
        )}
        <Box display="flex" alignItems="center" justifyContent="end" w="100%">
          <Select
            {...selectStyle}
            //  placeholder="Select"
            size="xs"
            rounded={2}
            display="flex"
            alignItems="center"
            w={120}
            h="25px"
            _focus={{
              outline: "none",
              border: "1px solid #ccc",
              boxShadow: "none",
            }}
            onChange={(e) => setFilter(e.target.value)}
          >
            <option value="today" selected>
              Today
            </option>
            <option value="last7days">Last 7 day&rsquo;s</option>
            <option value="last30days">Last 30 day&rsquo;s</option>
          </Select>
        </Box>
      </Box>

      <NormalTable
        emptyMessage={"We don't have any details"}
        tableHeadRow={tableHeadRow}
        data={extractedArray}
        isLoading={isLoading}
        viewActionId={actionId}
        setViewActionId={setActionId}
      />

      <CustomAlertDialog
        onClose={() => setDeleteAlert(false)}
        isOpen={deleteAlert}
        message={"Are you sure you want to delete this opportunity?"}
        isLoading={isLoading}
      />
    </Box>
  );
};

export default InvestmentOpportunities;
