import {
  Box,
  HStack,
  Image,
  //  Image,
  Text,
} from "@chakra-ui/react";
// import { LuSearch } from "react-icons/lu";
// import { RiDeleteBin5Line } from "react-icons/ri";
// import AlertDailog from "../../components/AlertDailog";
import DataTable from "../../components/DataTable";
import MainFrame from "../../components/MainFrame";
// import { InputGroup } from "../../components/ui/input-group";
import ManageJobsAdd from "./ManageJobsAdd";
import ViewManageJob from "./ViewManageJob";
import {
  useDeleteJobsPostMutation,
  useGetManageJobsQuery,
} from "../../Redux/Service/manage.jobs.service";
import { useEffect, useState } from "react";
import { Spinner } from "../../components/Sipnner/Spinner";
import Delete from "../../components/ActionIcons/Delete";
import { Toaster, toaster } from "../../components/ui/toaster";
import AlertDailog from "../../components/AlertDailog";
import { useDebounce } from "../../components/Hooks/useDebounce";
import SearchComponent from "../../components/SearchComponent";
// import { useState } from "react";
// import { useGetManageJobsQuery } from "../../Redux/Service/manage.jobs.service";
// import Delete from "../../components/ActionIcons/Delete";

// table data

const tableHeadRow = [
  "Sr. No",
  "Job Title",
  "Workspace mode",
  "Category",
  "Sub-category",
  "Salary",
  "Action",
];

const ManageJobs = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const [localData, setLocalData] = useState([]);
  const [searchTerm, setSearchTerm] = useState("");
  const debouncedSearchTerm = useDebounce(searchTerm, 500);
  const queryArgs = debouncedSearchTerm ? { page: currentPage, search: debouncedSearchTerm } : { page: currentPage };
  const { data, refetch, isLoading, isError, isFetching } = useGetManageJobsQuery(queryArgs);
  const [deleteJobsPost] = useDeleteJobsPostMutation();
  const [deleteModal, setDeleteModal] = useState(false);
  const [selectedJobsId, setSelectedJobsId] = useState<number | null>(null);

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

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

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

  const handleDeleteJobs = async (jobsId: number) => {
    try {
      const response = await deleteJobsPost({ id: jobsId }).unwrap();
      if (response?.status === "success") {
        toaster.create({
          title: "Success",
          description: "Jobs deleted successfully",
          type: "Success",
        });
        refetch();
      }
    } catch (error) {
      console.error("Error deleting FAQ:", error);
      toaster.create({
        title: "Error",
        description: "Something went wrong",
        type: "error",
      });
    }
  };

  const managepost = localData?.map((agency: any, index: number) => ({
    "Sr. No": index + 1,
    "Job Title": agency?.job_title,
    "Workspace mode": agency?.workspace?.en_name,
    Category: agency?.industry?.en_name,
    "Sub-category": agency?.department?.en_name,
    Salary: agency?.ctc_amount,
    Action: (
      <HStack justifyContent="center">
        <ViewManageJob data={agency} />
        <ManageJobsAdd data={agency} refetch={refetch}/>
        <AlertDailog
          isOpen={deleteModal}
          AltertTiggerIcon={() => (
            <Delete
              onClick={() => {
                setSelectedJobsId(agency.id);
                setDeleteModal(true);
              }}
            />
          )}
          alertText="Delete FAQ"
          alertIcon={<Image src={"DeleteIcon"} h={"39px"} />}
          alertCaption="are you sure you want to delete ?"
          onClose={() => setDeleteModal(false)}
          onConfirm={() => {
            // console.log("Deleting FAQ with ID:", selectedFaqId); // Correct ID
            if (selectedJobsId) {
              setDeleteModal(false);
              handleDeleteJobs(selectedJobsId);
            }
          }}
        />
      </HStack>
    ),
  }));

  if (isLoading) {
    return (
      <MainFrame>
        <Box
          display="flex"
          justifyContent="center"
          alignItems="center"
          height="100%"
        >
          <Spinner />
        </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"}>
            View job Posting
          </Text>

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