'use client';

import { Input } from '@admin/components/ui/input';
import { Label } from '@admin/components/ui/label';
import { cn } from '@admin/utils/common';
import { useEffect, useState } from 'react';
import { Controller, useFormContext } from 'react-hook-form';

interface HexColorPickerProps {
    name: string;
    label?: string;
    placeholder?: string;
    disabled?: boolean;
    className?: string;
    onColorChange?: (color: string) => void;
}

export const HexColorPicker = ({ name, label, placeholder = '#000000', disabled, className, onColorChange }: HexColorPickerProps) => {
    const { control } = useFormContext();
    const [displayColor, setDisplayColor] = useState('#000000');

    const isValidHex = (hex: string): boolean => {
        return /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(hex);
    };

    const handleColorChange = (color: string, onChange: (value: string) => void) => {
        // Always update the input value
        onChange(color);

        // Only update display color and trigger callback if valid hex
        if (isValidHex(color)) {
            setDisplayColor(color);
            onColorChange?.(color);
        }
    };

    return (
        <Controller
            control={control}
            name={name}
            render={({ field, fieldState }) => {
                useEffect(() => {
                    if (field.value && isValidHex(field.value)) {
                        setDisplayColor(field.value);
                    }
                }, [field.value]);

                return (
                    <div className={cn('space-y-2', className)}>
                        {label && (
                            <Label htmlFor={name} className="text-sm font-medium">
                                {label}
                            </Label>
                        )}

                        <div className="flex items-center gap-3">
                            {/* Hex Input */}
                            <div className="flex items-center gap-2">
                                {/* Native Color Input (hidden but functional) */}
                                <input
                                    type="color"
                                    value={isValidHex(field.value || '') ? field.value : displayColor}
                                    onChange={(e) => handleColorChange(e.target.value, field.onChange)}
                                    disabled={disabled}
                                    className="h-10 w-10 cursor-pointer rounded-lg"
                                    title="Click to open color picker"
                                />
                                <Input
                                    id={name}
                                    value={field.value || ''}
                                    onChange={(e) => handleColorChange(e.target.value, field.onChange)}
                                    placeholder={placeholder}
                                    disabled={disabled}
                                    className={cn('font-mono text-sm', fieldState.error && 'border-red-500')}
                                    maxLength={7}
                                />
                            </div>
                        </div>

                        {fieldState.error && <p className="mt-1 text-xs text-red-500">{fieldState.error.message}</p>}

                        {field.value && !isValidHex(field.value) && (
                            <p className="mt-1 text-xs text-amber-600">Please enter a valid hex color (e.g., #FF5733)</p>
                        )}
                    </div>
                );
            }}
        />
    );
};
