"use client";

import {motion} from "framer-motion";
import Image from "next/image";
import infoIcon from "../../../../public/icons/info.png";
import {useState} from "react";
import DatePicker from "react-multi-date-picker";
import persian_fa from "react-date-object/locales/persian_fa";
import persian from "react-date-object/calendars/persian";
import "../../../styles/globals.css";
import DropDown from "@/components/ui/dropDown/dropDown";


export default function Input({item, index, setRequiredFieldValues, requiredFieldValues, requiredFieldErrors}) {

    const [activeIndex, setActiveIndex] = useState(null);
    const [values, setValues] = useState({});
    const [focusedDate, setFocusedDate] = useState(false); // اصلاح به boolean

    const hasValue = values[index] && values[index].toString() !== "";

    const toEnglishDigits = (str) => str.replace(/[\u06F0-\u06F9]/g, (d) => d.charCodeAt(0) - 0x06F0);


    return (
        <div className="flex flex-col gap-1">

            <motion.div
                key={item.id || index}
                initial={{opacity: 0, scale: 0.9}}
                animate={{opacity: 1, scale: 1}}
                exit={{opacity: 0, scale: 0.9, transition: {duration: 0}}}
                transition={{duration: 0.3, ease: "easeInOut"}}
                className={`inputFild border-[1.5px] w-fill mt-2 transition duration-300
                            ${item?.active ? (hasValue ? "border-success-main" : requiredFieldErrors?.[item.excelKey] ? "border-danger-main" : "border-muted") : "border-none"}`}
            >
                {item?.type === "date" ? (
                    <div
                        style={{
                            position: "relative",
                            width: "100%",
                            display: "flex",
                            alignItems: "center",
                            height: "50px", // از inputFild
                        }}
                    >
                        <DatePicker
                            id={`input-${index}`}
                            value={requiredFieldValues[item.excelKey] || ""}
                            onChange={(dateObj) => {
                                const formatted = dateObj ? dateObj.format("YYYY/MM/DD") : "";
                                const englishFormatted = formatted ? toEnglishDigits(formatted) : "";
                                setRequiredFieldValues((prev) => ({
                                    ...prev,
                                    [item.excelKey]: englishFormatted,
                                }));
                            }}
                            calendar={persian}
                            locale={persian_fa}
                            format="YYYY/MM/DD"
                            calendarPosition="auto"
                            placeholder={item.placeHolder
                                ? `نمونه ${item?.placeHolder}`
                                : "----"
                            }
                            style={{
                                fontWeight: 500, // font-medium
                                fontSize: "16px", // text-paragraph (فرض بر 16px)
                                outline: "none",
                                background: "transparent",
                                padding: "0 24px",
                                width: "100%",
                                height: "100%",
                                border: "none",
                                paddingRight: "40px", // فضای آیکون تقویم
                                textAlign: "right",
                                boxShadow: "none",
                                ...(item?.active
                                    ? {}
                                    : {
                                        backgroundColor: "#f9f9f9", // bg-gray-100
                                        cursor: "not-allowed",
                                        color: "#0C0D0F", // text-gray-500
                                    }),
                            }}
                            containerStyle={{
                                width: "100%",
                            }}
                            disabled={!item?.active}
                            onOpen={() => {
                                if (item?.active) {
                                    setActiveIndex(index);
                                    setFocusedDate(true);
                                }
                            }}
                            onClose={() => {
                                setActiveIndex(null);
                                setFocusedDate(false);
                            }}
                        />

                        {/* Label */}
                        <label
                            htmlFor={`input-${index}`}
                            onClick={() => {
                                if (item?.active) {
                                    setActiveIndex(index);
                                    setFocusedDate(true);
                                }
                            }}
                            style={{
                                display: "flex",
                                alignItems: "center",
                                gap: "4px",
                                cursor: "pointer",
                                position: "absolute",
                                right: "20px",
                                top: "-16px",
                                color: item?.active ? "#0C0D0F" : "#9ca3af",
                                transition: "all 0.2s ease-in",
                                padding: "0 16px",
                                background: "#f8f8f8",
                                zIndex: 20,
                            }}
                        >
                            {item?.name}
                            <Image style={{width: "16px", height: "16px"}} src={infoIcon} alt=""/>
                        </label>
                    </div>
                ) : (
                    item?.type === "select" || item?.type === "boolean" ?
                        <DropDown item={item} index={index} setRequiredFieldValues={setRequiredFieldValues}/>
                        :
                        <>
                            <input
                                type={item.type}
                                id={`input-${index}`}
                                placeholder={item.placeHolder ? `نمونه ${item?.placeHolder}` : "----"}
                                value={requiredFieldValues?.[item.excelKey] || ""}
                                onChange={(e) =>
                                    setRequiredFieldValues((prev) => ({...prev, [item.excelKey]: e.target.value}))
                                }
                                className="input font-medium text-paragraph outline-none bg-transparent px-6 w-full h-full rounded-[16px]"
                                onFocus={() => {
                                    if (item?.active) setActiveIndex(index);
                                }}
                                onBlur={() => setActiveIndex(null)}
                                readOnly={!item?.active}
                            />
                            <label
                                className={`label flex items-center gap-1 ${
                                    item?.active ? "" : "top-4"
                                }`}
                                htmlFor={`input-${index}`}
                                onClick={() => {
                                    if (item?.active) setActiveIndex(index);
                                }}
                            >
                                {item?.name}
                                <Image className="w-4 h-4" src={infoIcon} alt=""/>
                            </label>
                        </>
                )}
            </motion.div>

            <span
                className="text-[12px] font-bold text-danger-main">{requiredFieldErrors?.[item.excelKey] && requiredFieldErrors?.[item.excelKey]}</span>

        </div>
    );
}