import { Box, HStack, Image, Spinner, Text } from "@chakra-ui/react";
import MainFrame from "../../../components/MainFrame"
import EditDetails from "./EditDetails";
// import { InputGroup } from "../../../components/ui/input-group";
// import { LuSearch } from "react-icons/lu";
import DataTable from "../../../components/DataTable";
import AlertDailog from "../../../components/AlertDailog";
import { Switch } from "../../../components/ui/switch";
import FaqAddModel from "./FaqAddModel";
import Delete from "../../../components/ActionIcons/Delete";
import { useEffect, useState } from "react";
import { FaqData, useDeleteFaqPostMutation, useFaqToggleMutation, useGetFaqQuery } from "../../../Redux/Service/faqs.service";
import SearchComponent from "../../../components/SearchComponent";
import NoData from "../../../components/NoData";
import { Toaster, toaster } from "../../../components/ui/toaster";


// table data

const tableHeadRow = [
  "Sr. No",
  'Category',
  "Question",
  "Answer",
  "Action",
];

// const managepost: any[] = [
//   ...Array.from({ length: 12 }, (_, i) => ({
//     "Sr. No": i + 1,
//     "Question": "Lorem Ipsum",
//     "Answer": "Lorem Ipsum",
//     "Action": (
//       <HStack justifyContent="center">
//         <Box>
//           <Switch colorPalette={'teal'} size={"xs"} />
//         </Box>
//         {/* <EditDetails /> */}
//         <EditDetails id={(i + 1).toString()} question="Lorem Ipsum" answer="Lorem Ipsum" />

//         <AlertDailog
//           AltertTiggerIcon={() => <Delete />}
//           alertText="Delete Users"
//           alertIcon={<Image src={"DeleteIcon"} h={"39px"} />}
//           alertCaption="are you sure you want to delete ?"
//           onConfirm={() => {
//             console.log("User deleted:", i + 1);
//           }}
//         />
//       </HStack>
//     ),
//   })),
// ];

const FAQ = () => {
  const [currentPage, setCurrentPage] = useState(1);
  const { data, refetch, isLoading, isFetching, isError } = useGetFaqQuery(currentPage)
  const [localData, setLocalData] = useState<any[]>([]);
  const [faqToggle] = useFaqToggleMutation()
  const [deleteFaqPost] = useDeleteFaqPostMutation()
  const [searchTerm, setSearchTerm] = useState("");
  const [deleteModal, setDeleteModal] = useState(false)
  const [selectedFaqId, setSelectedFaqId] = useState<number | null>(null);

  console.log('DATA', data?.data.data);

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

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


  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 faqToggle({ id: agencyId, is_active: newStatus }).unwrap();
      toaster.create({
        title: "Success",
        description: "Status updated successfully",
        type: "success",
      });
      setTimeout(() => {
        refetch();
      }, 500);
    } catch (error) {
      console.error("Error updating privacy policy:", 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 handleDeleteFaq = async (faqId: number) => {
    try {
      const response = await deleteFaqPost({ id: faqId }).unwrap();
      if (response?.status === "success") {
        toaster.create({
          title: "Success",
          description: "FAQ deleted successfully",
          type: "success",
        });
        refetch()
        console.log("FAQ deleted successfully:", response);
      }
      // Optionally, refetch data or update state after deletion
    } catch (error) {
      console.error("Error deleting FAQ:", error);
      toaster.create({
        title: "Error",
        description: "Something went wrong",
        type: "error",
      });
    }
  };

  const filteredData = localData?.filter((agency) =>
    agency.translations.some((translation: any) => {
      const searchLower = searchTerm.toLowerCase();
      const questionMatch = translation.question?.toLowerCase().includes(searchLower);
      const answerMatch = translation.answer?.toLowerCase().includes(searchLower);
      return questionMatch || answerMatch;
    })
  );

  console.log("filteredData", filteredData);


  const managepost = filteredData?.flatMap((agency: FaqData, index: number) =>
    agency.translations.map((translation: any) => ({
      'id': translation.id,
      "Sr. No": (currentPage - 1) * (data?.data.per_page ?? 0) + index + 1,
      "Question": translation.question,
      "Answer": translation.answer,
      'Category': agency.principal_type_xid === 2 ? "Recruiter" : "Job Seeker",

      "Action": (
        <HStack justifyContent="center">
          <EditDetails rowData={{ id: agency.id, question: translation.question, answer: translation.answer, principal_type_xid: agency.principal_type_xid }} refetch={refetch} />

          <AlertDailog
            isOpen={deleteModal}
            AltertTiggerIcon={() => <Delete onClick={() => {
              setSelectedFaqId(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 (selectedFaqId) {
                setDeleteModal(false);
                handleDeleteFaq(selectedFaqId);
              }
            }}
          />
          <Box>
            <Switch
              colorPalette={'teal'}
              size={"xs"}
              onChange={() => handleToggle(Number(agency.id), agency.is_active.toString())}
              checked={Boolean(Number(agency.is_active))}
              key={`switch-${agency.id}`}
            />
          </Box>
        </HStack>
      ),
    })))

  if (isFetching) {
    return (
      <HStack
        w={"100%"}
        justifyContent={"center"}
        mb={4}
        py={0}
        px={3}
      >
        <Spinner color={'teal'} />
      </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"}>
            FAQs
          </Text>

          <HStack >
            <SearchComponent
              value={searchTerm}
              onChange={setSearchTerm}
            />
            {/* <Button bgColor={'#EEEEEE'} pl={3} pr={3}><IoMdAdd /> <Text>Add</Text></Button> */}
            <FaqAddModel refetch={refetch} />
          </HStack>
        </HStack>
        {isFetching && <Spinner />}
        {!isLoading && !data?.data ? (
          <NoData message={'No data found'} text={'Please add new data'} />
        ) : (<DataTable
          sortableColumns={["Name"]}
          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 FAQ