import { Box, HStack, Image, Text } from "@chakra-ui/react";
import MainFrame from "../../../components/MainFrame"
import DataTable from "../../../components/DataTable";
import { Switch } from "../../../components/ui/switch";
// import img from "../../../assets/waterfall.jpg"
// import Templateimg from "../../../assets/Template_img.png"
import TemplateAddModel from "./TemplateAddModel";
import EditTemplateModel from "./EditTemplateModel";
import { Template, useGetTemplateMasterQuery, useTemplateMasterToggleMutation } from "../../../Redux/Service/template.master.service";
import { useEffect, useState } from "react";
import SearchComponent from "../../../components/SearchComponent";
import { toaster, Toaster } from "../../../components/ui/toaster";
import { delay } from "../../../components/Utils";

const APIURL = import.meta.env.VITE_IMG_TEMPLATES

// table data

const tableHeadRow = [
  "Sr. No",
  "Title",
  "User Type",
  "Images",
  "Action"
];

// const managepost: any[] = [
//   ...Array.from({ length: 12 }, (_, i) => ({
//     "Sr. No": i + 1,
//     "Title": "Lorem Ipsum",
//     "Images": (
//       // <Image w={50} src={img} />
//       <HStack >
//         <Image rounded={'lg'} w={100} h={50} src={img} />
//         <Image rounded={'lg'} w={100} h={50} src={Templateimg} />
//       </HStack>
//     ),

//     "Action": (
//       <HStack justifyContent="center">
//         <EditTemplateModel />
//         <Box>
//           <Switch colorPalette={'teal'} size={"xs"} />
//         </Box>
//       </HStack>
//     ),
//   })),
// ];

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

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

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

  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 templateMasterToggle({ 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 filteredData = localData?.filter((agency) =>
    agency.post_template_translate[0].title.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const activeCount = filteredData?.filter((a: any) => a.is_active === 1).length ?? 0;

  const managepost = filteredData?.map((agency: Template, index: number) => {
    const isOnlyActive = activeCount === 1 && Number(agency.is_active) === 1;

    return {
      'id': agency.id,
      "Sr. No": (currentPage - 1) * (data?.data.per_page ?? 0) + index + 1,
      "Title": agency.post_template_translate.length > 0
        ? agency.post_template_translate[0].title
        : "N/A",
      "User Type": agency.principle_type_xid === 2 ? 'Recruiter' : 'Job Seeker',
      "Images": (
        // <Image w={50} src={img} />
        <HStack>
          {agency.post_template_image.map((img) => (
            <Image key={img.id} rounded={'lg'} w={100} h={50} src={`${APIURL}${img.image_name}`} />
          ))}

          {/* <Image rounded={'lg'} w={100} h={50} src={Templateimg} /> */}
        </HStack>
      ),

      "Action": (
        <HStack justifyContent="center">
          <EditTemplateModel id={agency.id} localData={localData} refetch={refetch} />
          <Box>
            <Switch
              colorPalette={'teal'}
              size={"xs"}
              onChange={() => handleToggle(agency.id.toString(), Number(agency.is_active ?? 0))}
              checked={Boolean(Number(agency.is_active))}
              disabled={isOnlyActive}
            />
          </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"}>
            Template Master
          </Text>

          <HStack >
            {/* <InputGroup
              startElement={
                <LuSearch fontSize={"xs"} style={{ position: 'relative', left: '10px' }} />
              }
              color={"#000"}
            >
              <Input
                p={3}
                w={300}
                bg={"#fff"}
                colorPalette={"blue"}
                _focus={{ border: "1px solid #02A0A0" }}
                rounded={"md"}
                size={"xs"}
                fontSize={"sm"}
                placeholder="Search..."
                bgColor={'#EEEEEE'}
                ps={8}
              />
            </InputGroup> */}
            <SearchComponent
              value={searchTerm}
              onChange={setSearchTerm}
            />
            <TemplateAddModel 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 TemplateMaster