import { Box, HStack, Text } from "@chakra-ui/react";
import MainFrame from "../../../components/MainFrame"
// import { InputGroup } from "../../../components/ui/input-group";
// import { LuSearch } from "react-icons/lu";
import DataTable from "../../../components/DataTable";
import { Switch } from "../../../components/ui/switch";
import JobAddModel from "./JobAddModel";
import EditJobeModel from "./EditJobModel";
import { JobTypeData, useGetJobTypeQuery, useJobTypeToggleMutation } from "../../../Redux/Service/job.type.service";
import { useEffect, useState } from "react";
import SearchComponent from "../../../components/SearchComponent";
import { toaster, Toaster } from "../../../components/ui/toaster";
import { delay } from "../../../components/Utils";



// table data

const tableHeadRow = [
  "Sr. No",
  "Title",
  "Action"

];

// const managepost: any[] = [
//   ...Array.from({ length: 12 }, (_, i) => ({
//     "Sr. No": i + 1,
//     "Title": "Lorem Ipsum",
//     "Action": (
//       <HStack justifyContent="center">
//         <EditJobeModel />
//         <Box>
//           <Switch colorPalette={'teal'} size={"xs"} />
//         </Box>
//       </HStack>
//     ),
//   })),
// ];

const JobType = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const { data, refetch, isFetching, isError } = useGetJobTypeQuery(currentPage)
  const [localData, setLocalData] = useState<any[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [jobTypeToggle] = useJobTypeToggleMutation()
  console.log('DATA', data?.data.data);


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

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

  const filteredData = localData?.filter((agency) => {
    const searchLower = searchTerm.toLowerCase();
    const title = agency.en_name?.toLowerCase().includes(searchLower);
    return title;
  });

  const handleToggle = async (agencyId: string, currentStatus: number) => {
    const newStatus = currentStatus ? 0 : 1;
    setLocalData((prevData) =>
      prevData.map((agency) =>
        agency.id === agencyId ? { ...agency, is_active: newStatus } : agency
      )
    );
    try {
      await jobTypeToggle({ 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
        )
      );
      toaster.create({
        title: "Error",
        description: "Please try again later",
        type: "error",
      });
    }
  };


  const managepost = filteredData?.map((agency: JobTypeData, index: number) => ({
    'id': (currentPage - 1) * (data?.data.per_page ?? 0) + index + 1,
    "Sr. No": index + 1,
    "Title": agency.en_name,

    "Action": (
      <HStack justifyContent="center">
        <EditJobeModel id={agency.id} localData={localData} refetch={refetch} />
        <Box>
          <Switch
            colorPalette={'teal'}
            size={"xs"}
            onChange={() => handleToggle(agency.id.toString(), Number(agency.is_active))}
            checked={Boolean(Number(agency.is_active))}
          />
        </Box>
      </HStack>
    ),
  }));


  return (

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

          <HStack >
            <SearchComponent
              value={searchTerm}
              onChange={(value) => {
                setSearchTerm(value);
                // setCurrentPage(1);
                refetch()
              }}
            />
            {/* <Button bgColor={'#EEEEEE'} pl={3} pr={3}><IoMdAdd /> <Text>Add</Text></Button> */}
            <JobAddModel refetch={refetch} />
          </HStack>
        </HStack>
        <DataTable
          sortableColumns={["Name", "Registration Date "]}
          tableHeadRow={tableHeadRow}
          data={managepost}
          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 JobType