'use client';

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useLogin } from '@/lib/auth';
import { ApiError } from '@/lib/api';

export default function LoginPage() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const login = useLogin();

  const onSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    login.mutate({ username: username.trim(), password });
  };

  const errorMsg = login.error instanceof ApiError ? login.error.message : null;

  return (
    <div className="min-h-screen flex items-center justify-center bg-paper p-4">
      {/* Decorative top border - the only ornament on this screen */}
      <div className="fixed top-0 inset-x-0 h-1 bg-gradient-to-r from-transparent via-saffron-500 to-transparent opacity-60" />

      <div className="w-full max-w-sm space-y-8 animate-fade-in">
        {/* Header */}
        <div className="text-center space-y-3">
          <div className="font-display text-5xl text-ink leading-none">Vihar Sewa</div>
          <div className="saffron-rule mx-auto" />
          <div className="text-sm text-ink-400 font-light tracking-wide">
            Coordination for the journey
          </div>
        </div>

        {/* Form */}
        <form onSubmit={onSubmit} className="space-y-5">
          <div className="space-y-2">
            <Label htmlFor="username">Username</Label>
            <Input
              id="username"
              autoComplete="username"
              autoCapitalize="none"
              autoCorrect="off"
              required
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              disabled={login.isPending}
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="password">Password</Label>
            <Input
              id="password"
              type="password"
              autoComplete="current-password"
              required
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              disabled={login.isPending}
            />
          </div>

          {errorMsg && (
            <div className="text-sm text-rust bg-rust/5 border border-rust/20 rounded-md px-3 py-2">
              {errorMsg}
            </div>
          )}

          <Button type="submit" size="lg" className="w-full" disabled={login.isPending}>
            {login.isPending ? 'Signing in…' : 'Sign in'}
          </Button>
        </form>

      </div>
    </div>
  );
}
