import {
  Avatar,
  Badge,
  Box,
  Button,
  HStack,
  Input,
  Text,
  Tooltip,
  useDisclosure,
  useToast,
} from "@chakra-ui/react";
import React, { useContext, useEffect, useState, useRef } from "react";
import { HiDotsVertical } from "react-icons/hi";
import { Link, Link as RouterLink, useNavigate } from "react-router-dom";
import {
  EditIcon,
} from "@chakra-ui/icons";
import { OPACITY_ON_LOAD } from "../../../Layout/animations";
import DataTable from "../../../Components/DataTable/DataTable";
import Pagination from "../../../Components/Pagination";
import GlobalStateContext from "../../../Contexts/GlobalStateContext";
import CustomAlertDialog from "../../../Components/CustomAlertDialog";
import ToastBox from "../../../Components/ToastBox";
import { debounce } from "../../Master/Sponser/AddSponser";
import { useGetBankQuery } from "../../../Services/bank.details.service";
import NormalTable from '../../../Components/DataTable/NormalTable'

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

const BankDetails = () => {
  const navigate = useNavigate();
  const toast = useToast();
  const thirdField = useRef();
  const { InvestorDetails, setInvestorDetails, slideFromRight } =
    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: isEditOpen,
    onOpen: onEditOpen,
    onClose: onEditClose,
  } = useDisclosure();
  const btnRef = React.useRef();

  const {
    data: bankDetails,
    isLoading: bankDetailsLoading,
    error,
  } = useGetBankQuery({ page: 1, size: 10 });


  useEffect(() => {
    // Simulate loading
    const timer = setTimeout(() => {
      setIsLoading(false);
    }, 1500);

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

  // ====================================================[Table Setup]================================================================
  const tableHeadRow = [
    "Sr N/O",
    "Country name",
    "Account Name",
    "Account No",
    "Bank Name",
    "Action",
  ];

  const handleUpdateStatus = debounce((id) => {
    setInvestorDetails((prevData) =>
      prevData.map((InvestorDetails) =>
        InvestorDetails.id === id ? { ...InvestorDetails } : InvestorDetails
      )
    );
    toast({
      render: () => <ToastBox message={"Status changed succesfully.!"} />,
    });
  }, 300);

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

    // Filter by status
    // const status = item.status;
    // const statusLower = status ? "active" : "inactive";

    // const statusMatches =
    //   statusFilter === "all" ||
    //   (statusFilter === "active" && status === true) ||
    //   (statusFilter === "inactive" && status === false);

    return nameMatches;
  });
  

  const extractedArray = filteredData?.map((item,index) => ({
    id: item?.id,
    "Sr N/O": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"gray.600"}
        className="d-flex align-items-center fw-bold web-text-small"
      >
        {item.id}
      </Text>
    ),
    "Country name": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item?.country?.countryName}
        </Text>
      </Box>
    ),
    "Account Name": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item?.accountName}
        </Text>
      </Box>
    ),
    "Account No": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item?.accountNumber}
        </Text>
      </Box>
    ),
    "Bank Name": (
      <Box w={"auto"} isTruncated={true}>
        <Text as={"span"} color={"teal.900"}>
          {item.bankName}
        </Text>
      </Box>
    ),
    Action: (
      <Box display={"flex"} justifyContent={"space-between"}>
        <Tooltip
          rounded={"sm"}
          fontSize={"xs"}
          label="Edit"
          bg="#fff"
          color={"green.500"}
          placement="top"
        >
          <Button
            bg={index % 2 === 0 ? "#6311cb14" : "#fff"}
            onClick={() => {
              navigate(`/bank-details/edit-bank-details/${item.id}`);
            }}
            _hover={{ color: "green.500" }}
            // transition={"0.5s all"}
            color="green.300"
            rounded={"sm"}
            size={"xs"}
          >
            <EditIcon />
          </Button>
        </Tooltip>
      </Box>
    ),
  }));

  const handleDelete = () => {
    const updatedInvestorDetails = InvestorDetails.filter(
      (sponsor) => sponsor.id !== actionId
    );

    setTimeout(() => {
      setInvestorDetails(updatedInvestorDetails);
      setDeleteAlert(false);
      setIsLoading(false);
    }, 100);
    setIsLoading(true);
  };

  const handleEdit = (id) => {
    setActionId(id);
    onEditOpen();
  };

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

      <NormalTable
        emptyMessage={`We don't have any Details`}
        tableHeadRow={tableHeadRow}
        data={extractedArray}
        isLoading={isLoading}
        viewActionId={actionId}
        setViewActionId={setActionId}
        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 BankDetails;
