import { Box, HStack, Text } from "@chakra-ui/react";
import MainFrame from "../../components/MainFrame";
import PendingRequests from "../../Pages/ManageContact/PendingRequests";
// import { InputGroup } from "../../components/ui/input-group";
// import { LuSearch } from "react-icons/lu";
import DataTable from "../../components/DataTable";
import { useGetContactQuery } from "../../Redux/Service/manage.contactus.service";
import { useEffect, useState } from "react";
import { Spinner } from "../../components/Sipnner/Spinner";
import { useDebounce } from "../../components/Hooks/useDebounce";
import SearchComponent from "../../components/SearchComponent";

// table data
const tableHeadRow = ["Sr. No", "Email id", "Name", "Date", "Action"];

const ManageContact = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const [localData, setLocalData] = useState<any[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const debouncedSearchTerm = useDebounce(searchTerm, 500);
  const queryArgs = debouncedSearchTerm ? { page: currentPage, search: debouncedSearchTerm } : { page: currentPage };
  const { data, isLoading, isError, refetch, isFetching } = useGetContactQuery(queryArgs);


  useEffect(() => {
    if (data) {
      setLocalData((data as any)?.data?.data || []);
    }
  }, [data]);

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  const handleSearchChange = (value: string) => {
    setSearchTerm(value);
    setCurrentPage(1);
  };

  const filteredData = localData?.filter((agency) =>
    agency?.first_name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    agency?.email.toLowerCase().includes(searchTerm.toLowerCase())
  );

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

  const managepost = filteredData?.map((agency: any, index: number) => ({
    "Sr. No": index + 1, // Typically Sr. No starts from 1, not using id which might not be sequential
    "Email id": agency?.email || "-",
    Name: agency?.first_name || "-",
    Date: formatDateOfBirth(agency?.created_at) || "-",
    Action: (
      <HStack justifyContent="center" cursor={agency.response_status === 0 ? 'pointer' : 'default'}>
        {agency.response_status === 0 ? <PendingRequests data={agency} refetch={refetch} /> : 'Resolved'}
        {/* <PendingRequests data={agency} refetch={refetch} /> */}
      </HStack>
    ),
  }));

  if (isLoading) {
    return (
      <MainFrame>
        <Box
          display="flex"
          justifyContent="center"
          alignItems="center"
          height="100%"
        >
          <Spinner />
        </Box>
      </MainFrame>
    );
  }

  if (isError) {
    return (
      <MainFrame>
        <Box
          display="flex"
          justifyContent="center"
          alignItems="center"
          height="100%"
        >
          <Text>Error loading data</Text>
        </Box>
      </MainFrame>
    );
  }

  return (
    <MainFrame>
      <Box>
        <HStack
          w={"100%"}
          justifyContent={"space-between"}
          mb={4}
          py={0}
          px={3}
        >
          <Text as={"span"} fontSize={"sm"} fontWeight={500} color={"#000"}>
            Contact Requests
          </Text>

          <HStack>
            <SearchComponent
              value={searchTerm}
              onChange={handleSearchChange}
            />
          </HStack>
        </HStack>
        <DataTable
          sortableColumns={["Name", "Registration Date "]}
          tableHeadRow={tableHeadRow}
          data={managepost || []} // Ensure an empty array is passed if managepost is undefined
          paginationData={{
            current_page: (data?.data as any)?.current_page || 1,
            last_page: (data?.data as any)?.last_page || 1,
            per_page: (data?.data as any)?.per_page || 10,
            total: (data?.data as any)?.total || 0
          }}
          onPageChange={handlePageChange}
          isLoading={isFetching}
          isError={isError}
        />
      </Box>
    </MainFrame>
  );
};

export default ManageContact;
