import { useAuth } from '@/contexts/AuthContext';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { LogIn } from 'lucide-react';
import { ReLogo } from '@/assets';

export function Auth() {
  const { login, isLoading, error } = useAuth();

  const handleSSOLogin = async () => {
    // Clear any existing session data
    localStorage.clear();
    sessionStorage.clear();
    
    try {
      await login();
    } catch (loginError) {
      console.error('========================================');
      console.error('LOGIN ERROR');
      console.error('Error details:', loginError);
      console.error('Error message:', (loginError as Error)?.message);
      console.error('Error stack:', (loginError as Error)?.stack);
      console.error('========================================');
    }
  };

  if (error) {
    console.error('Auth0 Error in Auth Component:', {
      message: error.message,
      error: error
    });
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 to-slate-100 p-4">
      <Card className="w-full max-w-md shadow-xl">
        <CardHeader className="space-y-1 text-center pb-6">
          <div className="flex flex-col items-center justify-center mb-4">
            <img 
              src={ReLogo} 
              alt="Royal Enfield Logo" 
              className="h-10 w-auto max-w-[168px] object-contain mb-2"
            />
            <p className="text-xs text-gray-400 text-center truncate">Approval Portal</p>
          </div>
        </CardHeader>
        
        <CardContent className="space-y-4">
          {error && (
            <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg">
              <p className="text-sm font-medium">Authentication Error</p>
              <p className="text-sm">{error.message}</p>
            </div>
          )}
          
          <Button
            onClick={handleSSOLogin}
            disabled={isLoading}
            className="w-full h-12 text-base font-semibold bg-re-red hover:bg-re-red/90 text-white"
            size="lg"
          >
            {isLoading ? (
              <>
                <div 
                  className="mr-2 h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" 
                />
                Logging in...
              </>
            ) : (
              <>
                <LogIn className="mr-2 h-5 w-5" />
                SSO Login
              </>
            )}
          </Button>

          <div className="text-center text-sm text-gray-500 mt-4">
            <p>Secure Single Sign-On</p>
            <p className="text-xs mt-1">Powered by Auth0</p>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

