import { useState, useEffect } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { useLocation, useNavigate } from 'react-router-dom';

export function useGoogleCalendarAuth() {
  const [isAuthenticating, setIsAuthenticating] = useState(false);
  const [tokenStatus, setTokenStatus] = useState(null);
  const { toast } = useToast();
  const location = useLocation();
  const navigate = useNavigate();

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

  const checkConnectionStatus = async () => {
    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) {
        setTokenStatus({ isConnected: false });
        return;
      }
      // Check if user has Google calendar tokens stored
      // For now, check localStorage as a simple approach
      const stored = localStorage.getItem(`google_cal_${user.id}`);
      setTokenStatus({ isConnected: !!stored });
    } catch (err) {
      console.error('Status check failed:', err);
      setTokenStatus({ isConnected: false });
    }
  };

  const initiateGoogleLogin = () => {
    setIsAuthenticating(true);
    toast({ title: "Info", description: "Google Calendar integration requires server-side configuration." });
    setIsAuthenticating(false);
  };

  const handleOAuthCallback = async (code) => {
    if (!code) return;
    setIsAuthenticating(true);
    try {
      const { data: { user } } = await supabase.auth.getUser();
      const { data, error } = await supabase.functions.invoke('google-calendar-oauth', {
        body: { code, user_id: user?.id }
      });
      if (error) throw new Error(error.message || 'OAuth invocation failed');
      if (data?.error) throw new Error(data.error);

      toast({ title: "Connected", description: "Google Calendar linked successfully." });
      checkConnectionStatus();
      navigate('/dashboard/calendar', { replace: true });
    } catch (err) {
      console.error('OAuth Callback Error:', err);
      toast({ variant: "destructive", title: "Connection Failed", description: err.message });
    } finally {
      setIsAuthenticating(false);
    }
  };

  const revokeAccess = async () => {
    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (user) localStorage.removeItem(`google_cal_${user.id}`);
      setTokenStatus({ isConnected: false });
      toast({ title: "Disconnected", description: "Google Calendar has been disconnected." });
    } catch (err) {
      toast({ variant: "destructive", title: "Error", description: "Failed to disconnect." });
    }
  };

  const finalizePendingTokens = async () => {
    // No-op in current implementation
  };

  return {
    isAuthenticating,
    tokenStatus,
    initiateGoogleLogin,
    handleOAuthCallback,
    revokeAccess,
    checkConnectionStatus,
    finalizePendingTokens
  };
}
