import { useState } from "react";
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 { useCreateSubAdminPostMutation } from "../../Redux/Service/manage.subadmin.service";
import { toaster } from "../../components/ui/toaster";

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

  const [formData, setFormData] = useState({
    firstName: "",
    lastName: "",
    dob: "",
    gender: "",
    email: "",
    phone: ""
  });

  const [isOpen, setIsOpen] = useState(false);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

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

    const payload = {
    //   principal_type_xid: 4,
    //   principal_source_xid: 1,
    //   user_name: `${firstName} ${lastName}`,
      first_name: firstName,
      last_name: lastName,
      date_of_birth: dob,
      gender,
      email_address: email,   
      phone_number: phone,
      created_by: 1,
    };

    try {
      const response = await createSubAdminPost(payload).unwrap();
      
      if (response.status === "success") {
        toaster.create({
          title: "Success",
          description: response.message || "Sub-admin added successfully",
          type: "success",
        });
        refetch();
        setIsOpen(false);
      }
    } catch (error: any) {
      toaster.create({
        title: "Error",
        description: error?.data?.message || "Failed to create sub-admin",
        type: "error",
      });
    }
  };

  return (
    <DialogRoot
      open={isOpen}
      onOpenChange={(details) => setIsOpen(details.open)}
      placement="center"
    >
      <DialogTrigger asChild>
        <Button rounded={"md"} px={4} py={2} size={"xs"} bg={"#02A0A0"}>
          <IoMdAdd /> Add
        </Button>
      </DialogTrigger>

      <DialogContent
        bg={"#fff"}
        w={{ base: "90%", md: "400px" }}
        height={"80vh"}
        overflow={"scroll"}
        overflowX="hidden"
        p={3}
      >
        <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
                name="firstName"
                placeholder="Enter the First Name"
                value={formData.firstName}
                onChange={handleChange}
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
              />

              <Field.Label color="black" pt={1} fontSize="12px">
                Last Name
              </Field.Label>
              <Input
                name="lastName"
                placeholder="Enter the Last Name"
                value={formData.lastName}
                onChange={handleChange}
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
              />

              <Field.Label color="black" pt={1} fontSize="12px">
                DOB
              </Field.Label>
              <Input
                name="dob"
                placeholder="YYYY-MM-DD"
                value={formData.dob}
                onChange={handleChange}
                type="date"
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
              />

              <Field.Label color="black" pt={1} fontSize="12px">
                Gender
              </Field.Label>
              <Input
                name="gender"
                placeholder="Enter the Gender"
                value={formData.gender}
                onChange={handleChange}
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
              />

              <Field.Label color="black" pt={1} fontSize="12px">
                Email
              </Field.Label>
              <Input
                name="email"
                placeholder="Enter the Email"
                value={formData.email}
                onChange={handleChange}
                type="email"
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
              />

              <Field.Label color="black" pt={1} fontSize="12px">
                Phone Number
              </Field.Label>
              <Input
                name="phone"
                placeholder="Enter the Phone Number"
                value={formData.phone}
                onChange={handleChange}
                type="tel"
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
              />

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

            <Grid templateColumns="repeat(2, 1fr)" gap={4}>
              <Checkbox size={"sm"} color={"black"}>
                <Text fontSize={12}>Dashboard</Text>
              </Checkbox>
              <Checkbox size={"sm"} color={"black"}>
                <Text fontSize={12}>Manage contact us</Text>
              </Checkbox>
              <Checkbox size={"sm"} color={"black"}>
                <Text fontSize={12}>Manage User</Text>
              </Checkbox>
              <Checkbox size={"sm"} color={"black"}>
                <Text fontSize={12}>Manage CMS</Text>
              </Checkbox>
              <Checkbox size={"sm"} color={"black"}>
                <Text fontSize={12}>Manage Post</Text>
              </Checkbox>
              <Checkbox size={"sm"} color={"black"}>
                <Text fontSize={12}>Manage Reports</Text>
              </Checkbox>
              <Checkbox size={"sm"} color={"black"}>
                <Text fontSize={12}>Manage Sub-Admin</Text>
              </Checkbox>
              <Checkbox size={"sm"} color={"black"}>
                <Text fontSize={12}>My Profile</Text>
              </Checkbox>
              <Checkbox size={"sm"} color={"black"}>
                <Text fontSize={12}>Manage Jobs</Text>
              </Checkbox>
              <Checkbox size={"sm"} color={"black"}>
                <Text fontSize={12}>Manage Feedbacks</Text>
              </Checkbox>
              <Checkbox size={"sm"} color={"black"}>
                <Text fontSize={12}>Manage Community</Text>
              </Checkbox>
              <Checkbox size={"sm"} color={"black"}>
                <Text fontSize={12}>Notification</Text>
              </Checkbox>
            </Grid>
          </Stack>
        </DialogBody>

        <DialogFooter display="flex" justifyContent="center" pt={"2"}>
          <Button
            size={"xs"}
            w="100%"
            bg="#02A0A0"
            color={"#fff"}
            onClick={handleSubmit}
            // isLoading={isLoading}
            disabled={isLoading}
          >
            Save
          </Button>
        </DialogFooter>

        <DialogCloseTrigger color="black" />
      </DialogContent>
    </DialogRoot>
  );
}

export default AddModel;
