import { cn } from '@/lib/utils';
import { forwardRef } from 'react';
import type { Country as CountryCode } from 'react-phone-number-input';
import PhoneInputLib from 'react-phone-number-input';
import 'react-phone-number-input/style.css';

// ── Inner input: transparent — outer container owns the border/bg ──────────
const InnerInput = forwardRef<
    HTMLInputElement,
    React.InputHTMLAttributes<HTMLInputElement>
>(({ className, ...props }, ref) => (
    <input
        ref={ref}
        className={cn(
            'text-foreground min-w-0 flex-1 bg-transparent text-sm',
            'placeholder:text-muted-foreground dark:placeholder:text-muted-foreground/40 border-0 outline-none',
            className,
        )}
        {...props}
    />
));
InnerInput.displayName = 'PhoneInnerInput';

// ── Public component ──────────────────────────────────────────────────────
interface PhoneInputProps {
    value: string;
    onChange: (value: string) => void;
    defaultCountry?: CountryCode;
    placeholder?: string;
    className?: string;
    error?: boolean;
    disabled?: boolean;
}

export function PhoneInput({
    value,
    onChange,
    defaultCountry = 'KE',
    placeholder = '+254 700 000 000',
    className,
    error,
    disabled,
}: PhoneInputProps) {
    return (
        <div
            className={cn(
                'bg-card dark:bg-muted/30 flex h-10 w-full items-center gap-2 rounded-lg border px-3 transition-colors',
                'focus-within:border-primary/50 focus-within:ring-primary/20 focus-within:ring-1',
                error ? 'border-destructive' : 'border-border',
                disabled ? 'cursor-not-allowed opacity-50' : '',
                className,
            )}
        >
            <PhoneInputLib
                value={value}
                onChange={(v) => onChange(v ?? '')}
                defaultCountry={defaultCountry}
                placeholder={placeholder}
                inputComponent={InnerInput}
                disabled={disabled}
                className="pf-phone-input flex w-full items-center gap-2"
            />
        </div>
    );
}
