import { type FC, type InputHTMLAttributes, useState, useRef, useEffect } from 'react'
import { clx } from '../helpers/utils'
import Error from './Error'

type Props = {
    label?: string
    className?: string
    error_text?: string
    isNotRequired?: boolean
    value?: string
    onChange?: (value: string) => void
} & Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange' | 'value'>

const ColorPicker: FC<Props> = (props: Props) => {
    const [color, setColor] = useState<string>(props.value || '#000000')
    const colorInputRef = useRef<HTMLInputElement>(null)
    const pickerOpenGuardRef = useRef(false)

    const inputClass = clx(
        'w-full bg-white h-10 text-black block pl-10 pr-10 text-xs rounded-xl border border-border',
        props.readOnly && 'bg-gray-100 border-0 text-description',
        props.className
    )

    const handleColorChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        const newColor = event.target.value
        setColor(newColor)
        props.onChange?.(newColor)
    }

    const handleTextChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        const value = event.target.value
        if (/^#[0-9A-Fa-f]{0,6}$/.test(value) || value === '') {
            const finalColor = value || '#000000'
            setColor(finalColor)
            props.onChange?.(finalColor)
        }
    }

    const openNativeColorPicker = () => {
        if (props.readOnly) return
        if (pickerOpenGuardRef.current) return
        pickerOpenGuardRef.current = true
        colorInputRef.current?.click()
        window.setTimeout(() => {
            pickerOpenGuardRef.current = false
        }, 400)
    }

    useEffect(() => {
        if (props.value !== undefined) {
            setColor(props.value)
        }
    }, [props.value])

    return (
        <div className='w-full'>
            <label className='text-sm'>
                {props.label}
            </label>

            <div
                className={clx(
                    'w-full relative mt-1 rounded-xl',
                    !props.readOnly && 'cursor-pointer'
                )}
                onClick={!props.readOnly ? openNativeColorPicker : undefined}
            >
                <input
                    type='text'
                    value={color}
                    onChange={handleTextChange}
                    placeholder='#000000'
                    readOnly={props.readOnly}
                    title={
                        !props.readOnly
                            ? 'کلیک: پالت رنگ — با Tab وارد فیلد شوید تا کد را تایپ کنید'
                            : undefined
                    }
                    className={`${inputClass} cursor-pointer`}
                />

                <span
                    aria-hidden
                    className={clx(
                        'absolute top-0 bottom-0 my-auto left-1 flex items-center justify-center min-h-10 min-w-10 rounded-lg pointer-events-none',
                        props.readOnly && 'opacity-50'
                    )}
                >
                    {/* <img
                        src={ColorfilterIcon}
                        alt=''
                        className='size-7 select-none'
                    /> */}
                </span>

                <span
                    aria-hidden
                    className={clx(
                        'absolute top-0 bottom-0 my-auto right-1 flex items-center justify-center min-h-10 min-w-10 rounded-lg pointer-events-none',
                        props.readOnly && 'opacity-50'
                    )}
                >
                    <span
                        className='block w-5 h-5 rounded-full border border-border shadow-sm'
                        style={{ backgroundColor: color }}
                    />
                </span>

                <input
                    ref={colorInputRef}
                    type='color'
                    value={color}
                    onChange={handleColorChange}
                    className='absolute opacity-0 pointer-events-none w-0 h-0'
                />
            </div>

            {props.error_text && (
                <Error errorText={props.error_text} />
            )}
        </div>
    )
}

export default ColorPicker

