import { DialogBody, DialogCloseTrigger, DialogContent, DialogFooter, DialogHeader, DialogRoot, DialogTitle, DialogTrigger } from "../../../components/ui/dialog"
import { Box, Field, Input, Stack, Text } from "@chakra-ui/react"
import { IoMdAdd } from "react-icons/io"
import { Button } from "../../../components/ui/button"
import { FiUpload } from "react-icons/fi";
import { useEffect, useState } from "react";
// import { useCreateTemplatePostMutation } from "../../../Redux/Service/template.master.service";
import { Toaster, toaster } from "../../../components/ui/toaster"
import axios from "axios";

const APIURL = import.meta.env.VITE_API_URL

function TemplateAddModel({ refetch }: { refetch: VoidFunction }) {
    const [title, setTitle] = useState("");
    const [subTitle, setSubTitle] = useState("");
    const [userType, setUserType] = useState<number | "">("");
    const [images, setImages] = useState<(File | string)[]>([]);
    // const [createTemplatePost] = useCreateTemplatePostMutation()
    const [isOpen, setIsOpen] = useState(false);
    const [isLoading, setIsLoading] = useState(false);
    const token = localStorage.getItem("token");

    useEffect(() => {
        if (!isOpen) {
            setTitle("");
            setSubTitle("");
            setUserType("");
            setImages([]);
        }
    }, [isOpen]);

    if (!token) {
        console.error("No token found in localStorage!");
        return null;
    }
    
    const handleOpenModal = () => {
        setIsOpen(true);  // Open modal when clicking "Add"
    };


    const handleImageChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
        if (event.target.files) {
            const file = event.target.files[0];
            if (!["image/jpeg", "image/jpg", "image/png"].includes(file.type)) {
                toaster.create({
                    title: "Error",
                    description: "Only JPEG, JPG, and PNG files are allowed.",
                    type: "error",
                });
                return;
            }

            // setImages((prevImages) => [...prevImages, file]);
            if(file){
                setImages([file])
            }
        }
    };


    const handleSubmit = async () => {
        if (!title || !subTitle || images.length === 0) {
            toaster.create({
                title: "Error",
                description: "Please fill in all required fields and upload at least one image.",
                type: "error",
            });
            return;
        }

        if (userType === "" || isNaN(Number(userType))) {
            toaster.create({
                title: "Error",
                description: "Please select a valid user type.",
                type: "error",
            });
            return;
        }

        // const payload = {
        //     id: id,
        //     principle_type_xid: userType,
        //     title,
        //     sub_title: subTitle,
        //     image_name: images.filter((img) => typeof img === "string"), // Send only Base64 strings
        // };

        setIsLoading(true);

        const formData = new FormData();
        formData.append("principle_type_xid", `${userType}`);
        formData.append("title", title);
        formData.append("sub_title", subTitle);

        images.forEach((image, index) => {
            if (image instanceof File) {
                formData.append(`image_name[${index}]`, image, image.name);  // Ensure indexed naming
            }
        });

        if (token) {
            const payload = JSON.parse(atob(token.split(".")[1]));
            console.log("Token Payload:", payload);
        }

        try {
            // await createTemplatePost(formData)
            if (token) {
                await axios.post(`${APIURL}/template-store`, formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        'access-token': `${token}`,
                    },
                    // withCredentials: true,
                });
            }
            refetch();
            setTitle("");
            setSubTitle("");
            setUserType("");
            setImages([]);
            setIsOpen(false)
            setIsLoading(false);
        } catch (error: any) {
            console.error("Error creating template:", error);
            // alert("Failed to create template");
            toaster.create({
                title: "Error",
                description: `${error.response?.data?.message || "Please try again later."}`,
                type: "error",
            });
        }
    };

    // console.log("Token stored:", window.localStorage.getItem("token"))      


    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">Title</Field.Label>
                            <Input
                                placeholder="Enter Title"
                                bgColor="#EEEEEE"
                                color="black"
                                border="none"
                                pl={1}
                                fontSize="12px"
                                height="30px"
                                value={title}
                                onChange={(e) => setTitle(e.target.value)}
                            />
                        </Field.Root>

                        <Field.Root>
                            <Field.Label color="black" pt={1} fontSize="12px">Subtitle</Field.Label>
                            <Input
                                placeholder="Enter subtitle"
                                bgColor="#EEEEEE"
                                color="black"
                                border="none"
                                pl={1}
                                fontSize="12px"
                                height="30px"
                                value={subTitle}
                                onChange={(e) => setSubTitle(e.target.value)}
                            />
                        </Field.Root>

                        <Field.Root>
                            <Field.Label color="black" pt={1} fontSize="12px">Select User Type</Field.Label>
                            <Box bgColor="#EEEEEE" borderRadius="md" p={1}>
                                <select
                                    style={{
                                        width: "100%",
                                        background: "transparent",
                                        color: "black",
                                        border: "none",
                                        fontSize: "12px",
                                        height: "30px",
                                        outline: "none",
                                    }}
                                    value={userType}
                                    onChange={(e) => setUserType(Number(e.target.value))}
                                >
                                    <option value="">Select User Type</option>
                                    <option value="2">Recruiter</option>
                                    <option value="3">Jobseeker</option>
                                </select>
                            </Box>
                        </Field.Root>

                        <Field.Root>
                            <Field.Label color="black" pt={1} fontSize="12px">Images</Field.Label>
                            <Box display="flex" alignItems="center" justifyContent="space-between" px={3} bgColor="#EEEEEE" border="none" width="100%" height="50px" cursor="pointer" position="relative">
                                <Input type="file" accept="image/*" opacity={0} position="absolute" bgColor="#EEEEEE" border="none" pl={1} width="100%" height="100%" cursor="pointer" onChange={handleImageChange} />
                                <Box display="flex" gap={2} overflow="hidden">
                                    {images.length > 0 ? (
                                        images.map((img, index) => (
                                            <img
                                                key={index}
                                                src={img instanceof File ? URL.createObjectURL(img) : img}
                                                alt={`Uploaded ${index}`}
                                                style={{ maxHeight: "40px", maxWidth: "70px", objectFit: "contain" }}
                                            />
                                        ))
                                    ) : (
                                        <Box width="70px" height="40px" /> // Placeholder to maintain layout
                                    )}
                                </Box>
                                <FiUpload color="#000" />
                            </Box>

                            {/* <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} disabled={isLoading}>
                        Save
                    </Button>
                </DialogFooter>

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

    )
}

export default TemplateAddModel