"use client";

import { useState } from "react";
import { Github } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";

export default function LoginPage() {
  const [isLoading, setIsLoading] = useState(false);

  const handleGitHubLogin = async () => {
    setIsLoading(true);
    try {
      // Get the callbackUrl from the URL if present
      const urlParams = new URLSearchParams(window.location.search);
      const callbackUrl = urlParams.get('callbackUrl');

      // Use the API service to get the GitHub OAuth URL
      const { url } = await import('@/lib/api').then(module => 
        module.authAPI.getGitHubOAuthUrl()
      );

      // Store the callbackUrl in sessionStorage to use after authentication
      if (callbackUrl) {
        sessionStorage.setItem('callbackUrl', callbackUrl);
      }

      // Redirect to GitHub OAuth page
      window.location.href = url;
    } catch (error) {
      console.error('Login error:', error);
      setIsLoading(false);
      // You could add error handling UI here
    }
  };

  return (
    <div className="flex min-h-screen items-center justify-center bg-background p-4">
      <Card className="w-full max-w-md">
        <CardHeader className="space-y-1 text-center">
          <CardTitle className="text-2xl font-bold">Connexion</CardTitle>
          <CardDescription>
            Connectez-vous pour accéder à l&apos;application de création de groupes
          </CardDescription>
        </CardHeader>
        <CardContent className="flex flex-col gap-4">
          <Button
            variant="outline"
            onClick={handleGitHubLogin}
            disabled={isLoading}
            className="w-full"
          >
            {isLoading ? (
              <span className="flex items-center gap-2">
                <span className="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent" />
                Connexion en cours...
              </span>
            ) : (
              <span className="flex items-center gap-2">
                <Github className="h-5 w-5" />
                Se connecter avec GitHub
              </span>
            )}
          </Button>
        </CardContent>
        <CardFooter className="flex flex-col text-center text-sm text-muted-foreground">
          <p>
            En vous connectant, vous acceptez nos conditions d&apos;utilisation et notre politique de confidentialité.
          </p>
        </CardFooter>
      </Card>
    </div>
  );
}
