import { useState, useEffect, useCallback } from 'react';
import api, { fetchMaterialsSummary } from '../../api';

export default function useDashboardData(user, projects, selectedProject) {
  const [stats, setStats] = useState(null);
  const [projectStats, setProjectStats] = useState(null);
  const [loading, setLoading] = useState(true);

  // Always fetch system-wide stats
  useEffect(() => {
    let cancelled = false;
    setLoading(true);

    api.get('/dashboard/stats')
      .then(res => {
        if (!cancelled && res.data?.success) {
          setStats(res.data.stats);
        }
      })
      .catch(err => console.error('Dashboard stats error:', err))
      .finally(() => { if (!cancelled) setLoading(false); });

    return () => { cancelled = true; };
  }, [user]);

  // Fetch project-specific data when a project is selected
  useEffect(() => {
    if (!selectedProject) {
      setProjectStats(null);
      return;
    }

    let cancelled = false;
    const jobNo = selectedProject.job_no || selectedProject.official_project_code;

    Promise.all([
      fetchMaterialsSummary({ project_id: jobNo }).catch(() => ({ data: {} })),
      api.get('/purchase-request/list', { params: { job_no: jobNo } }).catch(() => ({ data: {} })),
      api.get('/files', { params: { job_no: jobNo } }).catch(() => ({ data: {} })),
    ]).then(([materialsRes, purchaseRes, filesRes]) => {
      if (cancelled) return;

      const materials = materialsRes.data;
      const purchases = purchaseRes.data;
      const files = filesRes.data;

      setProjectStats({
        bomCount: files.files?.length || files.total || 0,
        totalMaterials: materials.total_count || materials.total || 0,
        purchaseRequests: purchases.total || (Array.isArray(purchases.requests) ? purchases.requests.length : 0),
      });
    });

    return () => { cancelled = true; };
  }, [selectedProject]);

  // Build metric values
  const getMetrics = useCallback(() => {
    if (selectedProject && projectStats) {
      return {
        projects: { label: '프로젝트', value: 1, color: '#2563eb' },
        bom: { label: 'BOM 파일', value: projectStats.bomCount, color: '#16a34a' },
        materials: { label: '총 자재', value: projectStats.totalMaterials, color: '#9333ea' },
        purchase: { label: '구매요청', value: projectStats.purchaseRequests, color: '#d97706' },
      };
    }

    // System-wide fallback
    const metrics = stats?.metrics || [];
    const findMetric = (label) => {
      const m = metrics.find(m => m.label.includes(label));
      return m ? m.value : 0;
    };

    return {
      projects: { label: '전체 프로젝트', value: findMetric('프로젝트') || projects.length, color: '#2563eb' },
      bom: { label: 'BOM 파일', value: findMetric('업로드') || '-', color: '#16a34a' },
      materials: { label: '전체 자재', value: findMetric('자재') || '-', color: '#9333ea' },
      purchase: { label: '구매요청', value: findMetric('구매') || '-', color: '#d97706' },
    };
  }, [stats, projectStats, selectedProject, projects]);

  return { stats, projectStats, loading, getMetrics };
}
