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

const API_BASE = 'http://localhost:3001/api';

export interface Category {
  id: number;
  name: string;
  emoji: string;
  description?: string;
}

export interface KPI {
  id: number;
  category_id: number;
  name: string;
  unit: string;
  target?: number;
  formula?: string;
  description?: string;
  frequency?: string;
}

export interface Measurement {
  id?: number;
  kpi_id: number;
  measurement_date: string;
  value: number;
  status?: string;
}

export const useSQLiteDatabase = () => {
  const [categories, setCategories] = useState<Category[]>([]);
  const [kpis, setKpis] = useState<KPI[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Charger les catégories et KPI au démarrage
  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        const [categoriesRes, kpisRes] = await Promise.all([
          fetch(`${API_BASE}/categories`),
          fetch(`${API_BASE}/kpis`)
        ]);

        if (!categoriesRes.ok || !kpisRes.ok) {
          throw new Error('Erreur lors du chargement des données');
        }

        const categoriesData = await categoriesRes.json();
        const kpisData = await kpisRes.json();

        setCategories(categoriesData);
        setKpis(kpisData);
        setError(null);
      } catch (err: any) {
        setError(err.message || 'Erreur de connexion à la base de données');
        console.error('❌ Erreur:', err);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  // Obtenir les mesures pour un KPI
  const getMeasurementsForKPI = useCallback(async (kpiId: number, days: number = 30) => {
    try {
      const res = await fetch(`${API_BASE}/measurements/${kpiId}?days=${days}`);
      if (!res.ok) throw new Error('Erreur de chargement des mesures');
      return await res.json();
    } catch (err: any) {
      console.error('Erreur getMeasurementsForKPI:', err);
      return [];
    }
  }, []);

  // Obtenir la dernière mesure pour un KPI
  const getLatestMeasurement = useCallback(async (kpiId: number) => {
    try {
      const res = await fetch(`${API_BASE}/latest/${kpiId}`);
      if (!res.ok) throw new Error('Erreur de chargement');
      return await res.json();
    } catch (err: any) {
      console.error('Erreur getLatestMeasurement:', err);
      return null;
    }
  }, []);

  // Obtenir les statistiques pour un KPI
  const getKPIStats = useCallback(async (kpiId: number, days: number = 30) => {
    try {
      const res = await fetch(`${API_BASE}/stats/${kpiId}?days=${days}`);
      if (!res.ok) throw new Error('Erreur de chargement');
      return await res.json();
    } catch (err: any) {
      console.error('Erreur getKPIStats:', err);
      return null;
    }
  }, []);

  return {
    categories,
    kpis,
    loading,
    error,
    getMeasurementsForKPI,
    getLatestMeasurement,
    getKPIStats
  };
};
