import { Field, Grid, Heading, Input, Stack, Text } from "@chakra-ui/react";
// import { TbEdit } from "react-icons/tb";
import { Button } from "../../components/ui/button";
import { Checkbox } from "../../components/ui/checkbox";
import {
  DialogBody,
  DialogCloseTrigger,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogRoot,
  DialogTitle,
  DialogTrigger,
} from "../../components/ui/dialog";
import Edit from "../../components/ActionIcons/Edit";
import { PermissionResponse, useLazyViewSubAdminQuery, useUpdateSubAdminMutation } from "../../Redux/Service/manage.subadmin.service";
import { useEffect, useState } from "react";
import { Toaster, toaster } from "../../components/ui/toaster";

const resourceIdToLabel: { [key: number]: string } = {
  1: 'Dashboard',
  2: 'Manage User',
  3: 'Manage Post',
  4: 'Manage Subadmin',
  5: 'Manage Jobs',
  6: 'Manage Groups',
  7: 'Manage Contact Us',
  8: 'Manage CMS',
  9: 'My Profile',
  10: 'Master Module',
};


interface ResourceActionLink {
  id: number;
  app_resource_xid: number;
  is_active: boolean;
  app_resource: {
    id: number,
    app_resource_title: string
  }
}

function EditSubAdmin({ id, refetch, allPermissions }: { id: number, refetch: VoidFunction, allPermissions?: PermissionResponse }) {
  const [trigger, { data }] = useLazyViewSubAdminQuery();
  const [updateSubAdmin, {isLoading}] = useUpdateSubAdminMutation()
  const [isOpen, setIsOpen] = useState(false);
  const [editData, setEditData] = useState<{
    id: string;
    unique_id?: string,
    first_name: string;
    last_name: string;
    date_of_birth: string;
    gender?: string,
    permission: ResourceActionLink[];
  }>({
    id: '',
    unique_id: '',
    first_name: '',
    last_name: '',
    date_of_birth: '',
    gender: '',
    permission: [],
  })

  useEffect(() => {
    if (data?.data?.length && allPermissions?.data?.permission?.length) {
      const subAdmin = data.data[0];

      const activePermissionIds = subAdmin.get_resource_action_link
        .filter((perm: any) => perm.is_active)
        .map((perm: any) => perm.app_resource_xid);

      const mergedPermissions: ResourceActionLink[] = allPermissions.data.permission.map((perm) => ({
        id: perm.id,
        app_resource_xid: perm.id,
        is_active: activePermissionIds.includes(perm.id),
        app_resource: {
          id: perm.id,
          app_resource_title: perm.app_resource_title,
        },
      }));


      // Map the API response to editData
      setEditData({
        id: subAdmin.id.toString(),
        unique_id: subAdmin.unique_id,
        first_name: subAdmin.first_name,
        last_name: subAdmin.last_name,
        date_of_birth: formatDateOfBirth(subAdmin.date_of_birth),
        gender: subAdmin.gender,
        permission: mergedPermissions,
      });
    }
  }, [data, allPermissions]);

  const formatDateOfBirth = (dob: string): string => {
    // Convert the date to the desired format with slashes
    const formattedDate = new Date(dob).toLocaleDateString("en-GB", {
      day: "2-digit",
      month: "2-digit",
      year: "numeric",
    });

    // Replace slashes with hyphens
    return formattedDate.replace(/\//g, '-');
  };

  const handleOpenModal = () => {
    trigger(id)
    setIsOpen(true);
  };

  const handleCheckboxToggle = (permissionId: number) => {
    setEditData((prevData) => ({
      ...prevData,
      permission: prevData.permission.map((permission) =>
        permission.app_resource_xid === permissionId
          ? { ...permission, is_active: !permission.is_active }
          : permission
      ),
    }));
  };


  const handleSubmit = async () => {
    console.log('Updated Data:', editData);
    // Call your API here with the updated editData

    const payload = {
      id: Number(editData.id),
      // unique_id: editData.unique_id,
      first_name: editData.first_name,
      last_name: editData.last_name,
      date_of_birth: editData.date_of_birth,
      gender: editData.gender,
      permission: editData.permission
        .filter((p) => p.is_active)
        .map((p) => p.app_resource_xid),
    };

    try {
      const response = await updateSubAdmin(payload).unwrap();
      if (response?.status === "success") {
        toaster.create({
          title: "Success",
          description: "FAQ updated successfully",
          type: "success",
        });
        refetch()
        setIsOpen(false);
      } else {
        toaster.create({
          title: "Error",
          description: "Failed to update FAQ",
          type: "error",
        });
      }
    } catch (error) {
      console.error("Error updating template:", error);
      // alert("Failed to update template");
    }
  };

  return (
    <DialogRoot placement="center" open={isOpen} onOpenChange={({ open }) => setIsOpen(open)}>
      <DialogTrigger asChild>
        {/* <FaRegEdit style={{ cursor: "pointer" }} color="#000" /> */}

        <Button bg="transparent" color={"black"} h={"18px"} onClick={handleOpenModal}><Edit /></Button>
        {/* <Button><FaRegEdit /></Button> */}
      </DialogTrigger>

      <DialogContent
        bg={"#fff"}
        w={{ base: "90%", md: "400px" }}
        height={"80vh"}
        overflow={"scroll"}
        overflowX="hidden"
        p={3} // Reduced padding
        bgSize={"md"}
      >
        <DialogHeader bg="white">
          <DialogTitle alignSelf="center" color="black" fontSize="14px">
            Edit Sub Admin Account
          </DialogTitle>
        </DialogHeader>

        <DialogBody bg="white">
          <Stack py={3}>
            <Field.Root>
              {/* <Field.Label color="black" pt={1} fontSize="12px">
                ID
              </Field.Label>
              <Input
                placeholder="Enter the First Name"
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
                value={editData.unique_id}
                onChange={(e) => setEditData({ ...editData, unique_id: e.target.value })}
              /> */}

              <Field.Label color="black" pt={1} fontSize="12px">
                First Name
              </Field.Label>
              <Input
                placeholder="Enter the First Name"
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
                value={editData.first_name}
                onChange={(e) => setEditData({ ...editData, first_name: e.target.value })}
              />
              <Field.Label color="black" pt={1} fontSize="12px">
                Last Name
              </Field.Label>
              <Input
                placeholder="Enter the Last Name"
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
                value={editData.last_name}
                onChange={(e) => setEditData({ ...editData, last_name: e.target.value })}
              />

              <Field.Label color="black" pt={1} fontSize="12px">
                DOB
              </Field.Label>
              <Input
                placeholder="Enter the DOB"
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
                value={editData.date_of_birth}
                onChange={(e) => setEditData({ ...editData, date_of_birth: e.target.value })}
              />

              <Field.Label color="black" pt={1} fontSize="12px">
                Gender
              </Field.Label>
              <Input
                placeholder="Enter the Gender"
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
                value={editData.gender}
                onChange={(e) => setEditData({ ...editData, gender: e.target.value })}
              />
              <Heading mt={5} color={"#000"} fontSize={"sm"}>
                Permissions
              </Heading>
            </Field.Root>
            <Grid templateColumns="repeat(2, 1fr)" gap={4}>
              {editData.permission.map((permission) => {
                const label = resourceIdToLabel[permission.app_resource_xid];
                return (
                  <Checkbox
                    key={permission.id}
                    size="sm"
                    color="black"
                    checked={permission.is_active}
                    onChange={() => handleCheckboxToggle(permission.app_resource_xid)}
                    cursor={'pointer'}
                  >
                    <Text fontSize={12}>{label}</Text>
                  </Checkbox>
                );
              })}
            </Grid>
          </Stack>
        </DialogBody>
        <DialogFooter display="flex" justifyContent="center" pt={"2"}>
          <Button size={"xs"} w="100%" bg="#02A0A0" color={"#fff"} onClick={handleSubmit} disabled={isLoading}>
            Save
          </Button>
        </DialogFooter>
        <DialogCloseTrigger color="black" onClick={() => setIsOpen(false)} />
      </DialogContent>
      <Toaster />
    </DialogRoot>
  );
}

export default EditSubAdmin;
