import { useEffect, useRef, useState } from 'react';

interface Option {
    value: string;
    label: string;
}

interface InlineEditSelectProps {
    value: string;
    options: Option[];
    onSave: (value: string) => Promise<void>;
    displayLabel?: string;
    className?: string;
    disabled?: boolean;
}

type Status = 'idle' | 'editing' | 'saving' | 'success' | 'error';

export default function InlineEditSelect({
    value,
    options,
    onSave,
    displayLabel,
    className = '',
    disabled = false,
}: InlineEditSelectProps) {
    const [status, setStatus] = useState<Status>('idle');
    const selectRef = useRef<HTMLSelectElement>(null);

    useEffect(() => {
        if (status === 'editing' && selectRef.current) {
            selectRef.current.focus();
        }
    }, [status]);

    const startEditing = () => {
        if (disabled) return;
        setStatus('editing');
    };

    const handleChange = async (e: React.ChangeEvent<HTMLSelectElement>) => {
        const newValue = e.target.value;
        if (newValue === value) {
            setStatus('idle');
            return;
        }

        setStatus('saving');
        try {
            await onSave(newValue);
            setStatus('success');
            setTimeout(() => setStatus('idle'), 1500);
        } catch {
            setStatus('error');
            setTimeout(() => setStatus('idle'), 1500);
        }
    };

    const handleBlur = () => {
        if (status === 'editing') {
            setStatus('idle');
        }
    };

    if (status === 'editing' || status === 'saving') {
        return (
            <select
                ref={selectRef}
                value={value}
                onChange={handleChange}
                onBlur={handleBlur}
                disabled={status === 'saving'}
                className={`rounded border border-blue-300 bg-white px-2 py-0.5 text-sm text-gray-900 outline-none focus:ring-2 focus:ring-blue-500 ${className}`}
            >
                {options.map((opt) => (
                    <option key={opt.value} value={opt.value}>
                        {opt.label}
                    </option>
                ))}
            </select>
        );
    }

    return (
        <span
            onClick={startEditing}
            className={`inline-flex items-center gap-1 ${
                disabled
                    ? 'cursor-default text-gray-400'
                    : 'cursor-pointer rounded px-1 py-0.5 hover:bg-blue-50 hover:text-blue-700'
            } ${className}`}
        >
            {displayLabel || value}
            {status === 'success' && <span className="text-green-600">✓</span>}
            {status === 'error' && <span className="text-red-600">✗</span>}
        </span>
    );
}
