import Image from "next/image";
import infoIcon from "../../../../public/icons/info.png";
import {useState} from "react";
import {motion, AnimatePresence} from "framer-motion";

export default function DropDown({item, index, setRequiredFieldValues}) {
    const [show, setShow] = useState(false);
    const [selectedOption, setSelectedOption] = useState(null);

    return (
        <>
            <div className="w-full">

                <input
                    type={item.type}
                    id={`input-${index}`}
                    placeholder={"انتخاب کنید"}
                    className="input font-medium text-paragraph cursor-pointer outline-none bg-transparent px-6 w-full h-full rounded-[16px]"
                    readOnly
                    onClick={() => {
                        if (item.options) setShow((prev) => !prev);
                    }}
                    value={selectedOption?.label || ''}
                />

                <label
                    className={`label flex items-center gap-1 ${item?.active ? "" : "top-4"}`}
                    htmlFor={`input-${index}`}
                >
                    {item?.name}
                    <Image className="w-4 h-4" src={infoIcon} alt=""/>
                </label>


                <AnimatePresence>
                    {show && item.options && (
                        <motion.ul
                            initial={{opacity: 0, y: -6}}
                            animate={{opacity: 1, y: 0}}
                            exit={{opacity: 0, y: -6}}
                            transition={{duration: 0.15}}
                            className="absolute z-50 mt-4 border-primary-main w-full bg-white border rounded-xl shadow-lg overflow-hidden"
                        >
                            {item.options.map((opt, i) => (
                                <li
                                    key={i}
                                    onClick={() => {
                                        setSelectedOption(opt);
                                        setRequiredFieldValues((prev) => ({...prev, [item.excelKey]: opt.value}));
                                        setShow(false);
                                    }}
                                    className="px-4 py-2 cursor-pointer hover:bg-gray-100 transition-colors text-sm"
                                >
                                    {opt.label}
                                </li>
                            ))}
                        </motion.ul>
                    )}
                </AnimatePresence>
            </div>
        </>
    );
}
