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 JobStatusAddModel from "./JobStatusAddModel";
import EditJobStatusModel from "./EditJobStatusModel";
import { useGetJobStatusQuery, useJobStatusToggleMutation } from "../../../Redux/Service/job.status";
import { useEffect, useState } from "react";
import SearchComponent from "../../../components/SearchComponent";
import { toaster, Toaster } from "../../../components/ui/toaster";
import { useDebounce } from "../../../components/Hooks/useDebounce";
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">
//         <EditJobStatusModel />
//         <Box>
//           <Switch colorPalette={'teal'} size={"xs"} />
//         </Box>
//       </HStack>
//     ),
//   })),
// ];

const JobStatus = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const [searchTerm, setSearchTerm] = useState("");
  const debouncedSearchTerm = useDebounce(searchTerm, 500);
  const queryArgs = debouncedSearchTerm ? { page: currentPage, search: debouncedSearchTerm } : { page: currentPage };
  const { data, refetch, isError, isFetching } = useGetJobStatusQuery(queryArgs)
  const [localData, setLocalData] = useState<any[]>([]);
  const [jobStatusToggle] = useJobStatusToggleMutation()
  console.log(data?.data.data)

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

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

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

  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 jobStatusToggle({ 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:", error);
      toaster.create({
        title: "Error",
        description: "Someting went wrong.",
        type: "error",
      });
      setLocalData((prevData) =>
        prevData.map((agency) =>
          agency.id === agencyId ? { ...agency, is_active: currentStatus } : agency
        )
      );
    }
  };

  const filteredData = localData?.filter((agency) => {
    return (agency.job_status_translation.map((item: any) => {
      const searchLower = searchTerm.toLowerCase();
      const title = item.title?.toLowerCase().includes(searchLower);
      return title;
    }))
  });

  const managepost = filteredData?.flatMap((agency: any, index: number) => (agency.job_status_translation.map((translation: any) => ({
    'id': agency.id,
    "Sr. No": (currentPage - 1) * (data?.data.per_page ?? 0) + index + 1,
    "Title": translation.title,
    "is_active": agency.is_active,
    "Action": (
      <HStack justifyContent="center">
        {/* <ViewAgencyMaster agency={localData} id={agency.id} /> */}
        <EditJobStatusModel localData={{ ...agency, translation }} refetch={refetch} />
        <Box>
          <Switch
            colorPalette={"teal"}
            size={"xs"}
            onChange={() => handleToggle(agency.id, 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 Status
          </Text>

          <HStack >
            <SearchComponent
              value={searchTerm}
              onChange={handleSearchChange}
            />
            {/* <Button bgColor={'#EEEEEE'} pl={3} pr={3}><IoMdAdd /> <Text>Add</Text></Button> */}
            <JobStatusAddModel 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 JobStatus