import { useState, useEffect, useCallback } from 'react';
import { gsc, ahrefs, clickup, insights } from '../lib/api';

export function useSiteData(site, { days = 28, folderIds = null } = {}) {
  const [metrics,   setMetrics]   = useState(null);
  const [keywords,  setKeywords]  = useState([]);
  const [pages,     setPages]     = useState([]);
  const [history,   setHistory]   = useState([]);
  const [overview,  setOverview]  = useState(null);
  const [backlinks, setBacklinks] = useState([]);
  const [tasks,     setTasks]     = useState(null);
  const [insight,   setInsight]   = useState(null);
  const [loading,   setLoading]   = useState({});
  const [errors,    setErrors]    = useState({});

  const setLoad = (key, val) => setLoading(p => ({ ...p, [key]: val }));
  const setErr  = (key, val) => setErrors(p => ({ ...p, [key]: val }));

  const domain = site
    ? site.replace(/^https?:\/\//, '').replace(/\/$/, '').replace(/^sc-domain:/, '')
    : null;

  const fetchMetrics = useCallback(async () => {
    if (!site) return;
    setLoad('metrics', true);
    try {
      const data = await gsc.metrics(site, days);
      setMetrics(data); setErr('metrics', null);
    } catch (e) { setErr('metrics', e.message); }
    finally { setLoad('metrics', false); }
  }, [site, days]);

  const fetchKeywords = useCallback(async () => {
    if (!site) return;
    setLoad('keywords', true);
    try {
      const data = await gsc.keywords(site, days, 100);
      setKeywords(data); setErr('keywords', null);
    } catch (e) { setErr('keywords', e.message); }
    finally { setLoad('keywords', false); }
  }, [site, days]);

  const fetchPages = useCallback(async () => {
    if (!site) return;
    setLoad('pages', true);
    try {
      const data = await gsc.pages(site, days);
      setPages(data); setErr('pages', null);
    } catch (e) { setErr('pages', e.message); }
    finally { setLoad('pages', false); }
  }, [site, days]);

  const fetchHistory = useCallback(async () => {
    if (!site) return;
    setLoad('history', true);
    try {
      // History window = max(days*2, 90) so chart always has context
      const histDays = Math.max(days * 2, 90);
      const data = await gsc.history(site, histDays);
      setHistory(data); setErr('history', null);
    } catch (e) { setErr('history', e.message); }
    finally { setLoad('history', false); }
  }, [site, days]);

  const fetchOverview = useCallback(async () => {
    if (!domain) return;
    setLoad('overview', true);
    try {
      const data = await ahrefs.overview(domain);
      setOverview(data); setErr('overview', null);
    } catch (e) { setOverview(null); }
    finally { setLoad('overview', false); }
  }, [domain]);

  const fetchBacklinks = useCallback(async () => {
    if (!domain) return;
    setLoad('backlinks', true);
    try {
      const data = await ahrefs.backlinks(domain);
      setBacklinks(data); setErr('backlinks', null);
    } catch (e) {
      setBacklinks([]);
      if (!e.message?.includes('500')) setErr('backlinks', e.message);
    }
    finally { setLoad('backlinks', false); }
  }, [domain]);

  const fetchTasks = useCallback(async () => {
    setLoad('tasks', true);
    try {
      // Pass folderIds if configured for this site
      const data = await clickup.tasks(folderIds);
      setTasks(data); setErr('tasks', null);
    } catch (e) {
      setTasks(null);
      if (!e.message?.includes('500')) setErr('tasks', e.message);
    }
    finally { setLoad('tasks', false); }
  }, [folderIds]);

  const fetchInsight = useCallback(async (metricsData, kwData, tasksData, overviewData) => {
    if (!site || !metricsData) return;
    setLoad('insight', true);
    try {
      const data = await insights.site({
        site, days,
        metrics: metricsData,
        keywords: kwData?.slice(0, 20),
        tasks: tasksData,
        ahrefsOverview: overviewData,
      });
      setInsight(data.insight); setErr('insight', null);
    } catch (e) { setErr('insight', e.message); }
    finally { setLoad('insight', false); }
  }, [site, days]);

  useEffect(() => {
    if (!site) return;
    setMetrics(null); setKeywords([]); setPages([]);
    setHistory([]); setOverview(null); setBacklinks([]); setInsight(null);
    Promise.all([
      fetchMetrics(), fetchKeywords(), fetchPages(), fetchHistory(),
      fetchOverview(), fetchBacklinks(), fetchTasks(),
    ]);
  }, [site, days, folderIds]);

  useEffect(() => {
    if (metrics && keywords.length > 0) {
      fetchInsight(metrics, keywords, tasks, overview);
    }
  }, [metrics, keywords, overview]);

  const refetch = () => {
    fetchMetrics(); fetchKeywords(); fetchPages(); fetchHistory();
    fetchOverview(); fetchBacklinks(); fetchTasks();
  };

  return { metrics, keywords, pages, history, overview, backlinks, tasks, insight, loading, errors, refetch };
}
