
export const BR_STATES = [
  { value: "AC", label: "Acre" },
  { value: "AL", label: "Alagoas" },
  { value: "AP", label: "Amapá" },
  { value: "AM", label: "Amazonas" },
  { value: "BA", label: "Bahia" },
  { value: "CE", label: "Ceará" },
  { value: "DF", label: "Distrito Federal" },
  { value: "ES", label: "Espírito Santo" },
  { value: "GO", label: "Goiás" },
  { value: "MA", label: "Maranhão" },
  { value: "MT", label: "Mato Grosso" },
  { value: "MS", label: "Mato Grosso do Sul" },
  { value: "MG", label: "Minas Gerais" },
  { value: "PA", label: "Pará" },
  { value: "PB", label: "Paraíba" },
  { value: "PR", label: "Paraná" },
  { value: "PE", label: "Pernambuco" },
  { value: "PI", label: "Piauí" },
  { value: "RJ", label: "Rio de Janeiro" },
  { value: "RN", label: "Rio Grande do Norte" },
  { value: "RS", label: "Rio Grande do Sul" },
  { value: "RO", label: "Rondônia" },
  { value: "RR", label: "Roraima" },
  { value: "SC", label: "Santa Catarina" },
  { value: "SP", label: "São Paulo" },
  { value: "SE", label: "Sergipe" },
  { value: "TO", label: "Tocantins" },
];

type CnpjLookupResult = {
  razao_social?: string;
  nome_fantasia?: string;
  cep?: string;
  logradouro?: string;
  numero?: string;
  complemento?: string;
  bairro?: string;
  municipio?: string;
  uf?: string;
  ddd_telefone_1?: string;
  ddd_telefone_2?: string;
  email?: string;
};

export async function fetchCities(uf: string) {
  if (!uf) return [];
  try {
    const response = await fetch(
      `https://servicodados.ibge.gov.br/api/v1/localidades/estados/${uf}/municipios`
    );
    const data = (await response.json()) as Array<{ nome: string }>;
    return data.map((city) => ({
      value: city.nome,
      label: city.nome,
    }));
  } catch (error) {
    console.error("Error fetching cities:", error);
    return [];
  }
}

function onlyDigits(value: unknown) {
  return typeof value === "string" ? value.replace(/\D/g, "") : "";
}

function titleCase(value: unknown) {
  if (typeof value !== "string") return "";
  const normalized = value.trim().toLowerCase();
  if (!normalized) return "";
  return normalized
    .split(/\s+/)
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join(" ");
}

function mergePreferred(primary?: string, secondary?: string) {
  return String(primary || secondary || "").trim();
}

export async function fetchCnpj(cnpj: string) {
  const cleanCnpj = cnpj.replace(/\D/g, "");
  if (cleanCnpj.length !== 14) return null;
  
  try {
    const [brasilApiResponse, cnpjWsResponse] = await Promise.allSettled([
      fetch(`https://brasilapi.com.br/api/cnpj/v1/${cleanCnpj}`),
      fetch(`https://publica.cnpj.ws/cnpj/${cleanCnpj}`),
    ]);

    const brasilApiData =
      brasilApiResponse.status === "fulfilled" && brasilApiResponse.value.ok
        ? ((await brasilApiResponse.value.json()) as Record<string, unknown>)
        : null;

    const cnpjWsData =
      cnpjWsResponse.status === "fulfilled" && cnpjWsResponse.value.ok
        ? ((await cnpjWsResponse.value.json()) as {
            razao_social?: string;
            estabelecimento?: {
              nome_fantasia?: string;
              cep?: string;
              logradouro?: string;
              tipo_logradouro?: string;
              numero?: string;
              complemento?: string;
              bairro?: string;
              cidade?: { nome?: string };
              estado?: { sigla?: string };
              ddd1?: string;
              telefone1?: string;
              ddd2?: string;
              telefone2?: string;
              email?: string;
            };
            email?: string;
          })
        : null;

    if (!brasilApiData && !cnpjWsData) throw new Error("CNPJ not found");

    const estabelecimento = cnpjWsData?.estabelecimento;
    const logradouroComTipo = [estabelecimento?.tipo_logradouro, estabelecimento?.logradouro]
      .filter((item) => typeof item === "string" && item.trim())
      .join(" ");

    const merged: CnpjLookupResult = {
      razao_social: mergePreferred(
        typeof brasilApiData?.razao_social === "string" ? brasilApiData.razao_social : undefined,
        cnpjWsData?.razao_social
      ),
      nome_fantasia: mergePreferred(
        typeof brasilApiData?.nome_fantasia === "string" ? brasilApiData.nome_fantasia : undefined,
        estabelecimento?.nome_fantasia
      ),
      cep: onlyDigits(brasilApiData?.cep) || onlyDigits(estabelecimento?.cep),
      logradouro: titleCase(
        mergePreferred(
          typeof brasilApiData?.logradouro === "string" ? brasilApiData.logradouro : undefined,
          logradouroComTipo
        )
      ),
      numero: mergePreferred(
        typeof brasilApiData?.numero === "string" ? brasilApiData.numero : undefined,
        estabelecimento?.numero
      ),
      complemento: titleCase(
        mergePreferred(
          typeof brasilApiData?.complemento === "string" ? brasilApiData.complemento : undefined,
          estabelecimento?.complemento
        )
      ),
      bairro: titleCase(
        mergePreferred(
          typeof brasilApiData?.bairro === "string" ? brasilApiData.bairro : undefined,
          estabelecimento?.bairro
        )
      ),
      municipio: titleCase(
        mergePreferred(
          typeof brasilApiData?.municipio === "string" ? brasilApiData.municipio : undefined,
          estabelecimento?.cidade?.nome
        )
      ),
      uf: mergePreferred(
        typeof brasilApiData?.uf === "string" ? brasilApiData.uf : undefined,
        estabelecimento?.estado?.sigla
      ).toUpperCase(),
      ddd_telefone_1:
        onlyDigits(brasilApiData?.ddd_telefone_1) ||
        `${onlyDigits(estabelecimento?.ddd1)}${onlyDigits(estabelecimento?.telefone1)}`,
      ddd_telefone_2:
        onlyDigits(brasilApiData?.ddd_telefone_2) ||
        `${onlyDigits(estabelecimento?.ddd2)}${onlyDigits(estabelecimento?.telefone2)}`,
      email: mergePreferred(
        typeof brasilApiData?.email === "string" ? brasilApiData.email : undefined,
        estabelecimento?.email || cnpjWsData?.email
      ),
    };

    return merged;
  } catch (error) {
    console.error("Error fetching CNPJ:", error);
    return null;
  }
}

export async function fetchCep(cep: string) {
  const cleanCep = cep.replace(/\D/g, "");
  if (cleanCep.length !== 8) return null;

  try {
    const response = await fetch(`https://brasilapi.com.br/api/cep/v2/${cleanCep}`);
    if (!response.ok) throw new Error('CEP not found');
    return await response.json();
  } catch (error) {
    console.error("Error fetching CEP:", error);
    return null;
  }
}
