import { type FC, useState, useEffect, useMemo } from "react";
import Input from "@/components/Input";
import Select from "@/components/Select";
import ColorPicker from "@/components/ColorPicker";
import { useEditorStore } from "@/pages/editor/store/editorStore";
import { useTextDefaultsStore } from "@/pages/editor/store/textDefaultsStore";
import {
    getDefaultFontWeight,
    getFontFamilyOptions,
    getFontWeightOptions,
    hasMultipleFontWeights,
} from "@/pages/editor/utils/fonts";
import { getFontFamily } from "@/pages/editor/utils/fontFamily";

const fontOptions = getFontFamilyOptions();


type TextFormState = {
    text: string;
    fontFamily: string;
    fontWeight: string;
    fontSize: number;
    fill: string;
    opacity: number;
    letterSpacing: number;
    wordSpacing: number;
};

const TextInstruction: FC = () => {
    const { selectedObjectId, objects, updateObject } = useEditorStore();
    const { defaults, updateDefaults } = useTextDefaultsStore();

    const selectedObject = selectedObjectId
        ? objects.find((obj) => obj.id === selectedObjectId && obj.type === "text")
        : null;

    const isEditing = !!selectedObject;
    const baseValues = useMemo(() => {
        if (isEditing && selectedObject) {
            return {
                text: selectedObject.text || "",
                fontFamily: selectedObject.fontFamily || defaults.fontFamily,
                fontWeight: selectedObject.fontWeight || defaults.fontWeight,
                fontSize: selectedObject.fontSize || defaults.fontSize,
                fill: selectedObject.fill || defaults.fill,
                opacity: selectedObject.opacity ?? defaults.opacity,
                letterSpacing: selectedObject.letterSpacing ?? defaults.letterSpacing,
                wordSpacing: selectedObject.wordSpacing ?? defaults.wordSpacing,
            };
        }
        return { text: "", ...defaults };
    }, [isEditing, selectedObject, defaults]);

    const [formState, setFormState] = useState<TextFormState>(baseValues);

    const fontWeightOptions = useMemo(
        () => getFontWeightOptions(formState.fontFamily),
        [formState.fontFamily],
    );

    const selectedFontFamily = useMemo(
        () => getFontFamily(formState.fontFamily),
        [formState.fontFamily],
    );

    const showWeightSelect = hasMultipleFontWeights(formState.fontFamily);

    useEffect(() => {
        setFormState(baseValues);
    }, [baseValues]);

    const handleChange = (field: keyof TextFormState, value: string | number) => {
        if (field === "fontFamily") {
            const nextFontId = String(value);
            const nextWeightOptions = getFontWeightOptions(nextFontId);
            const nextWeight = nextWeightOptions.some((w) => w.value === formState.fontWeight)
                ? formState.fontWeight
                : getDefaultFontWeight(nextFontId);

            if (isEditing && selectedObject) {
                const newState = { ...formState, fontFamily: nextFontId, fontWeight: nextWeight };
                setFormState(newState);
                useEditorStore.getState().commitObjectHistoryBeforeChange();
                updateObject(selectedObject.id, {
                    fontFamily: nextFontId,
                    fontWeight: nextWeight,
                });
            } else {
                setFormState((prev) => ({ ...prev, fontFamily: nextFontId, fontWeight: nextWeight }));
                updateDefaults({ fontFamily: nextFontId, fontWeight: nextWeight });
            }
            return;
        }

        if (isEditing && selectedObject) {
            // اعمال تغییرات به صورت لایو
            const newState = { ...formState, [field]: value };
            setFormState(newState);
            useEditorStore.getState().commitObjectHistoryBeforeChange();
            updateObject(selectedObject.id, { [field]: value });
        } else {
            // text فقط برای حالت ویرایش است و نباید در defaults ذخیره شود
            if (field !== "text") {
                updateDefaults({ [field]: value });
            }
        }
    };

    // State محلی برای نمایش شفافیت
    const [opacityDisplay, setOpacityDisplay] = useState<string>(`${formState.opacity}`);

    useEffect(() => {
        setOpacityDisplay(`${formState.opacity}`);
    }, [formState.opacity]);


    return (
        <div>
            <h2 className="font-bold">متن</h2>

            {isEditing && (
                <div className="mt-4">
                    <label className="text-sm mb-1 block">متن</label>
                    <textarea
                        className="w-full min-h-[80px] rounded-xl border border-border px-3 py-2 text-sm outline-none focus:border-primary resize-y"
                        value={formState.text}
                        onChange={(e) => handleChange("text", e.target.value)}
                        placeholder="متن خود را وارد کنید..."
                    />
                </div>
            )}

            <div className="mt-4">
                <Select
                    items={fontOptions}
                    placeholder="انتخاب فونت"
                    label="فونت"
                    value={formState.fontFamily}
                    onChange={(e) => handleChange("fontFamily", e.target.value)}
                    style={{ fontFamily: selectedFontFamily }}
                />
            </div>

            <div className="flex gap-2 mt-4">
                {showWeightSelect && (
                    <Select
                        label="وزن"
                        items={fontWeightOptions}
                        value={formState.fontWeight}
                        onChange={(e) => handleChange("fontWeight", e.target.value)}
                    />
                )}

                <Input
                    type="number"
                    label="سایز"
                    className={showWeightSelect ? "" : "flex-1"}
                    value={Math.round(formState.fontSize)}
                    onChange={(e) => {
                        const numValue = parseInt(e.target.value) || 0;
                        handleChange("fontSize", numValue);
                    }}
                    min={1}
                />
            </div>

            <div className="mt-4 flex flex-col gap-2">
                <div className="flex gap-3">
                    <ColorPicker
                        label="رنگ"
                        className="flex-1"
                        value={formState.fill}
                        onChange={(value) => handleChange("fill", value)}
                    />
                    <div className="w-28">
                        <Input
                            type="number"
                            label="شفافیت"
                            className="px-3"
                            value={opacityDisplay}
                            onChange={(e) => {
                                const value = e.target.value;
                                setOpacityDisplay(value);

                                // اعمال تغییرات به صورت لایو اگر مقدار معتبر است
                                const numValue = parseInt(value);
                                if (!isNaN(numValue) && numValue >= 0 && numValue <= 100) {
                                    handleChange("opacity", numValue);
                                }
                            }}
                            onBlur={(e) => {
                                const numValue = parseInt(e.target.value) || 0;
                                const clampedValue = Math.min(100, Math.max(0, numValue));
                                setOpacityDisplay(`${clampedValue}`);
                                handleChange("opacity", clampedValue);
                            }}
                            min={0}
                            max={100}
                        />
                    </div>
                </div>
            </div>

            {/* <div className="mt-4 flex gap-2">
                <Input
                    label="فاصله کلمات"
                    value={`${formState.wordSpacing}px`}
                    onChange={(e) => {
                        const value = e.target.value.replace("px", "").trim();
                        const numValue = parseInt(value) || 0;
                        handleChange("wordSpacing", numValue);
                    }}
                />

                <Input
                    label="فاصله حروف"
                    value={`${formState.letterSpacing}px`}
                    onChange={(e) => {
                        const value = e.target.value.replace("px", "").trim();
                        const numValue = parseInt(value) || 0;
                        handleChange("letterSpacing", numValue);
                    }}
                />
            </div> */}
        </div>
    );
};

export default TextInstruction;


