import { DialogBody, DialogCloseTrigger, DialogContent, DialogFooter, DialogHeader, DialogRoot, DialogTitle, DialogTrigger } from "../../../components/ui/dialog"
import { Field, Input, Stack, Text } from "@chakra-ui/react"
import { IoMdAdd } from "react-icons/io"
import { Button } from "../../../components/ui/button"
import { AgencyPost, useCreateAgencyMasterPostMutation } from "../../../Redux/Service/agency.master.module.service"
import { useState } from "react"
import { Toaster, toaster } from "../../../components/ui/toaster"

function ViewAgencyAddModel({ refetch }: { refetch: VoidFunction }) {
    const [formData, setFormData] = useState<AgencyPost>({
        name: "",
        rc_number: "",
        state: "",
        registered_office: "",
        domain_name: "",
        gst_number: "",
    });
    const [isOpen, setIsOpen] = useState(false);
    const [createAgencyMasterPost] = useCreateAgencyMasterPostMutation()

    const handleOpenModal = () => {
        setIsOpen(true);  // Open modal when clicking "Add"
    };

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

    const handleSubmit = async () => {
        console.log("New Data:", formData);
        const requiredFields: (keyof AgencyPost)[] = ["name", "rc_number", "state", "registered_office", "domain_name", "gst_number"];
        const isEmptyField = requiredFields.some(field => !formData[field]?.trim());

        if (isEmptyField) {
            console.log("Validation failed: Some fields are empty.");
            toaster.create({
                title: "Error",
                description: "All required fields must be filled.",
                type: "error",
            });
            return;
        }

        const payload = {
            name: formData.name
        };

        try {
            const response = await createAgencyMasterPost(payload).unwrap();
            if (response) {
                toaster.create({
                    title: "Success",
                    description: "Added successfully",
                    type: "success",
                });
                refetch()
                setIsOpen(false);
            } else {
                toaster.create({
                    title: "Error",
                    description: "Failed to add data.",
                    type: "error",
                });
            }
        } catch (error) {
            console.error("Error updating template:", error);
            toaster.create({
                title: "Error",
                description: "Please try again later",
                type: "error",
            });

        }
    };

    return (

        <DialogRoot placement="center" open={isOpen} onOpenChange={({ open }) => setIsOpen(open)}>
            <DialogTrigger asChild>
                <Button px={5} size={"xs"} bg={"#02A0A0"} onClick={handleOpenModal}>
                    <IoMdAdd /> <Text >Add</Text>
                </Button>
            </DialogTrigger>

            <DialogContent
                bg={"#fff"}
                // w={{ lg: "60%", md: "230px" }}
                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">Add</DialogTitle>
                </DialogHeader>

                <DialogBody bg="white">
                    <Stack py={3}>

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

                            <Field.Label color="black" pt={1} fontSize="12px">RC No.</Field.Label>
                            <Input
                                name='rc_number'
                                value={formData.rc_number}
                                bgColor="#EEEEEE"
                                color="black"
                                border="none"
                                pl={1}
                                fontSize="12px"
                                height="30px"
                                onChange={handleChange}
                            />

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

                            <Field.Label color="black" pt={1} fontSize="12px">Registered Office Address</Field.Label>
                            <Input
                                name="registered_office"
                                value={formData.registered_office}
                                bgColor="#EEEEEE"
                                color="black"
                                border="none"
                                pl={1}
                                fontSize="12px"
                                height="30px"
                                onChange={handleChange}
                            />

                            <Field.Label color="black" pt={1} fontSize="12px">Website/Domain</Field.Label>
                            <Input
                                name="domain_name"
                                value={formData.domain_name}
                                bgColor="#EEEEEE"
                                color="black"
                                border="none"
                                pl={1}
                                fontSize="12px"
                                height="30px"
                                onChange={handleChange}
                            />

                            <Field.Label color="black" pt={1} fontSize="12px">GST no.</Field.Label>
                            <Input
                                name="gst_number"
                                value={formData.gst_number}
                                bgColor="#EEEEEE"
                                color="black"
                                border="none"
                                pl={1}
                                fontSize="12px"
                                height="30px"
                                onChange={handleChange}
                            />

                            {/* <Field.Label color="black" pt={1} fontSize="12px">Action</Field.Label>
                            <Input placeholder="" bgColor="#EEEEEE" color="black" border="none" pl={1} fontSize="12px" height="30px" /> */}
                        </Field.Root>
                    </Stack>
                </DialogBody>
                <DialogFooter display="flex" justifyContent="center" pt={"2"}>
                    <Button w="100%" bg="#02A0A0" color={"#fff"} onClick={handleSubmit}>
                        Save
                    </Button>
                </DialogFooter>

                <DialogCloseTrigger color="black" onClick={() => setIsOpen(false)} />
            </DialogContent>
            <Toaster />
        </DialogRoot >

    )
}

export default ViewAgencyAddModel