import { Box, HStack, Text } from "@chakra-ui/react";
import MainFrame from "../../../components/MainFrame";
import DataTable from "../../../components/DataTable";
import { Switch } from "../../../components/ui/switch";
// import { InputGroup } from "../../../components/ui/input-group";
// import { LuSearch } from "react-icons/lu";
// import { useGetContactQuery } from "../../../Redux/Service/deactivated.account.service";
import { useEffect, useState } from "react";
import { Spinner } from "../../../components/Sipnner/Spinner";
import { useGetDeactivateUserQuery, useUserDeactivateToggleMutation } from "../../../Redux/Service/manage.user";
import SearchComponent from "../../../components/SearchComponent";
import { Toaster, toaster } from "../../../components/ui/toaster";
import { delay } from "../../../components/Utils";

const tableHeadRow = [
  "Sr. No",
  "First Name",
  "Last Name",
  "User Type",
  "Activate/Deactivate",
];

const DeactivatedAccounts = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const { data, isLoading, refetch, isError, isFetching } = useGetDeactivateUserQuery(currentPage);
  const [localData, setLocalData] = useState<any[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [userDeactivateToggle] = useUserDeactivateToggleMutation()

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

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

  const filteredData = localData?.filter((agency) => {
    const searchLower = searchTerm.toLowerCase();
    const firstName = agency.first_name?.toLowerCase().includes(searchLower);
    const lastName = agency.last_name?.toLowerCase().includes(searchLower);
    // const email = agency.capital?.toLowerCase().includes(searchLower);
    return firstName || lastName;
  });

  const handleToggle = async (agencyId: number, currentStatus: string) => {
    const newStatus = currentStatus === '1' ? '0' : '1';

    setLocalData((prevData) =>
      prevData.map((agency) =>
        agency.id === agencyId ? { ...agency, is_active: newStatus } : agency
      )
    );

    try {
      await userDeactivateToggle({ id: agencyId, is_active: newStatus }).unwrap();
      toaster.create({
        title: "Success",
        description: "Status updated successfully",
        type: "success",
      });
      await delay(500);
      refetch()
    } catch (error) {
      console.error("Error updating privacy policy:", error);
      setLocalData((prevData) =>
        prevData.map((agency) =>
          agency.id === agencyId ? { ...agency, is_active: currentStatus } : agency
        )
      );
    }
  }

  const manageUser = filteredData?.map((agency: any, index: number) => ({
    "Sr. No": index + 1,
    "First Name": agency?.first_name,
    "Last Name": agency?.last_name,
    "User Type": agency?.principal_type_xid === 3 ? "JobSeeker" : "Recruiter",
    "Activate/Deactivate": (
      <Box display={"flex"} justifyContent={"center"}>
        <Switch
          size={"sm"}
          colorPalette={"teal"}
          checked={agency.is_active === true}
          onChange={() => handleToggle(agency.id, agency.is_active ? "1" : "0")}
        />
      </Box>
    ),
  }));

  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"}>
            Deactivated User Accounts
          </Text>

          <HStack>
            <SearchComponent
              value={searchTerm}
              onChange={(value) => {
                setSearchTerm(value);
                // setCurrentPage(1);
                refetch()
              }}
            />
          </HStack>
        </HStack>
        <DataTable
          sortableColumns={["Name", "Registration Date "]}
          tableHeadRow={tableHeadRow}
          data={manageUser}
          paginationData={{
            current_page: data?.data.current_page || 1,
            last_page: data?.data.last_page || 1,
            per_page: data?.data.per_page || 10,
            total: data?.data.total || 0
          }}
          onPageChange={handlePageChange}
          isLoading={isFetching}
          isError={isError}
        />
      </Box>
      <Toaster />
    </MainFrame>
  );
};

export default DeactivatedAccounts;
