'use client';

import { useState, FormEvent } from 'react';
import { useRouter } from 'next/navigation';
import { Lock, User, FileText, KeyRound, ArrowLeft, Loader2 } from 'lucide-react';

export default function LoginPage() {
  const router = useRouter();
  const [mode, setMode] = useState<'login' | 'changePassword'>('login');

  // Login state
  const [creds,   setCreds]   = useState({ username: '', password: '' });
  const [error,   setError]   = useState('');
  const [loading, setLoading] = useState(false);

  // Change password state
  const [cpForm,    setCpForm]    = useState({ username: '', currentPassword: '', newPassword: '', confirmPassword: '' });
  const [cpError,   setCpError]   = useState('');
  const [cpSuccess, setCpSuccess] = useState('');
  const [cpLoading, setCpLoading] = useState(false);

  async function handleLogin(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(creds),
      });
      const data = await res.json();

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

      router.push('/');
      router.refresh();
    } catch {
      setError('Network error. Please try again.');
    } finally {
      setLoading(false);
    }
  }

  async function handleChangePassword(e: FormEvent) {
    e.preventDefault();
    setCpError('');
    setCpSuccess('');

    if (cpForm.newPassword !== cpForm.confirmPassword) {
      setCpError('New passwords do not match');
      return;
    }
    if (cpForm.newPassword.length < 6) {
      setCpError('New password must be at least 6 characters');
      return;
    }

    setCpLoading(true);
    try {
      const res = await fetch('/api/auth/change-password', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          username:        cpForm.username,
          currentPassword: cpForm.currentPassword,
          newPassword:     cpForm.newPassword,
        }),
      });
      const data = await res.json();

      if (!res.ok) { setCpError(data.error ?? 'Failed'); return; }

      setCpSuccess('Password changed! You can now sign in with your new password.');
      setCpForm({ username: '', currentPassword: '', newPassword: '', confirmPassword: '' });
    } catch {
      setCpError('Network error. Please try again.');
    } finally {
      setCpLoading(false);
    }
  }

  return (
    <div className="flex min-h-full flex-col items-center justify-center bg-gradient-to-br from-slate-900 to-blue-950 px-4">
      <div className="w-full max-w-sm space-y-8">
        {/* Logo */}
        <div className="text-center">
          <div className="mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-2xl bg-blue-600 shadow-lg">
            <FileText className="h-7 w-7 text-white" />
          </div>
          <h1 className="text-2xl font-bold text-white">DocManager</h1>
          <p className="mt-1 text-sm text-slate-400">
            {mode === 'login' ? 'Sign in to your account' : 'Change your password'}
          </p>
        </div>

        {mode === 'login' ? (
          /* ── Login Form ──────────────────────── */
          <form onSubmit={handleLogin} className="card space-y-4 p-6">
            {error && (
              <div className="rounded-lg bg-red-50 px-4 py-3 text-sm text-red-700 border border-red-100">
                {error}
              </div>
            )}

            <div className="space-y-1">
              <label className="block text-sm font-medium text-slate-700">Username</label>
              <div className="relative">
                <User className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
                <input
                  type="text"
                  required
                  autoFocus
                  value={creds.username}
                  onChange={(e) => setCreds({ ...creds, username: e.target.value })}
                  className="input pl-9"
                  placeholder="Enter username"
                />
              </div>
            </div>

            <div className="space-y-1">
              <label className="block text-sm font-medium text-slate-700">Password</label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
                <input
                  type="password"
                  required
                  value={creds.password}
                  onChange={(e) => setCreds({ ...creds, password: e.target.value })}
                  className="input pl-9"
                  placeholder="Enter password"
                />
              </div>
            </div>

            <button type="submit" disabled={loading} className="btn-primary w-full justify-center py-2.5">
              {loading ? (
                <span className="flex items-center gap-2">
                  <Loader2 className="h-4 w-4 animate-spin" /> Signing in...
                </span>
              ) : (
                'Sign in'
              )}
            </button>

            <button
              type="button"
              onClick={() => { setMode('changePassword'); setError(''); }}
              className="flex w-full items-center justify-center gap-1.5 text-sm text-slate-400 hover:text-blue-400 transition-colors"
            >
              <KeyRound className="h-3.5 w-3.5" />
              Change Password
            </button>
          </form>
        ) : (
          /* ── Change Password Form ────────────── */
          <form onSubmit={handleChangePassword} className="card space-y-4 p-6">
            {cpError && (
              <div className="rounded-lg bg-red-50 px-4 py-3 text-sm text-red-700 border border-red-100">
                {cpError}
              </div>
            )}
            {cpSuccess && (
              <div className="rounded-lg bg-green-50 px-4 py-3 text-sm text-green-700 border border-green-100">
                {cpSuccess}
              </div>
            )}

            <div className="space-y-1">
              <label className="block text-sm font-medium text-slate-700">Username</label>
              <div className="relative">
                <User className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
                <input
                  type="text"
                  required
                  autoFocus
                  value={cpForm.username}
                  onChange={(e) => setCpForm({ ...cpForm, username: e.target.value })}
                  className="input pl-9"
                  placeholder="Enter username"
                />
              </div>
            </div>

            <div className="space-y-1">
              <label className="block text-sm font-medium text-slate-700">Current Password</label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
                <input
                  type="password"
                  required
                  value={cpForm.currentPassword}
                  onChange={(e) => setCpForm({ ...cpForm, currentPassword: e.target.value })}
                  className="input pl-9"
                  placeholder="Enter current password"
                />
              </div>
            </div>

            <div className="space-y-1">
              <label className="block text-sm font-medium text-slate-700">New Password</label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
                <input
                  type="password"
                  required
                  minLength={6}
                  value={cpForm.newPassword}
                  onChange={(e) => setCpForm({ ...cpForm, newPassword: e.target.value })}
                  className="input pl-9"
                  placeholder="Min 6 characters"
                />
              </div>
            </div>

            <div className="space-y-1">
              <label className="block text-sm font-medium text-slate-700">Confirm New Password</label>
              <div className="relative">
                <Lock className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
                <input
                  type="password"
                  required
                  minLength={6}
                  value={cpForm.confirmPassword}
                  onChange={(e) => setCpForm({ ...cpForm, confirmPassword: e.target.value })}
                  className="input pl-9"
                  placeholder="Re-enter new password"
                />
              </div>
            </div>

            <button type="submit" disabled={cpLoading} className="btn-primary w-full justify-center py-2.5">
              {cpLoading ? (
                <span className="flex items-center gap-2">
                  <Loader2 className="h-4 w-4 animate-spin" /> Changing...
                </span>
              ) : (
                'Change Password'
              )}
            </button>

            <button
              type="button"
              onClick={() => { setMode('login'); setCpError(''); setCpSuccess(''); }}
              className="flex w-full items-center justify-center gap-1.5 text-sm text-slate-400 hover:text-blue-400 transition-colors"
            >
              <ArrowLeft className="h-3.5 w-3.5" />
              Back to Sign In
            </button>
          </form>
        )}
      </div>
    </div>
  );
}
