"use client";
import React, { useState, useEffect } from "react";
import style from "./OnboardingLocation.module.css";
import filterObjects from "@components/TextObjectFilter/Filter.Service";
import { TextObjectFilterResult } from "@models/TextObjectFilter.model";

export interface OnboardingLocationData {
    street: string;
    streetNumber: string;
    builingFloor: string;
    buildingApartament: string;
    state: string;     // Provincia
    city: string;      // Partido
    block: string;     // Localidad
    zipCode: string;
    latitude: number;
    longitude: number;
}

interface OnboardingLocationProps {
    data: OnboardingLocationData;
    onChange: (data: Partial<OnboardingLocationData>) => void;
}

export default function OnboardingLocation({ data, onChange }: OnboardingLocationProps) {
    const [provincias, setProvincias] = useState<TextObjectFilterResult[]>([]);
    const [partidos, setPartidos] = useState<TextObjectFilterResult[]>([]);
    const [localidades, setLocalidades] = useState<TextObjectFilterResult[]>([]);

    useEffect(() => {
        // Cargar provincias al montar
        filterObjects<any>("location/provincias-filter-all", {}).then((res) => {
            setProvincias(res);
        }).catch(() => {});
    }, []);

    useEffect(() => {
        // Cargar partidos cuando cambia la provincia
        if (data.state && data.state.trim() !== "") {
            filterObjects<any>("location/partidos-filter-all", {
                provincia: data.state
            }).then((res) => {
                setPartidos(res);
            }).catch(() => {});
        } else {
            setPartidos([]);
        }
    }, [data.state]);

    useEffect(() => {
        // Cargar localidades cuando cambia el partido
        if (data.state && data.state.trim() !== "" && data.city && data.city.trim() !== "") {
            filterObjects<any>("location/localidades-filter-all", {
                provincia: data.state,
                partido: data.city,
            }).then((res) => {
                setLocalidades(res);
            }).catch(() => {});
        } else {
            setLocalidades([]);
        }
    }, [data.state, data.city]);

    const handleChange = (field: keyof OnboardingLocationData, value: string | number) => {
        onChange({ [field]: value });
    };

    return (
        <div className={style.container}>
            <div className={style.row}>
                <div className={style.inputGroup}>
                    <label className={style.inputLabel}>Calle *</label>
                    <input 
                        type="text" 
                        className={style.input} 
                        placeholder="Ej. Av. San Martín" 
                        value={data.street} 
                        onChange={(e) => handleChange("street", e.target.value)} 
                    />
                </div>
                <div className={style.inputGroupHalf}>
                    <label className={style.inputLabel}>Nro *</label>
                    <input 
                        type="text" 
                        className={style.input} 
                        placeholder="Ej. 123" 
                        value={data.streetNumber} 
                        onChange={(e) => handleChange("streetNumber", e.target.value)} 
                    />
                </div>
            </div>

            <div className={style.row}>
                <div className={style.inputGroupHalf}>
                    <label className={style.inputLabel}>Piso</label>
                    <input 
                        type="text" 
                        className={style.input} 
                        placeholder="Opcional" 
                        value={data.builingFloor} 
                        onChange={(e) => handleChange("builingFloor", e.target.value)} 
                    />
                </div>
                <div className={style.inputGroupHalf}>
                    <label className={style.inputLabel}>Dpto</label>
                    <input 
                        type="text" 
                        className={style.input} 
                        placeholder="Opcional" 
                        value={data.buildingApartament} 
                        onChange={(e) => handleChange("buildingApartament", e.target.value)} 
                    />
                </div>
                <div className={style.inputGroupHalf}>
                    <label className={style.inputLabel}>C.P.</label>
                    <input 
                        type="text" 
                        className={style.input} 
                        placeholder="Ej. 1000" 
                        value={data.zipCode} 
                        onChange={(e) => handleChange("zipCode", e.target.value)} 
                    />
                </div>
            </div>

            <div className={style.row}>
                <div className={style.inputGroup}>
                    <label className={style.inputLabel}>Provincia *</label>
                    <input 
                        type="text" 
                        list="provincias-list"
                        className={style.input} 
                        placeholder="Ej. Buenos Aires" 
                        value={data.state} 
                        onChange={(e) => handleChange("state", e.target.value)} 
                        autoComplete="off"
                    />
                    <datalist id="provincias-list">
                        {provincias.map(p => (
                            <option key={p.id} value={p.id}>{p.name}</option>
                        ))}
                    </datalist>
                </div>
            </div>

            <div className={style.row}>
                <div className={style.inputGroup}>
                    <label className={style.inputLabel}>Partido *</label>
                    <input 
                        type="text" 
                        list="partidos-list"
                        className={style.input} 
                        placeholder="Ej. La Plata" 
                        value={data.city} 
                        onChange={(e) => handleChange("city", e.target.value)} 
                        autoComplete="off"
                    />
                    <datalist id="partidos-list">
                        {partidos.map(p => (
                            <option key={p.id} value={p.id}>{p.name}</option>
                        ))}
                    </datalist>
                </div>
            </div>

            <div className={style.row}>
                <div className={style.inputGroup}>
                    <label className={style.inputLabel}>Localidad / Barrio *</label>
                    <input 
                        type="text" 
                        list="localidades-list"
                        className={style.input} 
                        placeholder="Ej. Tolosa" 
                        value={data.block} 
                        onChange={(e) => handleChange("block", e.target.value)} 
                        autoComplete="off"
                    />
                    <datalist id="localidades-list">
                        {localidades.map(l => (
                            <option key={l.id} value={l.id}>{l.name}</option>
                        ))}
                    </datalist>
                </div>
            </div>
        </div>
    );
}
