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

interface BaseProps {
    className?: string;
    disabled?: boolean;
}

interface NumberProps extends BaseProps {
    type?: 'number';
    value: number;
    onSave: (value: number) => Promise<void>;
    formatDisplay?: (value: number) => string;
    min?: number;
    step?: string;
}

interface TextProps extends BaseProps {
    type: 'text';
    value: string;
    onSave: (value: string) => Promise<void>;
    formatDisplay?: (value: string) => string;
}

type InlineEditInputProps = NumberProps | TextProps;

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

export default function InlineEditInput(props: InlineEditInputProps) {
    const { className = '', disabled = false } = props;
    const isText = props.type === 'text';

    const [status, setStatus] = useState<Status>('idle');
    const [editValue, setEditValue] = useState('');
    const inputRef = useRef<HTMLInputElement>(null);
    const savingRef = useRef(false);

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

    const startEditing = () => {
        if (disabled) return;
        setEditValue(String(props.value));
        setStatus('editing');
    };

    const cancel = () => {
        setStatus('idle');
    };

    const save = async () => {
        if (savingRef.current) return;

        let parsedValue: string | number;
        if (isText) {
            const trimmed = editValue.trim();
            if (trimmed === '' || trimmed === props.value) {
                setStatus('idle');
                return;
            }
            parsedValue = trimmed;
        } else {
            const parsed = Number(editValue);
            if (isNaN(parsed) || parsed === props.value) {
                setStatus('idle');
                return;
            }
            parsedValue = parsed;
        }

        savingRef.current = true;
        setStatus('saving');
        try {
            // Type assertion needed: TS can't correlate isText with the union branch
            await (props.onSave as (v: typeof parsedValue) => Promise<void>)(
                parsedValue,
            );
            setStatus('success');
            setTimeout(() => setStatus('idle'), 1500);
        } catch {
            setStatus('error');
            setTimeout(() => setStatus('idle'), 1500);
        } finally {
            savingRef.current = false;
        }
    };

    const handleKeyDown = (e: React.KeyboardEvent) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            save();
        } else if (e.key === 'Escape') {
            cancel();
        }
    };

    const displayValue = isText
        ? (props.formatDisplay ?? String)(props.value)
        : (props.formatDisplay ?? ((v: number) => String(v)))(props.value);

    if (status === 'editing' || status === 'saving') {
        return (
            <input
                ref={inputRef}
                type={isText ? 'text' : 'number'}
                value={editValue}
                onChange={(e) => setEditValue(e.target.value)}
                onBlur={save}
                onKeyDown={handleKeyDown}
                min={props.type !== 'text' ? props.min : undefined}
                step={props.type !== 'text' ? props.step : undefined}
                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 ${isText ? 'w-48' : 'w-24'} ${className}`}
            />
        );
    }

    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}`}
        >
            {displayValue}
            {status === 'success' && <span className="text-green-600">✓</span>}
            {status === 'error' && <span className="text-red-600">✗</span>}
        </span>
    );
}
