'use client';

import React, { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import {
  ShieldCheck,
  Lock,
  Mail,
  ArrowRight,
  AlertCircle,
  Eye,
  EyeOff,
  Zap,
} from 'lucide-react';

export default function LoginPage() {
  const router = useRouter();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

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

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

      const data = await res.json();
      if (!data.success) {
        setError(data.error?.message || 'Invalid email or password.');
      } else {
        const user = data.data.user;
        if (user.role === 'SUPER_ADMIN') {
          router.push('/super-admin-dashboard');
        } else if (user.role === 'ADMIN') {
          router.push('/admin-dashboard');
        } else if (user.role === 'API_USER') {
          router.push('/api-dashboard');
        } else {
          router.push('/dashboard');
        }
      }
    } catch (err: any) {
      setError('Connection error. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  const setTestAccount = (testEmail: string, testPass: string) => {
    setEmail(testEmail);
    setPassword(testPass);
    setError(null);
  };

  return (
    <div className="min-h-screen bg-[#f8fafc] text-slate-900 font-sans flex flex-col justify-center py-12 sm:px-6 lg:px-8 selection:bg-emerald-500/20">
      <div className="sm:mx-auto sm:w-full sm:max-w-md text-center space-y-3">
        <Link href="/" className="inline-flex items-center gap-2.5">
          <div className="w-10 h-10 rounded-xl bg-gradient-to-tr from-emerald-600 to-teal-500 flex items-center justify-center text-white shadow-md shadow-emerald-500/20">
            <ShieldCheck className="w-6 h-6" />
          </div>
          <span className="text-2xl font-extrabold text-slate-900 tracking-tight">
            Smart<span className="text-emerald-700">Auth</span>
          </span>
        </Link>
        <h2 className="text-xl font-bold text-slate-900">
          Sign In to Your Account
        </h2>
        <p className="text-xs text-slate-500">
          Access your identity verification workspace, units balance, and API settings.
        </p>
      </div>

      <div className="mt-6 sm:mx-auto sm:w-full sm:max-w-md">
        <div className="bg-white py-8 px-6 sm:px-8 shadow-sm border border-slate-200/90 rounded-2xl space-y-5">
          {error && (
            <div className="p-3.5 rounded-xl bg-rose-50 border border-rose-200 text-rose-800 text-xs font-semibold flex items-center gap-2">
              <AlertCircle className="w-4 h-4 text-rose-600 shrink-0" />
              <span>{error}</span>
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-xs font-semibold text-slate-700 mb-1.5">
                Email Address
              </label>
              <div className="relative">
                <Mail className="w-4 h-4 text-slate-400 absolute left-3.5 top-3" />
                <input
                  type="email"
                  required
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="name@company.com"
                  className="w-full bg-slate-50 border border-slate-200 rounded-xl pl-10 pr-4 py-2.5 text-xs text-slate-900 focus:outline-none focus:border-emerald-600 font-mono"
                />
              </div>
            </div>

            <div>
              <div className="flex items-center justify-between mb-1.5">
                <label className="block text-xs font-semibold text-slate-700">
                  Password
                </label>
              </div>
              <div className="relative">
                <Lock className="w-4 h-4 text-slate-400 absolute left-3.5 top-3" />
                <input
                  type={showPassword ? 'text' : 'password'}
                  required
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="••••••••"
                  className="w-full bg-slate-50 border border-slate-200 rounded-xl pl-10 pr-10 py-2.5 text-xs text-slate-900 focus:outline-none focus:border-emerald-600 font-mono"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-2.5 text-slate-400 hover:text-slate-600 p-0.5"
                >
                  {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                </button>
              </div>
            </div>

            <button
              type="submit"
              disabled={loading}
              className="w-full py-3 bg-[#00875a] hover:bg-[#00693e] text-white text-xs font-bold rounded-xl shadow-md transition-all flex items-center justify-center gap-2 disabled:opacity-50"
            >
              {loading ? (
                <span className="animate-pulse">Authenticating...</span>
              ) : (
                <>
                  <span>Sign In</span>
                  <ArrowRight className="w-4 h-4" />
                </>
              )}
            </button>
          </form>

          {/* 1-Click Demo Accounts */}
          <div className="space-y-2 pt-2 border-t border-slate-100">
            <div className="flex items-center gap-1.5 text-[11px] font-bold text-slate-500 uppercase tracking-wider font-mono">
              <Zap className="w-3.5 h-3.5 text-amber-500" />
              <span>1-Click Fast Login Test Accounts:</span>
            </div>

            <div className="grid grid-cols-2 gap-2 text-xs">
              <button
                type="button"
                onClick={() => setTestAccount('admin@smartauth.ng', 'AdminPass123!')}
                className="p-2.5 bg-emerald-50/70 hover:bg-emerald-100/70 border border-emerald-200 rounded-xl text-left transition-colors"
              >
                <div className="font-bold text-emerald-900 text-[11.5px]">👑 Super Admin</div>
                <div className="text-[10px] text-emerald-700 font-mono truncate">admin@smartauth.ng</div>
              </button>

              <button
                type="button"
                onClick={() => setTestAccount('ops@smartauth.ng', 'AdminPass123!')}
                className="p-2.5 bg-emerald-50/70 hover:bg-emerald-100/70 border border-emerald-200 rounded-xl text-left transition-colors"
              >
                <div className="font-bold text-emerald-900 text-[11.5px]">🛡️ Admin (Ops)</div>
                <div className="text-[10px] text-emerald-700 font-mono truncate">ops@smartauth.ng</div>
              </button>

              <button
                type="button"
                onClick={() => setTestAccount('apiuser@smartauth.ng', 'ApiUserPass123!')}
                className="p-2.5 bg-emerald-50/70 hover:bg-emerald-100/70 border border-emerald-200 rounded-xl text-left transition-colors"
              >
                <div className="font-bold text-emerald-900 text-[11.5px]">🔑 API User</div>
                <div className="text-[10px] text-emerald-700 font-mono truncate">apiuser@smartauth.ng</div>
              </button>

              <button
                type="button"
                onClick={() => setTestAccount('user@smartauth.ng', 'UserPass123!')}
                className="p-2.5 bg-slate-50 hover:bg-slate-100 border border-slate-200 rounded-xl text-left transition-colors"
              >
                <div className="font-bold text-slate-800 text-[11.5px]">🔍 User (Standard)</div>
                <div className="text-[10px] text-slate-500 font-mono truncate">user@smartauth.ng</div>
              </button>
            </div>
          </div>

          <div className="pt-2 text-center text-xs text-slate-500">
            Don&apos;t have an account?{' '}
            <Link href="/register" className="font-bold text-emerald-700 hover:text-emerald-800">
              Register Now
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}
