"use client";

import { useEffect, useState, FormEvent } from "react";
import { useQuery } from "@tanstack/react-query";
import { apiFetch } from "@/lib/api-client";
import { emptyFilters, useCartillaStore } from "@/store/cartilla-store";
import { CartillaResponse } from "@/components/cartilla/types";
import {
  ESALUD_RUBRO_MATCH,
  ESALUD_PLAN_LABEL,
  HARDCODED_ARGENTINE_PROVINCES,
} from "@/components/cartilla/mock/hardcoded-esalud";

const optionsFromArray = (arr?: string[]) => arr?.map((item) => ({ value: item, label: item })) ?? [];

// El backend devuelve las zonas en mayúsculas y con guiones bajos (ej. "GBA_NORTE").
// Acá solo se ajusta el texto que ve el usuario; el value que se manda al backend queda intacto.
const ZONA_LABELS: Record<string, string> = {
  BUENOS_AIRES: "Buenos Aires",
  CABA: "C.A.B.A",
  GBA_NORTE: "GBA Norte",
  GBA_OESTE: "GBA Oeste",
  GBA_SUR: "GBA Sur",
  INTERIOR: "Interior",
};

const formatZonaLabel = (value: string) =>
  ZONA_LABELS[value] ??
  value
    .toLowerCase()
    .split("_")
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join(" ");

const zonaOptionsFromArray = (arr?: string[]) => arr?.map((value) => ({ value, label: formatZonaLabel(value) })) ?? [];

const isEmptyCartilla = (data?: CartillaResponse) => {
  if (!data) return false;
  return (
    data.planes.length === 0 &&
    data.especialidades.length === 0 &&
    data.provincias.length === 0 &&
    data.localidades.length === 0
  );
};

const useCartilla = (rubroValue: string) => {
  const { setFiltros } = useCartillaStore();

  const { data, isLoading, error } = useQuery({
    queryKey: ["cartilla-rubro", rubroValue],
    enabled: !!rubroValue,
    queryFn: () => apiFetch<CartillaResponse>(`cartilla${rubroValue}`),
  });

  const [form, setForm] = useState(emptyFilters);

  const updateField = (field: keyof typeof form, value: string) =>
    setForm((prev) => {
      const next = { ...prev, [field]: value };
      // Al cambiar de plan, la zona/provincia elegida deja de ser válida (ver hardcoded-esalud.ts)
      if (field === "plan" && prev.plan !== value) next.zona = "";
      return next;
    });

  useEffect(() => {
    setForm(emptyFilters);
    setFiltros(emptyFilters);
  }, [rubroValue]);

  const submitHandler = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setFiltros(form);
  };

  // HARDCODEADO TEMPORAL: ver components/cartilla/mock/hardcoded-esalud.ts
  const isFarmaciasYOpticas = rubroValue.includes(ESALUD_RUBRO_MATCH);
  const isEsaludSelected = form.plan === ESALUD_PLAN_LABEL;

  const planOptions = optionsFromArray(data?.planes);
  if (isFarmaciasYOpticas && !planOptions.some((option) => option.value === ESALUD_PLAN_LABEL)) {
    planOptions.push({ value: ESALUD_PLAN_LABEL, label: ESALUD_PLAN_LABEL });
  }

  // Las provincias del plan E-salud siguen hardcodeadas: el backend todavía no conoce ese plan.
  const zonaLabel = isEsaludSelected ? "Provincia" : "Zona";
  const zonaOptions = isEsaludSelected ? optionsFromArray(HARDCODED_ARGENTINE_PROVINCES) : zonaOptionsFromArray(data?.zonas);
  // fin hardcodeado temporal

  // No se bloquea por "sin cambios": el usuario debe poder repetir la misma búsqueda
  // (por ejemplo, para reintentar después de un error de red).
  const isSubmitDisabled = !form.plan || !form.especialidad || !form.zona;

  return {
    data,
    isLoading,
    error,
    noData: isEmptyCartilla(data),
    form,
    updateField,
    submitHandler,
    isSubmitDisabled,
    planOptions,
    specialtyOptions: optionsFromArray(data?.especialidades),
    locationOptions: optionsFromArray(data?.localidades),
    zonaLabel,
    zonaOptions,
  };
};
export default useCartilla;
