import { useRef, useState } from 'react';

export interface CepAddress {
  street: string;
  neighborhood: string;
  city: string;
  uf: string;
}

type Setter = (addr: CepAddress) => void;

export function useCep(onFill: Setter) {
  const [loading, setLoading] = useState(false);
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);

  function handleChange(value: string) {
    const clean = value.replace(/\D/g, '');
    if (timer.current) clearTimeout(timer.current);
    if (clean.length !== 8) return;

    timer.current = setTimeout(async () => {
      setLoading(true);
      try {
        const res = await fetch(`https://viacep.com.br/ws/${clean}/json/`);
        const data = await res.json();
        if (!data.erro) {
          onFill({
            street:       data.logradouro ?? '',
            neighborhood: data.bairro ?? '',
            city:         data.localidade ?? '',
            uf:           data.uf ?? '',
          });
        }
      } catch {}
      finally { setLoading(false); }
    }, 500);
  }

  return { loading, handleChange };
}
