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 } 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 ToastBox from "../../../Components/ToastBox";
import { debounce } from "./AddInvestmentType";
import NormalTable from "../../../Components/DataTable/NormalTable";
import {
  useDeleteInvestmentTypeMutation,
  useGetInvestmentTypesQuery,
} from "../../../Services/io.service";
import { TABLE_PAGINATION } from "../../../Constants/Paginations";
import { generateSerialNumber } from "../../../Constants/Constants";

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

const InvestmentType = () => {
  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 [mouseEntered, setMouseEntered] = useState(false);
  const [mouseEnteredId, setMouseEnteredId] = useState("");
  const [isSwitchOn, setIsSwitchOn] = 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 });

  console.log(investmentTypes?.data?.rows);

  // ========= [Toggle ToastBox] =======

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

  // ===========================[Table Filter]=============================

  const filteredData = investmentTypes?.data?.rows?.filter((item) => {
    const name = item?.investmentTypeName;
    const searchLower = searchTerm.toLowerCase();
    const nameMatches = name.toLowerCase().includes(searchLower);

    return nameMatches;
  });

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

  const tableHeadRow = [
    "Sr No",
    "Investment Type",
    "Description",
    "Status",
    "Action",
  ];

  const extractedArray = filteredData?.map((item, index) => ({
    "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(index, currentPage, pageSize)}
      </Text>
    ),
    "Investment Type": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        isTruncated={true}
        className="d-flex align-items-center web-text-small"
      >
        {item?.investmentTypeName}
      </Text>
    ),
    Description: (
      <Tooltip
        hasArrow
        bg={"#fff"}
        fontSize={"xs"}
        label={item.note}
        placement="top-start"
        color={"blue.800"}
      >
        <Text
          as={"span"}
          color={"teal.900"}
          fontWeight={"500"}
          maxWidth="600px" // Adjust width as needed
          display="block" // Ensure block display for proper truncation
          overflow="hidden"
          isTruncated
          textOverflow="ellipsis"
          cursor={"grab"}
        >
          {item?.note ? item?.note : "---"}
        </Text>
      </Tooltip>
    ),
    Status: (
      <Box isTruncated={true}>
        <Text as={"span"} fontWeight={"500"}>
          <Badge
            bg={index % 2 === 0 ? "#6311cb14" : "#fff"}
            fontWeight={"500"}
            textTransform={"none"}
            color={item.isActive ? "green" : "red"}
            px={2}
            py={0.5}
          >
            {item?.isActive ? "Active" : "Inactive"}
          </Badge>
        </Text>
      </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-investment/${item.id}`);
            }}
            // color="green.300"
            rounded={"sm"}
            size={"xs"}
            colorScheme="green"
          >
            <ViewIcon />
          </Button>
        </Tooltip> */}

        <Tooltip
          rounded={"sm"}
          fontSize={"xs"}
          label="Edit"
          bg="#fff"
          color={"blue.500"}
          placement="top"
        >
          <Button
            onClick={() =>
              navigate(`/investment-type/add-investment/${item?.id}`)
            }
            // _hover={{ color: "blue.500" }}
            // color="blue.400"
            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" }}
            // color="red.300"
            colorScheme="red"
            rounded={"sm"}
            size={"xs"}
          >
            <DeleteIcon />
          </Button>
        </Tooltip>
      </Box>
    ),
  }));

  // ==================== [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) {}
  // };

  const handleDelete = async () => {
    console.log(actionId);
    setIsLoading(true);
    try {
      const response = await deleteInvestmentType(actionId);
      console.log(response?.data);
  
      if (response?.error?.data?.code === 400) {
        toast({
          render: () => (
            <ToastBox message={response?.error?.data?.message} status="error" />
          ),
        });
      } else if (
        response?.data?.statusCode === 201 ||
        response?.data?.statusCode === 200
      ) {
        toast({
          render: () => (
            <ToastBox message={response?.data?.message} status="success" />
          ),
        });
      }
      setIsLoading(false);
      setDeleteAlert(false);
    } catch (error) {
      console.error(error);
      setIsLoading(false);
    }
  };
  


  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"
        >
          {/* ======================= [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 display={"flex"} alignItems={"center"}>
            {/* ====================[Pagination]===================== */}

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

            {/* ===================== [Add Button] ===================== */}

            <Link to={"/investment-type/add-investment"}>
              <Button
                leftIcon={<AddIcon />}
                colorScheme={"forestGreen"}
                rounded={"sm"}
                size={"sm"}
                fontSize={"xs"}
              >
                Add Investment Type
              </Button>
            </Link>
          </HStack>
        </HStack>
      </Box>

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

      <NormalTable
        emptyMessage={`We don't have any Investment type `}
        tableHeadRow={tableHeadRow}
        data={extractedArray}
        isLoading={investmentTypesLoading}
        viewActionId={actionId}
        setViewActionId={setActionId}
        setMouseEnteredId={setMouseEnteredId}
        setMouseEntered={setMouseEntered}
      />

      {/* ========================  [Modal]  ======================== */}

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

export default InvestmentType;
