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, useRef, useState } from "react";
import { OPACITY_ON_LOAD } from "../../../Layout/animations";
import DataTable from "../../../Components/DataTable/DataTable";
import { HiDotsVertical } from "react-icons/hi";
import { Link, Link as RouterLink, useNavigate } from "react-router-dom";
import { AddIcon, EditIcon, EmailIcon } 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 { formatDate } from "../../../Components/Functions/UTCConvertor";
import EditExchangeRate from "./EditExchangeRate";
import ExchangeHistory from "./ExchangeHistroy";
import { useGetAllExchangeRatesQuery } from "../../../Services/exchange.rate.service";
import { TABLE_PAGINATION } from "../../../Constants/Paginations";
import NormalTable from "../../../Components/DataTable/NormalTable";
import { MdHistory } from "react-icons/md";
import { formatCurrency } from "../../../Components/CurrencyInput";

const ExchangeRate = () => {
  const toast = useToast();
  const btnRef = useRef();
  const navigate = useNavigate();
  const { slideFromRight, rateExchange, setRateExchange } =
    useContext(GlobalStateContext);
  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("");

  const { isOpen, onOpen, onClose } = useDisclosure();

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

  const {
    data,
    isLoading: isExchangeRateLoading,
    errors,
  } = useGetAllExchangeRatesQuery({ page: currentPage, size: pageSize });

  console.log(data?.data);

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

  const filteredData = data?.data?.filter((item) => {
    const name = item?.fromCurrency?.currencyCode;
    const searchLower = searchTerm.toLowerCase();
    const nameMatches = name.toLowerCase().includes(searchLower);

    return nameMatches;
  });

  // ====================================================[Table Setup]================================================================
  const tableHeadRow = [
    "Sr.No",
    "From Currency",
    "To Currency",
    "Effective From",
    "Rate",
    "Action",
  ];

  const extractedArray = filteredData?.map((item, index) => ({
    "Sr.No": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"gray.600"}
        fontWeight={"600"}
        className="d-flex align-items-center fw- web-text-small"
      >
        {index + 1}
      </Text>
    ),
    "From Currency": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"gray.600"}
        fontWeight={"600"}
        className="d-flex align-items-center fw- web-text-small"
      >
        {item?.fromCurrency?.currencyCode}
      </Text>
    ),
    "To Currency": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"gray.600"}
        fontWeight={"600"}
        className="d-flex align-items-center fw- web-text-small"
      >
        {item?.toCurrency?.currencyCode}
      </Text>
    ),
    "Effective From": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"gray.600"}
        fontWeight={"600"}
        className="d-flex align-items-center  web-text-small"
      >
        {formatDate(item.effectiveFrom)}
      </Text>
    ),
    Rate: (
      <Text
        justifyContent={"left"}
        as={"span"}
        color={"gray.600"}
        fontWeight={"600"}
        className="d-flex align-items-center  web-text-small"
      >
        {formatCurrency(item.rate)}
      </Text>
    ),

    Action: (
      // <Button colorScheme="forestGreen" size={"xs"} variant={"ghost"}>
      //   Edit
      // </Button>
      <Box display={"flex"} justifyContent={"center"} gap={2}>
        <Tooltip
          rounded={"sm"}
          fontSize={"xs"}
          label="Edit"
          bg="#fff"
          color={"blue.500"}
          placement="top"
        >
          <Button
            ref={btnRef}
            onClick={() => {
              setActionId(item?.id);
              onOpen();
            }}
            // _hover={{ color: "blue.500" }}
            // transition={"0.5s all"}
            // color="blue.400"
            colorScheme="blue"
            size={"xs"}
            // size={{base:'xs', lg:'sm'}}
            rounded={"sm"}
            display={"flex"}
            alignItems={"center"}
            gap={1}
          >
            <EditIcon />
          </Button>
        </Tooltip>
        <Tooltip
          rounded={"sm"}
          fontSize={"xs"}
          label="History"
          bg="#fff"
          color={"purple.500"}
          placement="top"
        >
          <Button
            // _hover={{ color: "purple.500" }}
            // transition={"0.5s all"}
            // color="purple.400"
            colorScheme="purple"
            rounded={"sm"}
            size={{ base: "xs", lg: "xs" }}
            onClick={() => navigate(`currency-history/${item?.id}`)}
            display={"flex"}
            alignItems={"center"}
            gap={1}
          >
            <MdHistory />
          </Button>
        </Tooltip>
      </Box>
    ),
  }));

  const handleDelete = () => {
    const updatedSponsors = sponser.filter(
      (sponsor) => sponsor.id !== actionId
    );

    setTimeout(() => {
      setSponser(updatedSponsors);
      setDeleteAlert(false);
      setIsLoading(false);
    }, 100);
    setIsLoading(true);
  };

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

      <NormalTable
        emptyMessage={`We don't have any Sponers `}
        tableHeadRow={tableHeadRow}
        data={extractedArray}
        isLoading={isExchangeRateLoading}
        setMouseEnteredId={setMouseEnteredId}
        setMouseEntered={setMouseEntered}
      />

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

      <EditExchangeRate
        setIsLoading={setIsLoading}
        id={actionId}
        setId={setActionId}
        onClose={onClose}
        onOpen={onOpen}
        isOpen={isOpen}
        btnRef={btnRef}
        // id={item.id}
        // updateHistory={updateHistory}
      />
    </Box>
  );
};

export default ExchangeRate;
