'use client';

import { useState, useRef, useEffect } from 'react';
import { Tick02Icon } from '@zen/core/shared/icons';

const ROW1 = ['#4489ed', '#2a9db0', '#43b53c', '#5e7b4e', '#f5c211', '#f7581f', '#ff2b2b', '#ff2e63', '#f540ed', '#b34ce9', '#818faf', '#c0bfbc'];
const ROW2 = ['#2657cf', '#24687a', '#287124', '#384d2f', '#c68408', '#c0280e', '#ca0505', '#ce0245', '#b417a7', '#8021aa', '#4e5b7e', '#75746f'];
const ROW3 = ['#233f85', '#234856', '#1e4a1d', '#263321', '#834a10', '#7b1e13', '#8d0f0f', '#93083e', '#78176c', '#5b1d72', '#373f55', '#282725'];
const PRESET_COLORS = [...ROW1, ...ROW2, ...ROW3];

const isValidHex = (hex) => /^#[0-9a-fA-F]{6}$/.test(hex);

const Checkmark = () => <Tick02Icon className="w-4 h-4 text-white drop-shadow-sm" />;

const ColorPicker = ({
    value,
    onChange,
    label,
    description,
    required = false,
    disabled = false,
}) => {
    const nativeRef = useRef(null);
    const selected = isValidHex(value) ? value.toLowerCase() : '#6b7280';
    const [hexInput, setHexInput] = useState(selected);

    useEffect(() => {
        if (isValidHex(value)) setHexInput(value.toLowerCase());
    }, [value]);

    const isCustom = !PRESET_COLORS.map(c => c.toLowerCase()).includes(selected);

    const handleSwatchClick = (color) => {
        if (disabled) return;
        setHexInput(color);
        onChange?.(color);
    };

    const handleHexChange = (e) => {
        const raw = e.target.value;
        setHexInput(raw);
        const normalized = raw.startsWith('#') ? raw : `#${raw}`;
        if (isValidHex(normalized)) onChange?.(normalized.toLowerCase());
    };

    const handleHexBlur = () => {
        const normalized = hexInput.startsWith('#') ? hexInput : `#${hexInput}`;
        if (isValidHex(normalized)) {
            const lower = normalized.toLowerCase();
            setHexInput(lower);
            onChange?.(lower);
        } else {
            setHexInput(selected);
        }
    };

    const handleNativeChange = (e) => {
        const color = e.target.value.toLowerCase();
        setHexInput(color);
        onChange?.(color);
    };

    return (
        <div className="flex flex-col gap-2">
            {label && (
                <label className="block text-xs font-medium text-neutral-700 dark:text-white">
                    {label}
                    {required && <span className="text-red-500 dark:text-red-400 ml-1">*</span>}
                </label>
            )}
            {description && (
                <p className="text-xs text-neutral-500 dark:text-neutral-400">{description}</p>
            )}

            <div className="flex flex-wrap items-start gap-3">
                {/* Left: big custom swatch + hex input */}
                <div className="flex flex-col gap-2 w-18 flex-shrink-0">
                    <button
                        type="button"
                        title="Couleur personnalisée"
                        onClick={() => !disabled && nativeRef.current?.click()}
                        disabled={disabled}
                        className="relative w-full h-14 rounded-xl flex items-center justify-center disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition-opacity hover:opacity-90 focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:ring-neutral-400"
                        style={{ backgroundColor: selected }}
                    >
                        {isCustom && <Checkmark />}
                        <input
                            ref={nativeRef}
                            type="color"
                            value={selected}
                            onChange={handleNativeChange}
                            disabled={disabled}
                            className="absolute inset-0 opacity-0 w-full h-full cursor-pointer"
                            tabIndex={-1}
                        />
                    </button>
                    <input
                        type="text"
                        value={hexInput}
                        onChange={handleHexChange}
                        onBlur={handleHexBlur}
                        disabled={disabled}
                        maxLength={7}
                        placeholder="#6b7280"
                        className="w-full px-2 py-[7px] rounded-lg text-[12px] text-center focus:outline-none transition-all duration-[120ms] ease-out disabled:opacity-50 disabled:cursor-not-allowed bg-white border border-neutral-300 text-neutral-900 placeholder-neutral-400 focus:border-neutral-500 focus:ring-1 focus:ring-neutral-500/20 dark:bg-neutral-900/60 dark:border-neutral-700/50 dark:text-white dark:placeholder-neutral-500 dark:focus:border-neutral-600 dark:focus:ring-neutral-600/20 font-mono uppercase"
                    />
                </div>

                {/* Right: 10×3 preset grid */}
                <div className="flex flex-col gap-1.5">
                    {[ROW1, ROW2, ROW3].map((row, rowIdx) => (
                        <div key={rowIdx} className="flex gap-1.5">
                            {row.map((color) => {
                                const isSelected = selected === color.toLowerCase();
                                return (
                                    <button
                                        key={color}
                                        type="button"
                                        title={color}
                                        onClick={() => handleSwatchClick(color)}
                                        disabled={disabled}
                                        className="w-7 h-7 rounded-md flex-shrink-0 flex items-center justify-center disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition-transform hover:scale-110 focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:ring-neutral-400"
                                        style={{ backgroundColor: color }}
                                    >
                                        {isSelected && <Checkmark />}
                                    </button>
                                );
                            })}
                        </div>
                    ))}
                </div>
            </div>
        </div>
    );
};

export default ColorPicker;
