'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { Card, CardContent, CardDescription, CardHeader, CardTitle, Input, Label, Button, Alert, AlertDescription } from '@the-order/ui';
import { useAuth } from '../../lib/auth';
import { useToast } from '@the-order/ui';

export default function LoginPage(): JSX.Element {
  const router = useRouter();
  const { login } = useAuth();
  const { success, error: showError } = useToast();
  const [formData, setFormData] = useState({
    email: '',
    password: '',
  });
  const [isLoading, setIsLoading] = useState(false);
  const [loginError, setLoginError] = useState<string | null>(null);

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>): Promise<void> => {
    e.preventDefault();
    setIsLoading(true);
    setLoginError(null);

    try {
      // In production, this would call an authentication API
      // For now, we'll simulate a login
      if (formData.email && formData.password) {
        // Simulate API call
        await new Promise((resolve) => setTimeout(resolve, 1000));

        // Mock authentication - in production, this would be a real API call
        // Admin users should have admin role
        const mockUser = {
          id: 'admin-123',
          email: formData.email,
          name: formData.email.split('@')[0],
          accessToken: 'mock-access-token-' + Date.now(),
          roles: ['admin', 'reviewer'],
        };

        login(mockUser);
        success('Login successful', 'Welcome to the admin portal!');
        router.push('/');
      } else {
        throw new Error('Please enter email and password');
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Login failed';
      setLoginError(errorMessage);
      showError(errorMessage, 'Login Error');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 flex items-center justify-center py-12 px-4">
      <Card className="w-full max-w-md">
        <CardHeader>
          <CardTitle>Admin Login</CardTitle>
          <CardDescription>Sign in to the internal portal</CardDescription>
        </CardHeader>
        <CardContent>
          <form onSubmit={(e) => { void handleSubmit(e); }} className="space-y-4">
            {loginError && (
              <Alert variant="destructive">
                <AlertDescription>{loginError}</AlertDescription>
              </Alert>
            )}

            <div>
              <Label htmlFor="email">Email Address</Label>
              <Input
                id="email"
                type="email"
                required
                value={formData.email}
                onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                placeholder="admin@theorder.org"
                className="mt-2"
              />
            </div>

            <div>
              <Label htmlFor="password">Password</Label>
              <Input
                id="password"
                type="password"
                required
                value={formData.password}
                onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                placeholder="Enter your password"
                className="mt-2"
              />
            </div>

            <Button type="submit" className="w-full" disabled={isLoading}>
              {isLoading ? 'Signing in...' : 'Sign In'}
            </Button>

            <div className="text-center text-sm text-gray-600">
              <p className="mb-2">For security, this portal requires authentication.</p>
              <a href="/forgot-password" className="text-primary hover:underline">
                Forgot password?
              </a>
            </div>
          </form>

          <div className="mt-6 pt-6 border-t">
            <p className="text-sm text-gray-600 text-center mb-4">Or continue with</p>
            <div className="space-y-2">
              <Button variant="outline" className="w-full" type="button">
                OIDC / eIDAS
              </Button>
              <Button variant="outline" className="w-full" type="button">
                DID Wallet
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}

