"use client";
import { useState, useEffect, useCallback } from "react";
import { getCountries, createCountry, updateCountry, deleteCountry } from "@/lib/api/country.api";
import { mapCountriesApiResponse } from "@/lib/api/mappers/country.mappers";
import type { CountryRow, CreateCountryDto, UpdateCountryDto } from "@/lib/api/types/country.types";

export function useCountries() {
  const [countries, setCountries] = useState<CountryRow[]>([]);
  const [loading, setLoading]     = useState(false);
  const [error, setError]         = useState<string | null>(null);

  const refresh = useCallback(() => {
    setLoading(true); setError(null);
    getCountries()
      .then((data) => setCountries(mapCountriesApiResponse(data)))
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false));
  }, []);

  useEffect(() => { refresh(); }, [refresh]);
  return { countries, loading, error, refresh };
}

export function useCountryMutations(onSuccess?: () => void) {
  const [saving, setSaving]     = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [mutationError, setMutationError] = useState<string | null>(null);

  const create = async (dto: CreateCountryDto) => {
    setSaving(true); setMutationError(null);
    try { const r = await createCountry(dto); onSuccess?.(); return r; }
    catch (err: any) { setMutationError(err.message); return null; }
    finally { setSaving(false); }
  };
  const update = async (id: number, dto: UpdateCountryDto) => {
    setSaving(true); setMutationError(null);
    try { const r = await updateCountry(id, dto); onSuccess?.(); return r; }
    catch (err: any) { setMutationError(err.message); return null; }
    finally { setSaving(false); }
  };
  const remove = async (id: number) => {
    setDeleting(true); setMutationError(null);
    try { await deleteCountry(id); onSuccess?.(); return true; }
    catch (err: any) { setMutationError(err.message); return false; }
    finally { setDeleting(false); }
  };
  return { create, update, remove, saving, deleting, mutationError };
}
