"use client";

import { useState, useCallback, useEffect } from "react";
import type {
  LeadOutput,
  LeadStats,
  PipelineView,
  LeadFilters,
  NurtureSequenceOutput,
  CaptureFormOutput,
  ScoringRuleOutput,
} from "@/lib/types/lead-crm.types";

interface UseLeadDataReturn {
  leads: LeadOutput[];
  leadsLoading: boolean;
  stats: LeadStats | null;
  pipeline: PipelineView | null;
  pipelineLoading: boolean;
  sequences: NurtureSequenceOutput[];
  captureForms: CaptureFormOutput[];
  scoringRules: ScoringRuleOutput[];
  pagination: { page: number; total: number; totalPages: number };
  refreshLeads: (filters?: LeadFilters) => Promise<void>;
  refreshPipeline: () => Promise<void>;
  refreshStats: () => Promise<void>;
  refreshSequences: () => Promise<void>;
  refreshCaptureForms: () => Promise<void>;
  refreshScoringRules: () => Promise<void>;
}

export function useLeadData(): UseLeadDataReturn {
  const [leads, setLeads] = useState<LeadOutput[]>([]);
  const [leadsLoading, setLeadsLoading] = useState(true);
  const [stats, setStats] = useState<LeadStats | null>(null);
  const [pipeline, setPipeline] = useState<PipelineView | null>(null);
  const [pipelineLoading, setPipelineLoading] = useState(true);
  const [sequences, setSequences] = useState<NurtureSequenceOutput[]>([]);
  const [captureForms, setCaptureForms] = useState<CaptureFormOutput[]>([]);
  const [scoringRules, setScoringRules] = useState<ScoringRuleOutput[]>([]);
  const [pagination, setPagination] = useState({
    page: 1,
    total: 0,
    totalPages: 0,
  });

  const refreshLeads = useCallback(async (filters?: LeadFilters) => {
    setLeadsLoading(true);
    try {
      const params = new URLSearchParams();
      if (filters?.status) params.set("status", filters.status);
      if (filters?.source) params.set("source", filters.source);
      if (filters?.search) params.set("search", filters.search);
      if (filters?.pipelineStageId)
        params.set("pipelineStageId", filters.pipelineStageId);
      if (filters?.minScore !== undefined)
        params.set("minScore", String(filters.minScore));

      const res = await fetch(`/api/leads?${params}`);
      if (res.ok) {
        const json = await res.json();
        setLeads(json.data || []);
        if (json.pagination) setPagination(json.pagination);
      }
    } catch {
      // silent
    } finally {
      setLeadsLoading(false);
    }
  }, []);

  const refreshPipeline = useCallback(async () => {
    setPipelineLoading(true);
    try {
      const res = await fetch("/api/leads/pipeline");
      if (res.ok) {
        const json = await res.json();
        setPipeline(json.data || null);
      }
    } catch {
      // silent
    } finally {
      setPipelineLoading(false);
    }
  }, []);

  const refreshStats = useCallback(async () => {
    try {
      const res = await fetch("/api/leads/stats");
      if (res.ok) {
        const json = await res.json();
        setStats(json.data || null);
      }
    } catch {
      // silent
    }
  }, []);

  const refreshSequences = useCallback(async () => {
    try {
      const res = await fetch("/api/leads/nurture");
      if (res.ok) {
        const json = await res.json();
        setSequences(json.data || []);
      }
    } catch {
      // silent
    }
  }, []);

  const refreshCaptureForms = useCallback(async () => {
    try {
      const res = await fetch("/api/leads/capture-forms");
      if (res.ok) {
        const json = await res.json();
        setCaptureForms(json.data || []);
      }
    } catch {
      // silent
    }
  }, []);

  const refreshScoringRules = useCallback(async () => {
    try {
      const res = await fetch("/api/leads/scoring/rules");
      if (res.ok) {
        const json = await res.json();
        setScoringRules(json.data || []);
      }
    } catch {
      // silent
    }
  }, []);

  useEffect(() => {
    refreshLeads();
    refreshPipeline();
    refreshStats();
    refreshSequences();
    refreshCaptureForms();
    refreshScoringRules();
  }, [
    refreshLeads,
    refreshPipeline,
    refreshStats,
    refreshSequences,
    refreshCaptureForms,
    refreshScoringRules,
  ]);

  return {
    leads,
    leadsLoading,
    stats,
    pipeline,
    pipelineLoading,
    sequences,
    captureForms,
    scoringRules,
    pagination,
    refreshLeads,
    refreshPipeline,
    refreshStats,
    refreshSequences,
    refreshCaptureForms,
    refreshScoringRules,
  };
}
