"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import type { VoiceAgentConfig } from "@/lib/types/voice-agent.types";

// ── Response types from API ──────────────────────────────────────────

interface ProvisionResponse {
  provisioned: boolean;
  agentId?: string;
  config?: VoiceAgentConfig;
  status?: {
    agent_id: string;
    is_active: boolean;
    last_call?: string;
    total_calls: number;
    avg_duration_seconds?: number;
  };
}

interface RecentCall {
  id: string;
  customerPhone: string | null;
  customerName: string | null;
  duration: number;
  outcome: string;
  appointmentBooked: boolean;
  timestamp: string;
}

interface VoiceAgentStats {
  totalCalls: number;
  todayCalls: number;
  weekCalls: number;
  appointmentsBooked: number;
  avgCallDuration: number;
}

interface AgentOverview {
  agent: {
    id: string | null;
    configured: boolean;
    config: Record<string, unknown> | null;
    status: string;
    healthStatus: string;
  };
  stats: VoiceAgentStats;
  recentCalls: RecentCall[];
  workflow: {
    id: string | null;
    status: string;
    lastRunAt: string | null;
  } | null;
}

// ── Hook return type ─────────────────────────────────────────────────

export interface VoiceAgentData {
  isProvisioned: boolean;
  isLoading: boolean;
  error: string | null;
  agent: {
    id: string;
    config: VoiceAgentConfig;
    status: string;
    healthStatus: string;
  } | null;
  stats: VoiceAgentStats | null;
  recentCalls: RecentCall[];
  refresh: () => Promise<void>;
}

export type { RecentCall, VoiceAgentStats };

// ── Hook implementation ──────────────────────────────────────────────

export function useVoiceAgentData(): VoiceAgentData {
  const [isProvisioned, setIsProvisioned] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [agent, setAgent] = useState<VoiceAgentData["agent"]>(null);
  const [stats, setStats] = useState<VoiceAgentStats | null>(null);
  const [recentCalls, setRecentCalls] = useState<RecentCall[]>([]);
  const mountedRef = useRef(true);

  const fetchData = useCallback(async () => {
    try {
      setIsLoading(true);
      setError(null);

      // Step 1: Check provisioning status
      const provisionRes = await fetch("/api/voice-agent/provision", {
        credentials: "include",
      });

      if (!provisionRes.ok) {
        throw new Error("Failed to check voice agent status");
      }

      const provision: ProvisionResponse = await provisionRes.json();

      if (!mountedRef.current) return;

      if (!provision.provisioned) {
        setIsProvisioned(false);
        setAgent(null);
        setStats(null);
        setRecentCalls([]);
        return;
      }

      setIsProvisioned(true);

      // Step 2: Fetch dashboard stats
      const dashRes = await fetch("/api/dashboard/voice-agents", {
        credentials: "include",
      });

      if (!dashRes.ok) {
        throw new Error("Failed to fetch voice agent dashboard data");
      }

      const dashData: { success: boolean; voiceAgent: AgentOverview } =
        await dashRes.json();

      if (!mountedRef.current) return;

      if (dashData.success && dashData.voiceAgent) {
        const overview = dashData.voiceAgent;

        setAgent({
          id: overview.agent.id || provision.agentId || "",
          config: (overview.agent.config as unknown as VoiceAgentConfig) ||
            provision.config || {
              language: "both" as const,
              voiceTone: "professional" as const,
              useKnowledgeBase: true,
            },
          status: overview.agent.status,
          healthStatus: overview.agent.healthStatus,
        });

        setStats(overview.stats);
        setRecentCalls(overview.recentCalls);
      }
    } catch (err) {
      if (!mountedRef.current) return;
      const message =
        err instanceof Error ? err.message : "An unexpected error occurred";
      setError(message);
    } finally {
      if (mountedRef.current) {
        setIsLoading(false);
      }
    }
  }, []);

  useEffect(() => {
    mountedRef.current = true;
    fetchData();
    return () => {
      mountedRef.current = false;
    };
  }, [fetchData]);

  return {
    isProvisioned,
    isLoading,
    error,
    agent,
    stats,
    recentCalls,
    refresh: fetchData,
  };
}
