'use client';

import { useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { Eye, EyeOff, Loader2, AlertTriangle } from 'lucide-react';
import Link from 'next/link';

function getInitialError(errorParam: string | null): string {
  if (!errorParam) return '';
  if (errorParam === 'unauthorized') return 'You are not authorised to access this panel.';
  return '';
}

export default function AdminLoginForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const from = searchParams.get('from') || '/admin';
  const errorParam = searchParams.get('error');

  const [email, setEmail]       = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError]   = useState(getInitialError(errorParam));
  const [loading, setLoading] = useState(false);

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

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

      const data = await res.json();

      if (res.status === 429) {
        setError(data.error || 'Too many attempts. Please wait 15 minutes.');
        return;
      }

      if (res.status === 403) {
        setError(data.error || 'Your account does not have admin access.');
        return;
      }

      if (!res.ok) {
        setError('Invalid credentials. Please try again.');
        return;
      }

      router.push(from);
      router.refresh();
    } catch {
      setError('Something went wrong. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      {/* Email */}
      <div className="space-y-1.5">
        <label className="block text-xs font-semibold text-gray-400 uppercase tracking-wide">
          Email
        </label>
        <input
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder="admin@example.com"
          autoComplete="username"
          className="w-full px-3 py-3 rounded-md border border-gray-700 bg-gray-800 text-white text-sm placeholder-gray-500 outline-none focus:ring-2 focus:ring-orange-500/30 focus:border-orange-500 transition-all"
          required
        />
      </div>

      {/* Password */}
      <div className="space-y-1.5">
        <label className="block text-xs font-semibold text-gray-400 uppercase tracking-wide">
          Password
        </label>
        <div className="relative">
          <input
            type={showPassword ? 'text' : 'password'}
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            placeholder="Enter admin password"
            autoComplete="current-password"
            className="w-full px-3 py-3 pr-10 rounded-md border border-gray-700 bg-gray-800 text-white text-sm placeholder-gray-500 outline-none focus:ring-2 focus:ring-orange-500/30 focus:border-orange-500 transition-all"
            required
          />
          <button
            type="button"
            onClick={() => setShowPassword((p) => !p)}
            className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-200 transition-colors"
            aria-label={showPassword ? 'Hide password' : 'Show password'}
          >
            {showPassword ? (
              <EyeOff className="w-4 h-4" />
            ) : (
              <Eye className="w-4 h-4" />
            )}
          </button>
        </div>
      </div>

      {error && (
        <div className="flex items-start gap-2 bg-red-500/10 border border-red-500/20 text-red-400 rounded-lg px-3 py-2.5 text-xs">
          <AlertTriangle className="w-3.5 h-3.5 mt-0.5 flex-shrink-0" />
          {error}
        </div>
      )}

      <button
        type="submit"
        disabled={loading || !email || !password}
        className="w-full flex items-center justify-center gap-2 bg-orange-500 hover:bg-orange-600 disabled:bg-orange-500/40 disabled:cursor-not-allowed text-white font-semibold text-sm py-3 rounded-xl transition-colors"
      >
        {loading ? (
          <>
            <Loader2 className="w-4 h-4 animate-spin" />
            Authenticating…
          </>
        ) : (
          'Sign In'
        )}
      </button>

      <div className="flex items-center justify-center mt-2">
        <Link
          href="/admin/signup"
          className="text-xs text-gray-500 hover:text-gray-300 transition-colors"
        >
          Need an account?{' '}
          <span className="text-orange-400 font-semibold hover:text-orange-300">
            Sign up
          </span>
        </Link>
      </div>
    </form>
  );
}