"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";

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

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 { filtros, 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) => ({ ...prev, [field]: value }));

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

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

  const isUnchanged = JSON.stringify(form) === JSON.stringify(filtros);
  const isSubmitDisabled = Object.values(form).some((v) => !v) || isUnchanged;

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