"use client";

import { useCallback, useEffect, useState } from "react";
import type { AppData } from "@/lib/types";

type UseDataResult = {
  data: AppData | null;
  loading: boolean;
  error: string | null;
  refresh: () => Promise<void>;
  mutate: (updater: (prev: AppData) => AppData | Promise<AppData>) => Promise<AppData>;
};

export function useAppData(): UseDataResult {
  const [data, setData] = useState<AppData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const refresh = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/data", { cache: "no-store" });
      if (!res.ok) throw new Error("Impossible de charger les données.");
      const json = (await res.json()) as AppData;
      setData(json);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Erreur inconnue");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void refresh();
  }, [refresh]);

  const mutate = useCallback(
    async (updater: (prev: AppData) => AppData | Promise<AppData>) => {
      if (!data) throw new Error("Données non chargées");
      const next = await updater(data);
      const res = await fetch("/api/data", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(next),
      });
      if (!res.ok) {
        const err = await res.json().catch(() => ({}));
        throw new Error(
          (err as { error?: string }).error ?? "Échec de l'enregistrement"
        );
      }
      const saved = (await res.json()) as AppData;
      setData(saved);
      return saved;
    },
    [data]
  );

  return { data, loading, error, refresh, mutate };
}
