'use client';
import React, { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';

export default function AdminLogin() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const router = useRouter();

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

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

      const data = await res.json();

      if (!res.ok) {
        throw new Error(data.error || 'Login failed');
      }

      router.push('/admin');
      router.refresh();
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="w-full max-w-md bg-white rounded-2xl shadow-xl overflow-hidden">
      <div className="bg-slate-900 p-8 text-center">
        <div className="bg-white p-3 rounded-lg inline-block mb-4 shadow-sm">
           <img src="/logo.png" alt="UKBCCI" className="h-10 w-auto" />
        </div>
        <h2 className="text-2xl font-bold text-white">Admin Login</h2>
        <p className="text-slate-400 mt-2">UKBCCI Content Management</p>
      </div>
      
      <div className="p-8">
        <form onSubmit={handleLogin} className="space-y-6">
          {error && (
            <div className="bg-red-50 text-red-600 text-sm p-3 rounded-lg border border-red-200">
              {error}
            </div>
          )}
          
          <div>
            <label className="block text-sm font-medium text-slate-700 mb-2">Email Address</label>
            <input
              type="email"
              required
              className="w-full px-4 py-3 rounded-lg border border-slate-300 focus:ring-2 focus:ring-primary focus:border-transparent outline-none transition"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="admin@ukbcci.org.uk"
            />
          </div>
          
          <div>
            <div className="flex justify-between items-center mb-2">
               <label className="block text-sm font-medium text-slate-700">Password</label>
               <Link href="/admin/forgot-password" className="text-xs text-primary hover:underline">Forgot Password?</Link>
            </div>
            <input
              type="password"
              required
              className="w-full px-4 py-3 rounded-lg border border-slate-300 focus:ring-2 focus:ring-primary focus:border-transparent outline-none transition"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="••••••••"
            />
          </div>

          <button
            type="submit"
            disabled={loading}
            className="w-full bg-primary hover:bg-primary-dark text-white font-bold py-3 rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {loading ? 'Authenticating...' : 'Sign In'}
          </button>
          
          <div className="text-center">
             <button type="button" onClick={async () => {
                await fetch('/api/seed');
                alert('Seed script triggered. Try logging in with default credentials.');
             }} className="text-xs text-slate-400 hover:text-primary">
               Initialize Admin (Dev Only)
             </button>
          </div>
        </form>
      </div>
    </div>
  );
}