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 NormalTable from '../../../Components/DataTable/NormalTable'
import { Link, Link as RouterLink } from "react-router-dom";
import {AddIcon,DeleteIcon,EditIcon,} from "@chakra-ui/icons";
import Pagination from "../../../Components/Pagination";
import GlobalStateContext from "../../../Contexts/GlobalStateContext";
import CustomAlertDialog from "../../../Components/CustomAlertDialog";
import { useNavigate } from "react-router-dom";
import ToastBox from "../../../Components/ToastBox";
import { debounce } from "./AddSponser";
import { TABLE_PAGINATION } from "../../../Constants/Paginations";
import { useDeleteSponserMutation, useGetSponserMasterQuery } from "../../../Services/io.service";
import { generateSerialNumber } from "../../../Constants/Constants";

export  const formatDate = (date) => {
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0'); // Months are 0-indexed
  const day = String(d.getDate()).padStart(2, '0');

  return `${day}/${month}/${year}`;
};

const Sponser = () => {

  const navigate = useNavigate();
  const toast = useToast();
  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 [deleteSponser] = useDeleteSponserMutation(); 
  const { sponser, setSponser, slideFromRight } = useContext(GlobalStateContext);

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

  // Debounce the search term to avoid making a request on every keystroke
  useEffect(() => {
    const handler = setTimeout(() => {
      setDebouncedSearchTerm(searchTerm);
    }, 500); // Adjust delay as needed
    return () => {
      clearTimeout(handler);
    };
  }, [searchTerm]);
  const { data: sponsors, error, isLoading: isSponserLoading } = useGetSponserMasterQuery(
    {
      page: debouncedSearchTerm ? undefined : currentPage,  // Omit pagination for search
      size: debouncedSearchTerm ? undefined : pageSize,     // Omit pagination for search
      searchTerm: debouncedSearchTerm,
    },
    {
      skip: debouncedSearchTerm === "" && searchTerm !== "", // Skip if search is empty and it's not the initial request
    }
  );
  console.log(sponsors?.data?.rows);

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

  const filteredData = sponsors?.data?.rows?.filter((item) => {
    const name = item.sponsorName;
    const searchLower = searchTerm?.toLowerCase();
    const nameMatches = name?.toLowerCase().includes(searchLower);
    return nameMatches;
  });

  // ====================================================[Table Setup]================================================================
  
  const tableHeadRow = [
    "Sr No",
    "Sponsor Name",
    "Email Address",
    "Status",
    "Action",
  ];

  const extractedArray = sponsors?.data?.rows?.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>),
    "Sponsor Name": (
      <Text
        justifyContent={slideFromRight ? "right" : "left"}
        as={"span"}
        color={"teal.900"}
        fontWeight={"500"}
        className="d-flex align-items-center web-text-small"
      >
        {item.sponsorName}
      </Text>
    ),

    "Email Address": (
      <Box isTruncated={true}>
        <Text as={"span"} color={"teal.900"} fontWeight={"500"}>
          {item.email ? item.email : "---" }
        </Text>
      </Box>
    ),
    Status: (
      <Box minW={24} isTruncated={true} >
        <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>
      </Box>
    ),
    Action: (
      <Box display={"flex"} justifyContent={"center"} gap={2}>
        <Tooltip
          rounded={"sm"}
          fontSize={"xs"}
          label="Edit"
          bg="#fff"
          color={"blue.500"}
          placement="top"
        >
          <Button
            onClick={() => navigate(`/sponser/add-sponser/${item.id}`)}
            // _hover={{ color: "blue.500" }}
            // color="blue.400"
            rounded={"sm"}
            size={"xs"}
            colorScheme="blue"
          >
            <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"
            rounded={"sm"}
            size={"xs"}
            colorScheme="red"
            variant={'solid'}
          >
            <DeleteIcon  />
          </Button>
        </Tooltip>
      </Box>
    ),
  }));

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

  const handleDelete = async () => {
    console.log(actionId);
    setIsLoading(true);
    try {
      const response = await deleteSponser(actionId);
      console.log(response?.data);
      if(response?.error?.data?.code === 400){
        toast({
          render: () => <ToastBox message={response?.error?.data?.message} status={'error'} />,
        });
        setIsLoading(false);
        setDeleteAlert(false);
      } 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.log(isSponserLoading);

  

  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={isSponserLoading} 
            pageSize={pageSize} 
            setPageSize={setPageSize} 
            currentPage={currentPage} 
            setCurrentPage={setCurrentPage} 
            totalItems={sponsors?.data?.totalItems} />

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

            <Link to={"/sponser/add-sponser"}>
              <Button
                leftIcon={<AddIcon />}
                colorScheme={"forestGreen"}
                rounded={"sm"}
                fontSize={'xs'}
                size={"sm"}
              >
                Add Sponsor
              </Button>
            </Link>
          </HStack>
        </HStack>
      </Box>

      {/* =================== [Data Table] ===================== */}
      
      <NormalTable
        emptyMessage={`We don't have any Sponers `}
        tableHeadRow={tableHeadRow}
        data={extractedArray}
        isLoading={isSponserLoading}
        viewActionId={actionId}
        setViewActionId={setActionId}
        setMouseEnteredId={setMouseEnteredId}
        setMouseEntered={setMouseEntered}
      />

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

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

export default Sponser;
