import {
  Badge,
  Box,
  Button,
  HStack,
  Input,
  Text,
  Tooltip,
  useToast,
} from "@chakra-ui/react";
import React, { useContext, useEffect, useState } from "react";
import { OPACITY_ON_LOAD } from "../../../Layout/animations";
import {
  Link,
  Link as RouterLink,
  useNavigate,
  useParams,
} from "react-router-dom";
import { AddIcon, DeleteIcon, EditIcon, ViewIcon } from "@chakra-ui/icons";
import Pagination from "../../../Components/Pagination";
import GlobalStateContext from "../../../Contexts/GlobalStateContext";
import CustomAlertDialog from "../../../Components/CustomAlertDialog";
import NormalTable from "../../../Components/DataTable/NormalTable";
import {
  useDeleteInvestmentTypeMutation,
  useGetInvestmentTypesQuery,
} from "../../../Services/io.service";
import { TABLE_PAGINATION } from "../../../Constants/Paginations";
import { generateSerialNumber } from "../../../Constants/Constants";
import { useGetInvestorsDetailsByIdQuery } from "../../../Services/investor.details.service";

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

const BankDetails = () => {
  const params = useParams();
  const id = params?.id;
  const navigate = useNavigate();
  const toast = useToast();

  // ======================== [Use State] =========================

  const [searchTerm, setSearchTerm] = useState("");
  // const [isLoading, setIsLoading] = useState(false);
  const [deleteAlert, setDeleteAlert] = useState(false);
  const [actionId, setActionId] = useState(false);
  const { investmentType, setInvestmentType, slideFromRight } =
    useContext(GlobalStateContext);

  const [deleteInvestmentType] = useDeleteInvestmentTypeMutation();

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

  // const {
  //   data: investmentTypes,
  //   isLoading: investmentTypesLoading,
  //   error,
  // } = useGetInvestmentTypesQuery({ page: currentPage, size: pageSize });
  const { data, isLoading:bankDetailsLoading, errors, refetch } = useGetInvestorsDetailsByIdQuery(
    id,
    {
      skip: !id,
    }
  );

  console.log(data?.data?.bank_details);

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

    return nameMatches;
  });

  // ==================================================== [Table Setup] ================================================================

  const tableHeadRow = [
    "Sr No",
    "Bank Nick Name",
    "IBAN",
    "Account No",
    "Bank Name",
    "Account Name",
    "Bank Address",
    "SWIFT Code",
  ];

  const extractedArray = filteredData?.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>
    ),
    "Bank Nick Name": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        isTruncated={true}
        className="d-flex align-items-center web-text-small"
      >
        {item.bankNickName}
      </Text>
    ),
    IBAN: (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        isTruncated={true}
        className="d-flex align-items-center web-text-small"
      >
        {item.IBANnumber}
      </Text>
    ),
    "Account No": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        isTruncated={true}
        className="d-flex align-items-center web-text-small"
      >
        {item.accountNumber}
      </Text>
    ),
    "Bank Name": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        isTruncated={true}
        className="d-flex align-items-center web-text-small"
      >
        {item.bankName}
      </Text>
    ),
    "Account Name": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        isTruncated={true}
        className="d-flex align-items-center web-text-small"
      >
        {item.accountName}
      </Text>
    ),
    "Bank Address": (
        <Text
        w={"200px"}  // Set a width to constrain the text
        justifyContent={slideFromRight ? "right" : "left"}
        whiteSpace={"normal"}  // Allow wrapping
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {item.bankAddress}
      </Text>
    ),
    "SWIFT Code": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        isTruncated={true}
        className="d-flex align-items-center web-text-small"
      >
        {item.swiftCode}
      </Text>
    ),
  }));

  // ==================== [Delete Function] =======================

  const handleDelete = async () => {
    console.log(actionId);
    setIsLoading(true);
    try {
      const response = await deleteInvestmentType(actionId);
      console.log(response);
      setIsLoading(false);
      setDeleteAlert(false);
    } catch (error) {}
  };

  return (
    <Box {...OPACITY_ON_LOAD} overflowY={"scroll"} height={"100vh"} pb={38}>
      <HStack>
        <Text as={'span'} fontSize={'sm'} fontWeight={700}>Bank Details</Text>
      </HStack>
        <HStack
          display={"flex"}
          justifyContent={"space-between"}
          ps={1}
          pe={1}
          pb={4}
          pt={4}
          spacing="24px"
        >
          {/* ======================= [Search Input] ======================== */}

          <Input
            type="search"
            width={300}
            placeholder="Search..."
            size="sm"
            rounded="sm"
            focusBorderColor="green.500"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </HStack>

      {/* ======================== [Data Table] ======================= */}

      <NormalTable
        emptyMessage={`We don't have any Investment type `}
        tableHeadRow={tableHeadRow}
        data={extractedArray}
        isLoading={bankDetailsLoading}
        viewActionId={actionId}
        setViewActionId={setActionId}
      />
    </Box>
  );
};

export default BankDetails;
