import { useMemo, useState } from 'react';
import { Input } from '@/components/ui/input';
import { getCountryCallingCode } from '@/lib/countries';
import { cn } from '@/lib/utils';

function splitContactNumber(
    value: string | null | undefined,
    country: string,
) {
    const callingCode = getCountryCallingCode(country);
    const trimmedValue = (value ?? '').trim();

    if (country === 'OTHER') {
        const [, manualCode = '', phoneNumber = ''] =
            trimmedValue.match(/^(\+\d+)\s*(.*)$/) ?? [];

        return { manualCode, phoneNumber };
    }

    if (callingCode && trimmedValue.startsWith(callingCode)) {
        return {
            manualCode: callingCode,
            phoneNumber: trimmedValue.slice(callingCode.length).trim(),
        };
    }

    return { manualCode: callingCode, phoneNumber: trimmedValue };
}

type ContactNumberInputProps = {
    country: string;
    defaultValue?: string | null;
    id?: string;
    tabIndex?: number;
    className?: string;
};

export default function ContactNumberInput({
    country,
    defaultValue = '',
    id = 'contact_number',
    tabIndex,
    className,
}: ContactNumberInputProps) {
    const initialValue = useMemo(
        () => splitContactNumber(defaultValue, country),
        [country, defaultValue],
    );
    const [manualCode, setManualCode] = useState(initialValue.manualCode);
    const [phoneNumber, setPhoneNumber] = useState(initialValue.phoneNumber);

    const callingCode =
        country === 'OTHER' ? manualCode : getCountryCallingCode(country);
    const contactNumber = [callingCode, phoneNumber]
        .filter(Boolean)
        .join(' ')
        .trim();

    return (
        <div className={cn('flex gap-2', className)}>
            <input
                name="contact_number"
                readOnly
                type="hidden"
                value={contactNumber}
            />

            {country === 'OTHER' ? (
                <Input
                    aria-label="Código de país"
                    className="w-28"
                    inputMode="tel"
                    onChange={(event) => setManualCode(event.target.value)}
                    placeholder="+000"
                    required
                    tabIndex={tabIndex}
                    type="tel"
                    value={manualCode}
                />
            ) : (
                <div className="flex h-9 min-w-20 items-center rounded-md border border-input bg-muted px-3 text-sm text-muted-foreground">
                    {callingCode || '+000'}
                </div>
            )}

            <Input
                id={id}
                autoComplete="tel-national"
                className="flex-1"
                inputMode="tel"
                onChange={(event) => setPhoneNumber(event.target.value)}
                placeholder="Número de contacto"
                required
                tabIndex={country === 'OTHER' ? undefined : tabIndex}
                type="tel"
                value={phoneNumber}
            />
        </div>
    );
}
