"use client";

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

// Generic data type for inspection_plans
type Inspection_plan = Record<string, unknown>;

/**
 * Fetch and manage inspection_plans data.
 */
export function useInspection_plans() {
  const [data, setData] = useState<Inspection_plan[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchData = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      const res = await fetch(`/api/inspection_plans`);
      const json = await res.json();
      setData(Array.isArray(json) ? json : json?.data || []);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Failed to load data");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

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