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

interface RecentCall {
  id: string;
  time: string;
  caller: string | null;
  duration: string;
  store_id: string;
}

interface DashboardStats {
  totalCalls: { value: number; change: string; changeType: string };
  todayCalls: { value: number; change: string; changeType: string };
  weekCalls: { value: number; change: string; changeType: string };
  avgDuration: { value: number; formatted: string; change: string; changeType: string };
  totalDuration: { value: number; formatted: string; change: string; changeType: string };
  recentCalls: RecentCall[];
}

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 { data: { session } } = await supabase.auth.getSession();
      if (!session) {
        throw new Error('Not authenticated');
      }

      const response = await fetch(`${API_URL}/api/dashboard/stats`, {
        headers: {
          'Authorization': `Bearer ${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;
}
