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 { useState } from "react";
import { toaster } from "../../../components/ui/toaster";
import { useCreateDepartmentPostMutation, useGetDepartmentMasterDropDownQuery } from "../../../Redux/Service/department.master";

function AddDepartmentMaster({ refetch }: { refetch: VoidFunction }) {
    const [jobType, setJobType] = useState("");
    const [isOpen, setIsOpen] = useState(false);
    const [createDepartmentPost, { isLoading }] = useCreateDepartmentPostMutation()
    const { data } = useGetDepartmentMasterDropDownQuery()
    const [selectdDep, setSelectdDep] = useState<any>({
        id: '',
        en_name: '',
    });


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

    const handleSubmit = async () => {
        if (!jobType.trim() || !selectdDep.id) {
            toaster.create({
                title: "Error",
                description: "Title and Subtitle cannot be empty.",
                type: "error",
            });
            return;
        }

        const payload = {
            en_name: jobType,
            industry_masters_xid: selectdDep.id,
        };

        try {
            await createDepartmentPost(payload);
            refetch()
            setIsOpen(false);
            setJobType("");
            setSelectdDep({
                id: '',
                en_name: '',
            })
        } catch (error) {
            console.error("Error updating template:", error);
            alert("Failed to update template");
        }
    };

    console.log("Selected Department", selectdDep);


    return (

        <DialogRoot placement="center" open={isOpen}>
            <DialogTrigger asChild>
                {/* <Button bg={"transparent"} size="sm">
                    <MdOutlineRemoveRedEye style={{ cursor: "pointer", fontSize: "16px" }} />
                </Button> */}
                <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={'auto'}

                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">
                                Select Industry
                            </Field.Label>
                            <select
                                value={selectdDep.id}
                                onChange={(e) => {
                                    const selectedId = e.target.value;
                                    const selectedIndustry = data?.data.find((item: any) => item.id.toString() === selectedId);
                                    if (selectedIndustry) {
                                        setSelectdDep({
                                            id: selectedIndustry.id,
                                            en_name: selectedIndustry.en_name,
                                        });
                                    }
                                }}
                                style={{
                                    backgroundColor: "#EEEEEE",
                                    color: "black",
                                    border: "none",
                                    height: "30px",
                                    fontSize: "12px",
                                    padding: "4px",
                                    borderRadius: "4px",
                                    width: "100%",
                                }}
                            >
                                <option value="" disabled>
                                    Select department
                                </option>
                                {data?.data.map((item: any) => (
                                    <option value={item.id} key={item.id}>
                                        {item.en_name}
                                    </option>
                                ))}
                            </select>
                        </Field.Root>

                        <Field.Root>
                            <Field.Label color="black" pt={1} fontSize="12px">Department</Field.Label>
                            <Input
                                placeholder=""
                                bgColor="#EEEEEE"
                                color="black"
                                border="none"
                                pl={1}
                                fontSize="12px"
                                height="30px"
                                value={jobType}
                                onChange={(e) => setJobType(e.target.value)}
                            />
                        </Field.Root>
                    </Stack>

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

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

    )
}

export default AddDepartmentMaster