'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import { users } from '@/data/mockData';
import { Zap, ArrowRight, Bike, Wallet, Shield, Users, Calculator } from 'lucide-react';

const demoUsers = [
  { email: 'superadmin@jaiben.com', role: 'super_admin', label: 'Super Admin', icon: Shield, color: 'bg-accent' },
  { email: 'adminmanager@jaiben.com', role: 'admin_manager', label: 'Admin Manager', icon: Users, color: 'bg-blue-500' },
  { email: 'staff@jaiben.com', role: 'staff', label: 'Front Desk', icon: Users, color: 'bg-purple-500' },
  { email: 'accountant@jaiben.com', role: 'accountant', label: 'Accountant', icon: Calculator, color: 'bg-green-500' },
  { email: 'investor@email.com', role: 'investor', label: 'Investor', icon: Wallet, color: 'bg-amber-500' },
  // { email: 'swap@jaiben.com', role: 'swapstation', label: 'Swap Station', icon: Zap, color: 'bg-purple-500' },
];

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

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

    await new Promise(resolve => setTimeout(resolve, 800));

    const user = users.find(u => u.email === email);

    if (user && password === 'demo123') {
      sessionStorage.setItem('authToken', 'demo-token');
      sessionStorage.setItem('userRole', user.role);
      sessionStorage.setItem('userName', user.name);

      const rolePerms: Record<string, string[]> = {
        super_admin: ['kyc.request', 'kyc.view', 'kyc.doc_upload', 'kyc.doc_approve', 'kyc.doc_reject', 'kyc.make_valid_user', 'dashboard.view'],
        admin_manager: ['kyc.request', 'kyc.view', 'kyc.doc_upload', 'kyc.doc_approve', 'kyc.doc_reject', 'kyc.make_valid_user', 'dashboard.view'],
        staff: ['kyc.request', 'kyc.view', 'kyc.doc_upload', 'dashboard.view'],
        accountant: ['dashboard.view', 'accounting.view', 'accounting.create', 'accounting.edit', 'accounting.delete'],
        investor: ['dashboard.view', 'kyc.request', 'kyc.view'],
        biker: ['dashboard.view', 'kyc.request', 'kyc.view', 'rentals.view', 'rentals.create'],
        'swapstation': ['dashboard.view', 'kyc.request', 'kyc.view'],
        merchant: ['dashboard.view', 'kyc.request', 'kyc.view', 'merchants.view'],
      };
      sessionStorage.setItem('userPermissions', JSON.stringify(rolePerms[user.role] || []));

      switch (user.role) {
        case 'super_admin':
        case 'admin_manager':
        case 'staff':
          router.push('/admin');
          break;
        case 'accountant':
          router.push('/admin/accounting');
          break;
        case 'investor':
          router.push('/investor/dashboard');
          break;
        case 'biker':
          router.push('/biker');
          break;
        case 'swapstation':
          router.push('/swapstation');
          break;
        case 'merchant':
          router.push('/merchant');
          break;
        default:
          router.push('/login');
      }
    } else {
      setError('Invalid email or password. Try demo123');
    }

    setLoading(false);
  };

  const handleQuickLogin = async (userEmail: string) => {
    setLoading(true);
    await new Promise(resolve => setTimeout(resolve, 500));

    const user = users.find(u => u.email === userEmail);
    if (user) {
      sessionStorage.setItem('authToken', 'demo-token');
      sessionStorage.setItem('userRole', user.role);
      sessionStorage.setItem('userName', user.name);

      const rolePerms: Record<string, string[]> = {
        super_admin: ['kyc.request', 'kyc.view', 'kyc.doc_upload', 'kyc.doc_approve', 'kyc.doc_reject', 'kyc.make_valid_user', 'dashboard.view'],
        admin_manager: ['kyc.request', 'kyc.view', 'kyc.doc_upload', 'kyc.doc_approve', 'kyc.doc_reject', 'kyc.make_valid_user', 'dashboard.view'],
        staff: ['kyc.request', 'kyc.view', 'kyc.doc_upload', 'dashboard.view'],
        accountant: ['dashboard.view', 'accounting.view', 'accounting.create', 'accounting.edit', 'accounting.delete'],
        investor: ['dashboard.view', 'kyc.request', 'kyc.view'],
        biker: ['dashboard.view', 'kyc.request', 'kyc.view', 'rentals.view', 'rentals.create'],
        'swapstation': ['dashboard.view', 'kyc.request', 'kyc.view'],
        merchant: ['dashboard.view', 'kyc.request', 'kyc.view', 'merchants.view'],
      };
      sessionStorage.setItem('userPermissions', JSON.stringify(rolePerms[user.role] || []));

      switch (user.role) {
        case 'super_admin':
        case 'admin_manager':
        case 'staff':
          router.push('/admin');
          break;
        case 'accountant':
          router.push('/admin/accounting');
          break;
        case 'investor':
          router.push('/investor/dashboard');
          break;
        case 'biker':
          router.push('/biker');
          break;
        case 'swapstation':
          router.push('/swapstation');
          break;
        case 'merchant':
          router.push('/merchant');
          break;
        default:
          router.push('/login');
      }
    }
    setLoading(false);
  };

  return (
    <div className="w-full min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        <div className="text-center mb-8">
          <button
            onClick={() => router.push('/')}
            className="inline-flex items-center gap-3 text-left"
          >
            <Image src="/jaiben.png" alt="JAIBEN Logo" width={56} height={56} className="object-contain h-12 w-auto" priority />
            <div>
              <h1 className="text-3xl font-extrabold text-white leading-tight">JAIBEN</h1>
              <p className="text-sm text-slate-400 leading-none">Mobility Ltd</p>
            </div>
          </button>
        </div>

        <div className="bg-slate-800/50 border border-slate-700 rounded-2xl p-6 lg:p-8 backdrop-blur">
          <div className="text-center mb-6">
            <h2 className="text-xl font-bold text-white mb-1">Welcome Back</h2>
            <p className="text-slate-400 text-sm">Sign in to continue to your dashboard</p>
          </div>

          <form onSubmit={handleLogin} className="space-y-4">
            <div>
              <label htmlFor="email" className="block text-sm font-medium text-slate-300 mb-2">
                Email Address
              </label>
              <input
                type="email"
                id="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
                className="w-full px-4 py-3 bg-slate-700/50 border border-slate-600 rounded-lg text-white placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-accent focus:border-accent transition-all"
                placeholder="Enter your email"
              />
            </div>

            <div>
              <label htmlFor="password" className="block text-sm font-medium text-slate-300 mb-2">
                Password <span className="text-slate-500 text-xs">(demo: demo123)</span>
              </label>
              <input
                type="password"
                id="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                required
                className="w-full px-4 py-3 bg-slate-700/50 border border-slate-600 rounded-lg text-white placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-accent focus:border-accent transition-all"
                placeholder="Enter your password"
              />
            </div>

            {error && (
              <div className="bg-red-500/10 border border-red-500/30 text-red-400 px-4 py-3 rounded-lg text-sm">
                {error}
              </div>
            )}

            <button
              type="submit"
              disabled={loading}
              className="w-full py-3 bg-accent text-white rounded-lg font-semibold hover:bg-accent-dark transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
            >
              {loading ? (
                <>
                  <svg className="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z"></path>
                  </svg>
                  Signing in...
                </>
              ) : (
                <>
                  Sign In <ArrowRight className="w-5 h-5" />
                </>
              )}
            </button>
          </form>

          <div className="mt-6 pt-6 border-t border-slate-700">
            <p className="text-slate-400 text-sm mb-4 text-center">Quick Login as Demo User:</p>
            <div className="grid grid-cols-1 gap-2">
              {demoUsers.map((user) => {
                const Icon = user.icon;
                return (
                  <button
                    key={user.email}
                    onClick={() => handleQuickLogin(user.email)}
                    disabled={loading}
                    className="flex items-center gap-3 px-4 py-2.5 bg-slate-700/30 border border-slate-600 rounded-lg hover:border-accent hover:bg-slate-700/50 transition-all text-left"
                  >
                    <div className={`w-8 h-8 ${user.color} rounded-lg flex items-center justify-center`}>
                      <Icon className="w-4 h-4 text-white" />
                    </div>
                    <div className="flex-1">
                      <p className="text-white font-medium text-sm">{user.label}</p>
                      <p className="text-slate-400 text-xs">{user.email}</p>
                    </div>
                    <ArrowRight className="w-4 h-4 text-slate-500" />
                  </button>
                );
              })}
            </div>
          </div>
        </div>

        <div className="mt-6 text-center">
          <button
            onClick={() => router.push('/')}
            className="text-slate-400 hover:text-white text-sm transition-colors flex items-center justify-center gap-2"
          >
            <ArrowRight className="w-4 h-4 rotate-180" /> Back to Home
          </button>
        </div>

        <div className="mt-6 text-center">
          <p className="text-slate-500 text-xs">
            &copy; 2026 JAIBEN Mobility Ltd. All rights reserved.
          </p>
        </div>
      </div>
    </div>
  );
}