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

function AddModel({ refetch, allPermissions }: { refetch: VoidFunction, allPermissions?: PermissionResponse }) {
  const [createSubAdminPost, { isLoading }] = useCreateSubAdminPostMutation();

  // State fields
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  // const [userName, setUserName] = useState("");
  const [dateOfBirth, setDateOfBirth] = useState("");
  const [gender, setGender] = useState("");
  const [email, setEmail] = useState("");
  const [phonenumber, setPhonenumber] = useState("");
  const [permissions, setPermission] = useState<number[]>([]);
  const [isOpen, setIsOpen] = useState(false);
  // const [ setIsOpen] = useState(false);

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

  const handleCheckboxToggle = (permissionId: number) => {
    setPermission((prevData) =>
      prevData.includes(permissionId)
        ? prevData.filter((id) => id !== permissionId)
        : [...prevData, permissionId]
    );
  };

useEffect(() => {
        if (!isOpen) {
          setFirstName("");
          setLastName("");
          // setUserName("");
          setDateOfBirth("");
          setGender("");
          setEmail("");
          setPhonenumber("");
          setPermission([]);
        }
    }, [isOpen]);

  const handleSubmit = async () => {
    if (
      !firstName.trim() ||
      !lastName.trim() ||
      !dateOfBirth.trim() ||
      !gender.trim()
    ) {
      toaster.create({
        title: "Error",
        description: "Please fill in all required fields",
        type: "error",
      });
      return;
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      toaster.create({
        title: "Invalid Email",
        description: "Please enter a valid email address",
        type: "error",
      });
      return;
    }

    if (phonenumber.length !== 10) {
      toaster.create({
        title: "Invalid Phone Number",
        description: "Phone number must be exactly 10 digits",
        type: "error",
      });
      return;
    }

    const payload = {
      // user_name: userName,
      first_name: firstName,
      last_name: lastName,
      date_of_birth: dateOfBirth,
      gender: gender,
      email_address: email,
      phone_number: phonenumber,
      permission: permissions.filter((id) => typeof id === "number"),
      // created_by: 1,
    };

    try {
      const response = await createSubAdminPost(payload).unwrap();
      if (response) {
        toaster.create({
          title: "Success",
          description: "Sub-admin created successfully",
          type: "success",
        });
        refetch();
        setFirstName("");
        setLastName("");
        // setUserName("");
        setDateOfBirth("");
        setGender("");
        setIsOpen(false);
      }
    } catch (error:any) {
      console.error("Error creating sub-admin:", error);
      toaster.create({
        title: "Error",
        description: error ? error.data.message : "Failed to create sub-admin",
        type: "error",
      });
    }
  };

  return (
    <DialogRoot placement="center" open={isOpen} onOpenChange={({ open }) => setIsOpen(open)}>
      <DialogTrigger asChild>

        <Button
          rounded={"md"}
          px={4} py={2}
          size={"xs"}
          bg={"#02A0A0"}
          onClick={handleOpenModal}>
          <IoMdAdd /> Add
        </Button>
      </DialogTrigger>

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

        <DialogBody bg="white">
          <Stack py={3}>
            <Field.Root>
              <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={firstName}
                onChange={(e) => setFirstName(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={lastName}
                onChange={(e) => setLastName(e.target.value)}
              />

              {/* <Field.Label color="black" pt={1} fontSize="12px">
                Username
              </Field.Label>
              <Input
                placeholder="Enter the Username"
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
                value={userName}
                onChange={(e) => setUserName(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"
                type="date"
                value={dateOfBirth}
                onChange={(e) => setDateOfBirth(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={gender}
                onChange={(e) => setGender(e.target.value)}
              />

              <Field.Label color="black" pt={1} fontSize="12px">
                Email Address
              </Field.Label>
              <Input
                placeholder="Enter Email address"
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                type="email"
                fontSize="12px"
                height="30px"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
              />

              <Field.Label color="black" pt={1} fontSize="12px">
                Phone Number
              </Field.Label>
              <Input
                placeholder="Enter phone number"
                bgColor="#EEEEEE"
                color="black"
                border="none"
                type="tel"
                pl={1}
                fontSize="12px"
                height="30px"
                value={phonenumber}
                onChange={(e) => {
                  const value = e.target.value;
                  if (/^\d*$/.test(value)) { // Only allow digits
                    setPhonenumber(value);
                  }
                }}
              />

              <Heading mt={5} color={"#000"} fontSize={"sm"}>
                Permissions
              </Heading>
            </Field.Root>

            <Grid templateColumns="repeat(2, 1fr)" gap={4}>
              {Array.isArray(allPermissions?.data?.permission)
                ? allPermissions.data.permission.map((permission: any) => (
                  <Checkbox
                    size="sm"
                    color="black"
                    key={permission.id}
                    checked={permissions.includes(permission.id)}
                    onChange={() => handleCheckboxToggle(permission.id)}
                  >
                    <Text fontSize={12}>{permission.app_resource_title}</Text>
                  </Checkbox>
                ))
                : <Text fontSize={12} color="gray.500">Loading permissions...</Text>
              }
            </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 AddModel;
