import { useState } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';

export const useGoogleCalendarSync = () => {
  const [isSyncing, setIsSyncing] = useState(false);
  const [syncError, setSyncError] = useState(null);
  const [isConfigured, setIsConfigured] = useState(true);
  const [lastSyncResult, setLastSyncResult] = useState(null);
  const { toast } = useToast();

  const syncGoogleEventsToStaffCalendar = async (selectedCalendarIds = []) => {
    try {
      setIsSyncing(true);
      setSyncError(null);

      const { data: { session } } = await supabase.auth.getSession();
      if (!session?.access_token) {
        throw new Error("No active session. Please log in.");
      }

      const requestBody = {
        action: 'sync',
        calendarIds: selectedCalendarIds.length > 0 ? selectedCalendarIds : undefined
      };

      const { data, error } = await supabase.functions.invoke("sync-google-calendar", {
        body: requestBody,
        headers: { Authorization: `Bearer ${session.access_token}` }
      });

      if (error) throw error;
      if (data?.error) {
        if (data.code === "MISSING_CREDENTIALS") {
          setIsConfigured(false);
          throw new Error("Google Calendar integration is not configured on the server.");
        }
        throw new Error(data.error);
      }

      setLastSyncResult({ count: data?.count || 0, timestamp: new Date() });
      toast({ title: "Sync Complete", description: `Successfully synced ${data?.count || 0} events from Google Calendar.` });
      return true;
    } catch (err) {
      console.error("Google Sync Error:", err);
      setSyncError(err.message);
      toast({ variant: "destructive", title: "Sync Failed", description: err.message || "Could not synchronize events." });
      return false;
    } finally {
      setIsSyncing(false);
    }
  };

  return { isSyncing, syncError, isConfigured, lastSyncResult, syncGoogleEventsToStaffCalendar };
};
