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, 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 { debounce } from "./AddIOCharges";

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

const ViewIOTable = () => {
  const navigate = useNavigate();
  const toast = useToast();
  const { IODetails, setIODetails, slideFromRight } =
    useContext(GlobalStateContext);
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");
  // const [isLoading, setIsLoading] = useState(true);
  const [deleteAlert, setDeleteAlert] = useState(false);
  const [actionId, setActionId] = useState(false);
  const [mouseEntered, setMouseEntered] = useState(false);
  const [mouseEnteredId, setMouseEnteredId] = useState("");

  // ===============================[ Paginations ] 
  const [pageSize, setPageSize] = useState(TABLE_PAGINATION?.size);
  const [currentPage, setCurrentPage] = useState(TABLE_PAGINATION?.page);

  // ===============================[ RTK Api calls ]
  const {
    data,
    isLoading,
    error,
  } = useGetIOsQuery({ page: currentPage, size: pageSize });
  console.log(data);

  // ===============================[ Table Header ]
  const tableHeadRow = [
    "IO ID",
    "IO Name",
    "Sponsorer",
    "Investment Type",
    "Goal Amount",
    "Holding Period",
    "IO Status",
    "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;
  });

  console.log(filteredData);

  const extractedArray = filteredData?.map((item, index) => ({
    "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": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          {item.investmentNameEnglish ? item.investmentNameEnglish : "---"}
        </Text>
      </Box>
    ),
    Sponsorer: (
      <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={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          {item?.investmentType?.investmentTypeName ? item.investmentType?.investmentTypeName : "---"}
        </Text>
      </Box>
    ),
    "Goal Amount": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          {item.goalAmount ? item.goalAmount : "---"}
        </Text>
      </Box>
    ),
    "Holding Period": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          {item.holdingPeriod ? item.holdingPeriod : "---"}
        </Text>
      </Box>
    ),
    "IO Status": (
      <Box w={"auto"} isTruncated={true}>
        <Badge
          rounded={"md"}
          pt={0.5}
          pb={0.5}
          ps={4}
          pe={4}
          textTransform={"none"}
          color={
            item?.ioStatus?.statusAdmin === "Draft"
              ? "yellow.500"
              : item.ioStatus === "Pending"
              ? "#6226EF"
              : "#EF3826"
          }
          colorScheme={
            item?.ioStatus?.statusAdmin === "Draft"
              ? "yellow"
              : item.ioStatus?.statusAdmin === "Pending"
              ? "purple"
              : "red"
          }
        >
          {item.ioStatus?.statusAdmin}
        </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" }}
            // transition={"0.5s all"}
            onClick={() => {
              navigate(`/view-io/${item.id}`);
            }}
            color="green.300"
            rounded={"sm"}
            size={"xs"}
          >
            <ViewIcon />
          </Button>
        </Tooltip>

        <Tooltip
          rounded={"sm"}
          fontSize={"xs"}
          label="View"
          bg="#fff"
          color={"green.500"}
          placement="top"
        >
          <Button
            _hover={{ color: "green.500" }}
            // transition={"0.5s all"}
            onClick={() => {
              navigate(`/create-io/${item.id}`);
            }}
            color="green.300"
            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 = () => {};

  console.log(extractedArray);

  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="all" selected disabled hidden defaultChecked>
                Status
              </option>

              <option value="all">All</option>
              <option value="Draft">Draft</option>
              <option value="Cancelled">Cancelled</option>
              <option value="Processing">Processing</option>
              <option value="Open">Open</option>
              <option value="Exited">Exited</option>
              <option value="Closed">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}
      />

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

export default ViewIOTable;
