"use client";

import { useState, useEffect, useCallback } from 'react';

interface UseApiDataOptions {
  /** Don't fetch on mount */
  skip?: boolean;
}

interface UseApiDataResult<T> {
  data: T;
  loading: boolean;
  error: string | null;
  refetch: () => void;
}

export function useApiData<T>(url: string, fallback: T, options?: UseApiDataOptions): UseApiDataResult<T> {
  const [data, setData] = useState<T>(fallback);
  const [loading, setLoading] = useState(!options?.skip);
  const [error, setError] = useState<string | null>(null);

  const fetchData = useCallback(() => {
    setLoading(true);
    setError(null);
    fetch(url)
      .then((r) => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return r.json();
      })
      .then((d) => {
        setData(d);
        setLoading(false);
      })
      .catch((err) => {
        console.error(`Failed to fetch ${url}:`, err);
        setError(err.message);
        setLoading(false);
      });
  }, [url]);

  useEffect(() => {
    if (!options?.skip) {
      fetchData();
    }
  }, [fetchData, options?.skip]);

  return { data, loading, error, refetch: fetchData };
}

/** Post data to an API endpoint */
export async function apiPost<T = unknown>(url: string, body: unknown): Promise<{ data?: T; error?: string }> {
  try {
    const res = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    });
    const data = await res.json();
    if (!res.ok) {
      return { error: data.error || `HTTP ${res.status}` };
    }
    return { data };
  } catch (err) {
    return { error: String(err) };
  }
}

/** Put data to an API endpoint */
export async function apiPut<T = unknown>(url: string, body: unknown): Promise<{ data?: T; error?: string }> {
  try {
    const res = await fetch(url, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    });
    const data = await res.json();
    if (!res.ok) {
      return { error: data.error || `HTTP ${res.status}` };
    }
    return { data };
  } catch (err) {
    return { error: String(err) };
  }
}
