"use client";
import React, { useState, useEffect } from 'react';
import { validatePhone } from "@core/helpers/validatePhone";
import QuestionInput from "../QuestionCard/QuestionInput";
import style from "./OnboardingPhone.module.css";

interface OnboardingPhoneProps {
    value: string;
    onChange: (area: string, num: string, full: string) => void;
    onValid?: (isValid: boolean) => void;
    onKeyDown?: (e: React.KeyboardEvent<HTMLInputElement>) => void;
}

export default function OnboardingPhone({ value, onChange, onValid, onKeyDown }: OnboardingPhoneProps) {
    const [localValue, setLocalValue] = useState(value);
    const [validationMessage, setValidationMessage] = useState("");
    const [isValid, setIsValid] = useState(false);

    useEffect(() => {
        // If external value changes, we sync and re-validate if it's 10 digits
        if (value && value !== localValue) {
            setLocalValue(value);
            checkAndValidate(value);
        }
    }, [value]);

    const checkAndValidate = (rawValue: string) => {
        if (rawValue.length === 10) {
            // Try to split area code (2, 3, or 4 digits) and phone number
            let foundArea = "";
            let foundNum = "";
            let valid = false;
            let msg = "";

            // Prioritize longest area code match
            for (let i = 4; i >= 2; i--) {
                const a = rawValue.substring(0, i);
                const n = rawValue.substring(i);
                const res = validatePhone(a, n);
                if (res.isValid) {
                    foundArea = a;
                    foundNum = n;
                    valid = true;
                    msg = res.message; // e.g. "Teléfono válido para AMBA"
                    break;
                } else if (i === 2) {
                    // if we reached the end and still invalid, use a generic error
                    msg = "Código de área inválido o no reconocido.";
                }
            }

            setIsValid(valid);
            setValidationMessage(msg);
            if (onValid) onValid(valid);
            
            if (valid) {
                onChange(foundArea, foundNum, rawValue);
            } else {
                onChange("", "", rawValue);
            }
        } else {
            setIsValid(false);
            if (onValid) onValid(false);
            onChange("", "", rawValue);

            if (rawValue.length > 0 && rawValue.length < 10) {
                setValidationMessage(`Faltan ${10 - rawValue.length} dígitos.`);
            } else if (rawValue.length > 10) {
                setValidationMessage(`Sobran ${rawValue.length - 10} dígitos.`);
            } else {
                setValidationMessage("");
            }
        }
    };

    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const rawValue = e.target.value.replace(/\D/g, ""); // Only numbers
        setLocalValue(rawValue);
        checkAndValidate(rawValue);
    };

    return (
        <div className={style.container}>
            <QuestionInput 
                placeholder="Ej. 1112345678 (10 números exactos)"
                value={localValue}
                onChange={handleInputChange}
                onKeyDown={onKeyDown}
                autoFocus
                error={!isValid && localValue.length === 10 ? validationMessage : ""}
            />
            {isValid && <div className={style.successMessage}>{validationMessage}</div>}
            {!isValid && localValue.length > 0 && localValue.length !== 10 && (
                <div className={style.infoMessage}>{validationMessage}</div>
            )}
        </div>
    );
}
