import { createContext, useContext, useState, useEffect, ReactNode } from "react";
import { API_URL } from "@/lib/config";

interface DashboardStats {
  totalCalls: { value: number; change: string; changeType: string };
  resolvedCalls: { value: number; change: string; changeType: string };
  avgDuration: { value: number; formatted: string; change: string; changeType: string };
  totalCost: { value: number; formatted: string; change: string; changeType: string };
  timeSaved: { value: string; formatted: string; change: string; changeType: string };
  humanCostSaved: { value: number; formatted: string; change: string; changeType: string };
  resolutionRate: { value: number; dailyChange: string; weeklyChange: string };
  topIntents: Array<{
    name: string;
    count: number;
    percentage: number;
    change: string;
  }>;
}

interface DashboardContextType {
  stats: DashboardStats | null;
  loading: boolean;
  error: string | null;
  refetch: () => void;
}

const DashboardContext = createContext<DashboardContextType | undefined>(undefined);

export function DashboardProvider({ children }: { children: ReactNode }) {
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchStats = async () => {
    try {
      setLoading(true);
      setError(null);

      const sessionData = localStorage.getItem('session_data');
      if (!sessionData) {
        throw new Error('No session data found');
      }

      const session = JSON.parse(sessionData);
      const response = await fetch(`${API_URL}/api/dashboard/stats`, {
        headers: {
          'Authorization': `Bearer ${session.session.access_token}`,
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        throw new Error('Failed to fetch dashboard stats');
      }

      const data = await response.json();
      if (data.success) {
        setStats(data.stats);
      }
    } catch (err) {
      console.error('Error fetching dashboard stats:', err);
      setError(err instanceof Error ? err.message : 'Failed to load stats');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchStats();
  }, []);

  return (
    <DashboardContext.Provider value={{ stats, loading, error, refetch: fetchStats }}>
      {children}
    </DashboardContext.Provider>
  );
}

export function useDashboard() {
  const context = useContext(DashboardContext);
  if (context === undefined) {
    throw new Error('useDashboard must be used within a DashboardProvider');
  }
  return context;
}
