'use client';

import { useState, FormEvent } from 'react';
import { Lock } from 'lucide-react';
import Card from '@/components/ui/Card';
import Button from '@/components/ui/Button';

export default function LoginPage() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState(false);

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);

    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password }),
        credentials: 'include',
      });

      if (res.status === 429) {
        setError('Too many login attempts. Please wait a moment and try again.');
        setLoading(false);
        return;
      }

      const data = await res.json();

      if (!res.ok) {
        setError(data.error || 'Login failed');
        setLoading(false);
        return;
      }

      setSuccess(true);
      setLoading(false);
      
      setTimeout(() => {
        window.location.replace('/');
      }, 500);
      
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : 'Unknown error';
      setError(`Network error: ${errorMsg}`);
      setLoading(false);
    }
  };

  if (success) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center px-4">
        <Card className="w-full max-w-sm text-center" hover={false}>
          <div className="mb-6">
            <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-success/10 flex items-center justify-center">
              <Lock className="w-8 h-8 text-success" />
            </div>
          </div>
          <h2 className="text-2xl font-bold text-foreground mb-4">Login Successful!</h2>
          <p className="text-foreground-muted mb-6">Redirecting to dashboard...</p>
          <a 
            href="/" 
            className="inline-block bg-foreground text-background hover:bg-foreground/90 font-semibold py-3 px-6 rounded-xl transition-all duration-200 hover:scale-[1.02]"
          >
            Click here if not redirected
          </a>
        </Card>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background flex items-center justify-center px-4">
      <Card className="w-full max-w-sm" hover={false}>
        <div className="text-center mb-8">
          <div className="w-12 h-12 mx-auto mb-4 rounded-full bg-foreground/5 flex items-center justify-center">
            <Lock className="w-6 h-6 text-foreground" />
          </div>
          <h1 className="text-4xl font-bold mb-2 text-foreground">
            NEXUS
          </h1>
          <p className="text-foreground-muted text-sm">VM Control Center</p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-6">
          {error && (
            <div className="bg-danger/10 border border-danger/30 rounded-xl p-3">
              <p className="text-danger text-sm text-center">{error}</p>
            </div>
          )}

          <div>
            <label htmlFor="username" className="block text-sm font-medium text-foreground-muted mb-2">
              Username
            </label>
            <input
              id="username"
              type="text"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              required
              autoComplete="username"
              disabled={loading}
              className="w-full px-4 py-3 bg-background border border-border rounded-xl text-foreground placeholder-foreground-subtle focus:outline-none focus:border-foreground focus:ring-2 focus:ring-white focus:ring-offset-2 focus:ring-offset-background transition-colors disabled:opacity-50"
              placeholder="Enter username"
            />
          </div>

          <div>
            <label htmlFor="password" className="block text-sm font-medium text-foreground-muted mb-2">
              Password
            </label>
            <input
              id="password"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
              autoComplete="current-password"
              disabled={loading}
              className="w-full px-4 py-3 bg-background border border-border rounded-xl text-foreground placeholder-foreground-subtle focus:outline-none focus:border-foreground focus:ring-2 focus:ring-white focus:ring-offset-2 focus:ring-offset-background transition-colors disabled:opacity-50"
              placeholder="Enter password"
            />
          </div>

          <Button
            type="submit"
            disabled={loading}
            variant="primary"
            size="lg"
            className="w-full"
          >
            {loading ? 'Signing in...' : 'Sign In'}
          </Button>
        </form>

        <div className="mt-6 text-center">
          <p className="text-foreground-subtle text-xs">
            Secure access only
          </p>
        </div>
      </Card>
    </div>
  );
}
