import {
    DialogBody,
    DialogCloseTrigger,
    DialogContent,
    DialogFooter,
    DialogHeader,
    DialogRoot,
    DialogTitle,
    DialogTrigger,
} from "../../../components/ui/dialog";
import { Box, Field, Input, Stack } from "@chakra-ui/react";
import { Button } from "../../../components/ui/button";
import Edit from "../../../components/ActionIcons/Edit";
import { useState } from "react";
import { Toaster, toaster } from "../../../components/ui/toaster";
import { useGetDepartmentMasterDropDownQuery, useUpdateDepartmentMutation } from "../../../Redux/Service/department.master";

function EditDepartmentMaster({ localData, refetch }: { localData: any, refetch: VoidFunction }) {
    const [jobtype, setJobType] = useState("");
    const [updateDepartment, { isLoading }] = useUpdateDepartmentMutation()
    const { data } = useGetDepartmentMasterDropDownQuery()
    const [isOpen, setIsOpen] = useState(false);
    const [selectdDep, setSelectdDep] = useState<any>({
        id: localData.industry_master.id,
        en_name: localData.industry_master.en_name,
    });

    const handleOpenModal = () => {
        // const template = localData?.find((item: any) => item.id === id);
        if (localData) {
            setJobType(localData.en_name);
            setSelectdDep({
                id: localData.industry_master.id,
                en_name: localData.industry_master.en_name,
            })
            setIsOpen(true);
        }
    };


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

        const payload = {
            id: localData.id,
            industry_masters_xid: selectdDep.id != null ? selectdDep.id : localData.industry_master.id,
            en_name: jobtype
        };

        try {
            await updateDepartment(payload).unwrap();
            refetch()
            setIsOpen(false);
        } catch (error) {
            console.error("Error updating template:", error);
            alert("Failed to update template");
        }
    };

    console.log("Dropdown Data", selectdDep);
    console.log("Dep Data", localData)


    return (
        <DialogRoot placement="center" open={isOpen} onOpenChange={({ open }) => setIsOpen(open)}>
            <DialogTrigger asChild>
                <Box bg={"transparent"} onClick={handleOpenModal}>
                    <Edit />
                </Box>
            </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">
                        Edit Title
                    </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 selected = data?.data.find((item: any) => item.id === Number(e.target.value));
                                    if (selected) {
                                        setSelectdDep({ id: selected.id, en_name: selected.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
                                value={jobtype}
                                bgColor="#EEEEEE"
                                color="black"
                                border="none"
                                pl={1}
                                fontSize="12px"
                                height="30px"
                                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>
            <Toaster />
        </DialogRoot>
    );
}

export default EditDepartmentMaster;
