'use client';

import { useState, Suspense } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useAuthStore, useToastStore } from '@/lib/store';

export default function LoginPage() {
  return (
    <Suspense fallback={<div className="min-h-screen flex items-center justify-center"><div className="w-8 h-8 border-4 border-primary border-t-transparent rounded-full animate-spin"></div></div>}>
      <LoginContent />
    </Suspense>
  );
}

function LoginContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const redirectTo = searchParams.get('redirect');
  const setAuth = useAuthStore(s => s.setAuth);
  const toast = useToastStore(s => s.show);

  const [mode, setMode] = useState<'login' | 'register'>('login');
  const [loading, setLoading] = useState(false);
  const [form, setForm] = useState({
    email: '', password: '', first_name: '', last_name: '', phone: '', remember_me: false,
  });

  function update(field: string, value: string | boolean) {
    setForm(prev => ({ ...prev, [field]: value }));
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setLoading(true);

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

      const data = await res.json();
      if (!data.success) {
        toast(data.error || 'Something went wrong', 'error');
        setLoading(false);
        return;
      }

      setAuth(data.data.user, 'session');
      toast(mode === 'login' ? `Welcome back, ${data.data.user.first_name}!` : 'Account created! Check your email.', 'success');
      // Redirect admin users to /admin, or honor redirect param
      if (redirectTo) {
        router.push(redirectTo);
      } else if (data.data.user.is_admin) {
        router.push('/admin');
      } else {
        router.push('/');
      }
    } catch {
      toast('Network error. Please try again.', 'error');
    }
    setLoading(false);
  }

  return (
    <div className="min-h-screen bg-white flex">
      {/* Left - Testimonial */}
      <div className="hidden lg:flex lg:w-1/2 relative items-center justify-center p-12" style={{ background: 'linear-gradient(135deg, #001233 0%, #002060 30%, #003087 60%, #004ab5 100%)' }}>
        <div className="absolute inset-0 overflow-hidden">
          <div className="absolute -top-20 -right-20 w-96 h-96 bg-blue-400 rounded-full opacity-10 blur-3xl"></div>
          <div className="absolute bottom-0 left-1/4 w-64 h-64 bg-accent rounded-full opacity-5 blur-3xl"></div>
        </div>
        <div className="relative text-white max-w-md">
          <div className="flex items-center gap-2 mb-8">
            <div className="w-12 h-12 bg-accent rounded-xl flex items-center justify-center shadow-lg">
              <span className="text-primary font-black text-2xl">S</span>
            </div>
            <div>
              <span className="font-black text-2xl tracking-tight leading-none block">SceneKey</span>
              <span className="text-accent text-xs font-semibold tracking-widest">STORE</span>
            </div>
          </div>
          <h2 className="text-3xl font-black mb-4 leading-tight">Your Premium Electronics Marketplace</h2>
          <p className="text-blue-200 text-lg mb-8 leading-relaxed">Join thousands of tech enthusiasts who trust SceneKey for the best electronics deals online.</p>
          <div className="bg-white bg-opacity-10 rounded-2xl p-6 border border-white border-opacity-20">
            <div className="flex items-center gap-3 mb-3">
              <img src="https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=60&h=60&q=80&auto=format&fit=crop" alt="Customer" className="w-10 h-10 rounded-full object-cover" />
              <div>
                <p className="font-bold text-sm">David Chen</p>
                <div className="flex gap-0.5 text-yellow-400 text-xs">⭐⭐⭐⭐⭐</div>
              </div>
            </div>
            <p className="text-blue-100 text-sm italic">&quot;Best electronics store I&apos;ve ever used. The auction feature saved me hundreds on a camera!&quot;</p>
          </div>
          <div className="flex items-center gap-6 mt-8">
            <div className="text-center"><div className="text-2xl font-black text-accent">50K+</div><div className="text-xs text-blue-200">Products</div></div>
            <div className="w-px h-10 bg-white bg-opacity-20"></div>
            <div className="text-center"><div className="text-2xl font-black text-accent">4.9</div><div className="text-xs text-blue-200">Rating</div></div>
            <div className="w-px h-10 bg-white bg-opacity-20"></div>
            <div className="text-center"><div className="text-2xl font-black text-accent">2M+</div><div className="text-xs text-blue-200">Customers</div></div>
          </div>
        </div>
      </div>

      {/* Right - Form */}
      <div className="flex-1 flex items-center justify-center p-8">
        <div className="w-full max-w-md">
          {/* Mobile Logo */}
          <div className="lg:hidden flex items-center gap-2 mb-8 justify-center">
            <div className="w-10 h-10 bg-accent rounded-xl flex items-center justify-center shadow-lg">
              <span className="text-primary font-black text-xl">S</span>
            </div>
            <div>
              <span className="text-primary font-black text-xl tracking-tight leading-none block">SceneKey</span>
              <span className="text-accent text-xs font-semibold tracking-widest">STORE</span>
            </div>
          </div>

          <h1 className="text-2xl font-black text-gray-900 mb-1">
            {mode === 'login' ? 'Welcome back' : 'Create your account'}
          </h1>
          <p className="text-gray-500 text-sm mb-6">
            {mode === 'login' ? 'Sign in to your SceneKey account' : 'Join the SceneKey community'}
          </p>

          <form onSubmit={handleSubmit} className="space-y-4">
            {mode === 'register' && (
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs font-semibold text-gray-700 mb-1">First Name</label>
                  <input type="text" required value={form.first_name} onChange={e => update('first_name', e.target.value)}
                    className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm focus:border-primary" />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-gray-700 mb-1">Last Name</label>
                  <input type="text" required value={form.last_name} onChange={e => update('last_name', e.target.value)}
                    className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm focus:border-primary" />
                </div>
              </div>
            )}

            <div>
              <label className="block text-xs font-semibold text-gray-700 mb-1">Email Address</label>
              <input type="email" required value={form.email} onChange={e => update('email', e.target.value)}
                className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm focus:border-primary" placeholder="you@example.com" />
            </div>

            <div>
              <label className="block text-xs font-semibold text-gray-700 mb-1">Password</label>
              <input type="password" required value={form.password} onChange={e => update('password', e.target.value)}
                className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm focus:border-primary" placeholder="Min. 8 characters" minLength={8} />
            </div>

            {mode === 'register' && (
              <div>
                <label className="block text-xs font-semibold text-gray-700 mb-1">Phone Number <span className="text-gray-400">(optional)</span></label>
                <input type="tel" value={form.phone} onChange={e => update('phone', e.target.value)}
                  className="w-full px-4 py-2.5 rounded-xl border border-gray-200 text-sm focus:border-primary" placeholder="+1 (555) 000-0000" />
              </div>
            )}

            {mode === 'login' && (
              <div className="flex items-center justify-between">
                <label className="flex items-center gap-2 cursor-pointer">
                  <input type="checkbox" checked={form.remember_me} onChange={e => update('remember_me', e.target.checked)}
                    className="w-4 h-4 rounded border-gray-300" />
                  <span className="text-sm text-gray-600">Remember me</span>
                </label>
                <Link href="/forgot-password" className="text-sm text-primary font-semibold hover:underline">Forgot password?</Link>
              </div>
            )}

            <button type="submit" disabled={loading}
              className="w-full btn-primary py-3 rounded-xl font-bold text-sm disabled:opacity-50 flex items-center justify-center gap-2">
              {loading ? (
                <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
              ) : (
                mode === 'login' ? 'Sign In' : 'Create Account'
              )}
            </button>
          </form>

          <div className="mt-6 text-center">
            <p className="text-sm text-gray-500">
              {mode === 'login' ? "Don't have an account? " : 'Already have an account? '}
              <button onClick={() => setMode(mode === 'login' ? 'register' : 'login')} className="text-primary font-semibold hover:underline">
                {mode === 'login' ? 'Sign Up' : 'Sign In'}
              </button>
            </p>
          </div>

          <div className="mt-8 grid grid-cols-3 gap-3 text-center">
            <div className="bg-gray-50 rounded-xl p-3">
              <div className="text-lg">🔒</div>
              <p className="text-xs text-gray-500 mt-1">Secure</p>
            </div>
            <div className="bg-gray-50 rounded-xl p-3">
              <div className="text-lg">📦</div>
              <p className="text-xs text-gray-500 mt-1">Free Shipping</p>
            </div>
            <div className="bg-gray-50 rounded-xl p-3">
              <div className="text-lg">🔄</div>
              <p className="text-xs text-gray-500 mt-1">Easy Returns</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

