import { Box, HStack, Image, 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 AlertDailog from "../../components/AlertDailog";
// import { RiDeleteBin5Line } from "react-icons/ri";
import AddModel from "./AddModel"
import EditSubAdmin from "./EditSubAdmin"
import ViewSubAdmin from "./ViewSubAdmin"
import Delete from "../../components/ActionIcons/Delete"
import { PermissionResponse, useDeleteSubAdminPostMutation, useGetPermissionQuery, useGetSubAdminQuery } from "../../Redux/Service/manage.subadmin.service"
import { useEffect, useState } from "react"
import { Toaster, toaster } from "../../components/ui/toaster"
import { useDebounce } from "../../components/Hooks/useDebounce"
import SearchComponent from "../../components/SearchComponent"


// table data

const tableHeadRow = [
  "Sr. No",
  "Emp ID",
  "First Name",
  "last Name",
  "DOB",
  "Gender",
  "Action",
];

// const managepost: any[] = [
//   ...Array.from({ length: 12 }, (_, i) => ({
//     "Sr. No": i + 1,
//     "Id": 12565,
//     "First Name": "Kamlesh",
//     "last Name": "Pandey",
//     "DOB": "12/01/1987",
//     "Gender": "Male",
//     "Action": (
//       <HStack justifyContent="center">

//         <ViewSubAdmin />
//         <EditSubAdmin />

//         <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 SubAdmin = () => {
  const [currentPage, setCurrentPage] = useState(1);
  // const { data, refetch } = useGetSubAdminQuery()
  const { data: permissions } = useGetPermissionQuery()
  const [localData, setLocalData] = useState<any[]>([]);
  const [allPermissions, setAllPermissions] = useState<PermissionResponse>();
  const [deleteModal, setDeleteModal] = useState(false)
  const [deleteSubAdminPost] = useDeleteSubAdminPostMutation()
  const [searchTerm, setSearchTerm] = useState("");
  const debouncedSearchTerm = useDebounce(searchTerm, 500);
  const queryArgs = debouncedSearchTerm ? { page: currentPage, search: debouncedSearchTerm } : { page: currentPage };
  const { data, refetch, isError, isFetching } = useGetSubAdminQuery(queryArgs);

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

  console.log("============================", allPermissions);
  console.log('localData', localData);

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

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

  const handleDeleteAdmin = async (faqId: number) => {
    try {
      const response = await deleteSubAdminPost(faqId).unwrap();
      if (response.success) {
        toaster.create({
          title: "Success",
          description: "Sub Admin deleted successfully",
          type: "success",
        });
        refetch()
        console.log("Sub Admin deleted successfully:", response);
      }
      // Optionally, refetch data or update state after deletion
    } catch (error) {
      console.error("Error deleting Sub Admin:", error);
      toaster.create({
        title: "Error",
        description: "Something went wrong",
        type: "error",
      });
    }
  };

  const formatDateOfBirth = (dob: string): string => {
    return new Date(dob).toLocaleDateString("en-GB", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
    });
  };

  const filteredData = localData?.filter((agency) => {
    const searchLower = searchTerm.toLowerCase();
    const userName = agency.user_name?.toLowerCase().includes(searchLower);
    const firstName = agency.first_name?.toLowerCase().includes(searchLower);
    const lastName = agency.last_name?.toLowerCase().includes(searchLower);
    return userName || firstName || lastName;
  });

  const managepost = filteredData?.map((agency: any, index: number) => ({
    'id': agency.id,
    "Sr. No": index + 1,
    "Emp ID": agency.unique_id,
    "First Name": agency.first_name,
    "last Name": agency.last_name,
    "DOB": formatDateOfBirth(agency.date_of_birth),
    "Gender": agency.gender,

    "Action": (
      <HStack justifyContent="center">
        {/* <EditDetails rowData={{ id: agency.id, question: agency.question, answer: agency.answer }} refetch={refetch} /> */}
        <ViewSubAdmin id={agency.id} />
        <EditSubAdmin id={agency.id} refetch={refetch} allPermissions={permissions} />

        <AlertDailog
          isOpen={deleteModal}
          AltertTiggerIcon={() => <Delete onClick={() => setDeleteModal(prev => !prev)} />}
          alertText="Delete sub admin"
          alertIcon={<Image src={"DeleteIcon"} h={"39px"} />}
          alertCaption="are you sure you want to delete ?"
          onClose={() => setDeleteModal(false)}
          onConfirm={() => {
            // console.log("User deleted:", index + 1);
            setDeleteModal(false);
            handleDeleteAdmin(agency.id)
          }}
        />
      </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"}>
            {/* Manage Post */}
          </Text>

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