'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import api from '@/lib/api';

export default function LoginPage() {
  const router = useRouter();
  const [form, setForm]       = useState({ email: '', password: '' });
  const [error, setError]     = useState('');
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      const { data } = await api.post('/auth/login', form);
      if (data.data.user.role !== 'admin') {
        setError('Acceso denegado. Solo administradores.');
        return;
      }
      localStorage.setItem('admin_token', data.data.token);
      localStorage.setItem('admin_user', JSON.stringify(data.data.user));
      router.push('/');
    } catch (err) {
      setError(err.response?.data?.message || 'Error al iniciar sesión');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex">
      {/* Left panel */}
      <div className="hidden lg:flex lg:w-1/2 flex-col items-center justify-center p-12 text-white relative overflow-hidden"
        style={{ background: 'linear-gradient(135deg, #1B3A8C 0%, #152d6e 60%, #0f2057 100%)' }}>
        <div className="absolute inset-0 opacity-10"
          style={{ backgroundImage: 'radial-gradient(circle at 20% 80%, #fff 1px, transparent 1px), radial-gradient(circle at 80% 20%, #fff 1px, transparent 1px)', backgroundSize: '60px 60px' }} />
        <div className="relative z-10 text-center max-w-sm">
          <img src="/logo.png" alt="ALBaraTái" className="h-16 mx-auto mb-8 object-contain brightness-0 invert" />
          <h1 className="text-3xl font-bold mb-4 leading-tight">Bienvenido al Panel de Administración</h1>
          <p className="text-blue-200 text-sm leading-relaxed">Gestiona usuarios, categorías, planes y todo el contenido de la plataforma ALBaraTái desde un solo lugar.</p>
          <div className="mt-10 grid grid-cols-2 gap-4 text-left">
            {[
              { icon: '👥', label: 'Usuarios', desc: 'Gestión completa' },
              { icon: '💎', label: 'Planes', desc: 'Suscripciones' },
              { icon: '🗂️', label: 'Categorías', desc: 'Árbol jerárquico' },
              { icon: '📊', label: 'Dashboard', desc: 'Estadísticas' },
            ].map(item => (
              <div key={item.label} className="bg-white/10 rounded-xl p-3 backdrop-blur-sm">
                <div className="text-xl mb-1">{item.icon}</div>
                <div className="text-sm font-semibold">{item.label}</div>
                <div className="text-xs text-blue-300">{item.desc}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Right panel */}
      <div className="flex-1 flex items-center justify-center p-6 bg-gray-50">
        <div className="w-full max-w-md">
          {/* Mobile logo */}
          <div className="lg:hidden text-center mb-8">
            <img src="/logo.png" alt="ALBaraTái" className="h-12 mx-auto object-contain" />
          </div>

          <div className="bg-white rounded-3xl shadow-xl border border-gray-100 p-8">
            <div className="mb-8">
              <h2 className="text-2xl font-bold text-gray-800">Iniciar sesión</h2>
              <p className="text-gray-500 text-sm mt-1">Ingresa tus credenciales de administrador</p>
            </div>

            {error && (
              <div className="bg-red-50 border border-red-200 text-red-700 rounded-xl px-4 py-3 text-sm mb-6 flex items-center gap-2">
                <span>⚠️</span> {error}
              </div>
            )}

            <form onSubmit={handleSubmit} className="space-y-5">
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">Correo electrónico</label>
                <input
                  type="email" required
                  value={form.email}
                  onChange={e => setForm({ ...form, email: e.target.value })}
                  className="w-full border border-gray-200 rounded-xl px-4 py-3 text-sm outline-none focus:border-primary focus:ring-2 focus:ring-primary/10 transition"
                  placeholder="admin@albaratai.com.mx"
                />
              </div>
              <div>
                <label className="block text-sm font-semibold text-gray-700 mb-2">Contraseña</label>
                <input
                  type="password" required
                  value={form.password}
                  onChange={e => setForm({ ...form, password: e.target.value })}
                  className="w-full border border-gray-200 rounded-xl px-4 py-3 text-sm outline-none focus:border-primary focus:ring-2 focus:ring-primary/10 transition"
                  placeholder="••••••••"
                />
              </div>
              <button
                type="submit" disabled={loading}
                className="w-full font-bold py-3 rounded-xl transition disabled:opacity-60 text-white text-sm mt-2"
                style={{ background: loading ? '#6b7280' : 'linear-gradient(135deg, #1B3A8C, #2d5fd4)' }}
              >
                {loading ? 'Iniciando sesión...' : 'Iniciar sesión →'}
              </button>
            </form>
          </div>

          <p className="text-center text-xs text-gray-400 mt-6">ALBaraTái © {new Date().getFullYear()} — Solo para administradores</p>
        </div>
      </div>
    </div>
  );
}
