import {
  Avatar,
  Badge,
  Box,
  Button,
  HStack,
  Input,
  Menu,
  MenuButton,
  MenuItem,
  MenuList,
  Portal,
  Select,
  Switch,
  Tag,
  Text,
  Tooltip,
  useDisclosure,
  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, Link as RouterLink, useNavigate } from "react-router-dom";
import {
  AddIcon,
  CheckIcon,
  CloseIcon,
  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 { useGetIOsQuery } from "../../../Services/io.service";
import { TABLE_PAGINATION } from "../../../Constants/Paginations";
import { formatCurrency } from "../../../Components/CurrencyInput";
import { IoIosPhonePortrait } from "react-icons/io";
import MobileView from "../../../Components/MobileView";
import { ImMobile } from "react-icons/im";
import {
  generateSerialNumber,
  removeTrailingZeros,
} from "../../../Constants/Constants";
// import { debounce } from "./AddIOCharges";

const formatDate = (date) => {
  return new Date(date).toLocaleDateString("en-GB", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
  });
}; // Simple date formatter

const ViewIOTable = () => {
  const navigate = useNavigate();
  const toast = useToast();
  const { IODetails, setIODetails, 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: isOpen, onOpen: onOpen, onClose: onClose } = useDisclosure();

  // ===============================[ Paginations ]
  const [pageSize, setPageSize] = useState(TABLE_PAGINATION?.size);
  const [currentPage, setCurrentPage] = useState(TABLE_PAGINATION?.page);
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("");
  const [debouncedSearchTerm, setDebouncedSearchTerm] = 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]);

  // ===============================[ RTK Api calls ] =============================================
  const { data, isLoading, error } = useGetIOsQuery({
    page: currentPage,
    size: pageSize,
    ioStatus_xid: statusFilter,
    search: debouncedSearchTerm,
  },
  {
    skip: debouncedSearchTerm === "" && searchTerm !== "", // Skip if search is empty and it's not the initial request
  });


  // ===============================[ Table Header ]
  const tableHeadRow = [
    "Sr No.",
    "IO ID",
    "IO Name",
    "Sponsor",
    "Investment Type",
    "Goal Amount",
    "Amount Raised",
    "Closing Date",
    "IO Status",
    // "Preview",
    "Action",
  ];

  // ====================================================[Table Filter]================================================================
  const filteredData = data?.data?.rows?.filter((item) => {
    // Filter by name (case insensitive)
    const name = item.investmentNameEnglish;
    const searchLower = searchTerm.toLowerCase();
    const nameMatches = name.toLowerCase().includes(searchLower);

    // Filter by status
    const status = item?.ioStatus?.statusAdmin;
    const statusMatches =
      statusFilter === "all" ||
      (status && status.toLowerCase() === statusFilter.toLowerCase());

    return nameMatches && statusMatches;
  });

  const extractedArray = data?.data?.rows?.map((item, idx) => ({
    "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>
    ), 
    "IO ID": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          {item.io_id ? item.io_id : "---"}
        </Text>
      </Box>
    ),
    "IO Name": (
      <Tooltip
        hasArrow
        bg="#c6f6d5"
        fontSize={"xs"}
        label={item.investmentNameEnglish ? item.investmentNameEnglish : "---"}
        placement="top-start"
        color={"blue.800"}
        
      >
        <Text
          as={"span"}
          color={"teal.900"}
          fontWeight={"500"}
          maxWidth="100px" // Adjust width as needed
          display="block" // Ensure block display for proper truncation
          overflow="hidden"
          isTruncated
          textOverflow="ellipsis"
          cursor={"pointer"}
        >
          {item.investmentNameEnglish ? item.investmentNameEnglish : "---"}
        </Text>
      </Tooltip>
    ),
    Sponsor: (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          {item?.sponsor?.sponsorName ? item.sponsor?.sponsorName : "---"}
        </Text>
      </Box>
    ),
    "Investment Type": (
      <Box w={"120px"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          {item?.investmentType?.investmentTypeName
            ? item.investmentType?.investmentTypeName
            : "---"}
        </Text>
      </Box>
    ),
    "Goal Amount": (
      <Box w={"100%"} display={"flex"} justifyContent={"start"} alignItems={'center'}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>       
        <Badge ms={1} colorScheme="green" me={1}>
            $
          </Badge>
          {`${parseFloat(item.goalAmount || 0).toLocaleString(undefined, {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
          })}`}
        </Text>
      </Box>
    ),
    "Amount Raised": (
      <Box w={"100%"} display={"flex"} justifyContent={"start"} alignItems={'center'}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          {/* {item.goalAmount
            ? formatCurrency(removeTrailingZeros(item.goalAmount))
            : "---"} */}
            
          <Badge ms={1} colorScheme="green" me={1}>
            $
          </Badge>
          {`${parseFloat(item.totalRaisedAmount || 0).toLocaleString(undefined, {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
          })}`}
        </Text>
      </Box>
    ),
    "Closing Date": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          {/* {item.closingDate ? item.closingDate : "---"} */}
          {formatDate(item.closingDate ? item.closingDate : "---")}
        </Text>
      </Box>
    ),
    "IO Status": (
      <Box w={"auto"} isTruncated={true}>
        <Badge
          rounded={"full"}
          pt={1}
          pb={1}
          ps={4}
          pe={4}
          mt={1.5}
          mb={1.5}
          textTransform={"none"}
          // variant={"solid"}
          colorScheme={
            item?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_DRAFT
              ? "gray"
              : item?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_PROCESSING
              ? "yellow"
              : item?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_OPEN
              ? "blue"
              : item?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_CLOSED
              ? "green"
              : item?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_EXITED
              ? "red"
              : item?.ioStatus?.statusAdmin === import.meta.env.VITE_STATUS_CANCELLED
              ? "orange"
              : "purple"
          }
          boxShadow={"0 4px 6px rgba(0, 0, 0, 0.1)"} // Adjusted shadow
        >
          {item.ioStatus?.statusAdmin}
        </Badge>
      </Box>
    ),
    Preview: (
      <Box display={"flex"} justifyContent={"start"}>
        <Badge
          display={"flex"}
          px={2}
          py={1}
          alignItems={"center"}
          color={"#000"}
          fontWeight={500}
          bg="purple.200"
          onClick={() => {
            setActionId(item.id);
            onOpen();
          }}
          rounded={"sm"}
          size={"xs"}
          variant={"ghost"}
          cursor={"pointer"}
        >
          <ImMobile className="me-1" /> View
        </Badge>
      </Box>
    ),
    Action: (
      <Box display={"flex"} justifyContent={"center"} gap={2}>
        {/* <Tooltip
          rounded={"sm"}
          fontSize={"xs"}
          label="View"
          bg="#fff"
          color={"green.500"}
          placement="top"
        > */}
        <Button
          // _hover={{ color: "green.500" }}
          colorScheme="green"
          // transition={"0.5s all"}
          onClick={() => {
            navigate(`/view-io/${item.id}`);
          }}
          // color="green.300"
          rounded={"sm"}
          size={"xs"}
        >
          <ViewIcon me={2} /> View
        </Button>
        {/* </Tooltip> */}

        {/* <Tooltip
          rounded={"sm"}
          fontSize={"xs"}
          label="Edit"
          bg="#fff"
          color={"blue.500"}
          placement="top"
        >
          <Button
            // _hover={{ color: "green.500" }}
            // transition={"0.5s all"}
            onClick={() => {
              navigate(`/create-io/${item.id}`);
            }}
            // color="green.300"
            colorScheme="blue"
            rounded={"sm"}
            size={"xs"}
          >
            <EditIcon />
          </Button>
        </Tooltip> */}

        {/* <Tooltip
          rounded={"sm"}
          fontSize={"xs"}
          label="Delete"
          bg="#fff"
          color={"red.500"}
          placement="top"
        >
          <Button
            onClick={() => {
              setActionId(item?.id);
              setDeleteAlert(true);
            }}
            _hover={{ color: "red.500" }}
            // transition={"0.5s all"}
            color="red.300"
            rounded={"sm"}
            size={"xs"}
          >
            <DeleteIcon />
          </Button>
        </Tooltip> */}
      </Box>
    ),
  }));

  const handleDelete = () => {};

  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)}
          />

          <HStack display={"flex"} alignItems={"center"}>
            <Select
              onChange={(e) => setStatusFilter(e.target.value)}
              focusBorderColor="green.500"
              size={"sm"}
              fontSize={"xs"}
              cursor={"pointer"}
              value={statusFilter} // Use the value prop here
            >
              <option value="" selected disabled hidden defaultChecked>
                Status
              </option>

              <option value="">All</option>
              <option value="1">Draft</option>
              <option value="6">Cancelled</option>
              <option value="3">Processing</option>
              <option value="2">Open</option>
              <option value="5">Exited</option>
              <option value="4">Closed</option>
            </Select>

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

            {/* <Link to={"/create-io"}>
              <Button
              ps={4}
              pe={4}
                leftIcon={<AddIcon />}
                colorScheme={"green"}
                rounded={"sm"}
                size={"sm"}
                fontSize={'sm'}
              >
                Create IO
              </Button>
            </Link> */}
          </HStack>
        </HStack>
      </Box>

      <NormalTable
        emptyMessage={`We don't have any Sponers `}
        tableHeadRow={tableHeadRow}
        data={extractedArray}
        isLoading={isLoading}
        viewActionId={actionId}
        setViewActionId={setActionId}
        // totalPages={10}

        setMouseEnteredId={setMouseEnteredId}
        setMouseEntered={setMouseEntered}
      />

      {/* <MobileView isOpen={isOpen} onClose={onClose} actionId={actionId} /> */}

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

export default ViewIOTable;
