/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState } from 'react';
import {
  ShieldCheck,
  Mail,
  Lock,
  ArrowRight,
  Eye,
  EyeOff,
  Loader2,
} from 'lucide-react';
import { checkEmailRequest } from '../services/auth';
import type { AuthUser } from '../services/auth';
import { useLogin } from '../services/fiestaQueries';

interface LoginViewProps {
  /** Called with the authenticated user once credentials are verified. */
  onLogin: (user: AuthUser) => void;
}

export default function LoginView({ onLogin }: LoginViewProps) {
  // A single login form. The backend's role on the verified user decides the
  // workspace (admin vs user) the account actually lands on.
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState('');
  const [step, setStep] = useState<'email' | 'password'>('email');
  const [checkingEmail, setCheckingEmail] = useState(false);

  const login = useLogin();
  const loading = login.isPending;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (loading || checkingEmail) return;

    if (step === 'email') {
      if (!email.trim()) {
        setError('Please enter your email.');
        return;
      }
      setError('');
      setCheckingEmail(true);
      try {
        const emailExists = await checkEmailRequest(email);
        if (emailExists) {
          setStep('password');
        } else {
          setError('Email not found. Please try again.');
        }
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Unable to verify email. Please try again.');
      } finally {
        setCheckingEmail(false);
      }
    } else {
      if (!password.trim()) {
        setError('Please enter your password.');
        return;
      }
      setError('');
      // Verify credentials against the backend via the TanStack mutation. Only an
      // exact match resolves; the returned role routes admin vs user workspace.
      login.mutate(
        { email, password },
        {
          onSuccess: (user) => onLogin(user),
          onError: (err) =>
            setError(err instanceof Error ? err.message : 'Sign in failed. Please try again.'),
        },
      );
    }
  };

  return (
    <div className="h-screen w-full flex bg-white font-sans text-slate-800 overflow-hidden">
      {/* ── Left brand / hero panel (desktop only) ── */}
      <div className="hidden lg:flex lg:w-1/2 shrink-0 relative overflow-hidden bg-gradient-to-br from-[#5b1d8c] via-purple-950 to-slate-950 text-white flex-col p-12 xl:p-16 justify-center">
        {/* Layered ambient glows */}
        <div className="absolute -top-24 -right-24 w-96 h-96 bg-purple-500/25 rounded-full blur-[120px] pointer-events-none" />
        <div className="absolute -bottom-24 -left-24 w-[26rem] h-[26rem] bg-indigo-500/20 rounded-full blur-[140px] pointer-events-none animate-pulse" style={{ animationDuration: '9s' }} />
        <div className="absolute top-1/3 left-1/2 w-72 h-72 bg-fuchsia-500/10 rounded-full blur-[120px] pointer-events-none" />
        {/* Subtle dot-grid texture */}
        <div
          className="absolute inset-0 opacity-[0.07] pointer-events-none"
          style={{ backgroundImage: 'radial-gradient(circle, #ffffff 1px, transparent 1px)', backgroundSize: '22px 22px' }}
        />

        <div className="relative z-10 flex flex-col justify-center w-full max-w-[520px] mx-auto h-full">
          {/* Logo */}
          <div className="shrink-0 mb-10">
            <img src="/logo.png" alt="nearledaily" className="h-10 w-auto object-contain" />
          </div>

          {/* Hero */}
          <div className="min-h-0">
            {/* Eyebrow */}
            <span className="inline-flex items-center gap-1.5 self-start text-[11px] font-bold uppercase tracking-[0.15em] text-purple-100 bg-white/10 border border-white/15 rounded-full px-3 py-1 backdrop-blur-sm">
              <ShieldCheck size={13} className="text-purple-200" />
              Secure Merchant Console
            </span>

            <h1
              className="text-5xl xl:text-6xl font-bold tracking-tight leading-[1.1] mt-6 max-w-[460px]"
              style={{ textShadow: '0 2px 16px rgba(0,0,0,0.25)' }}
            >
              All Operations
              <br />
              In One Console
            </h1>
            <p className="text-purple-100/90 text-lg xl:text-xl leading-[1.6] mt-6 max-w-[460px]">
              Monitor regional hubs, track live order operations, and manage your entire store network from a single command center.
            </p>

            {/* Glassmorphic live-snapshot preview card */}
            <div className="mt-10 max-w-[460px] rounded-2xl bg-white/10 backdrop-blur-md border border-white/15 p-6 shadow-2xl shadow-purple-950/50">
              <div className="flex items-center justify-between">
                <span className="text-xs font-bold uppercase tracking-widest text-purple-100">Live Operations</span>
                <span className="inline-flex items-center gap-1.5 text-xs font-bold text-emerald-300">
                  <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" />
                  LIVE
                </span>
              </div>

              <div className="mt-5 grid grid-cols-2 gap-6">
                <div>
                  <p className="text-3xl font-extrabold tracking-tight tabular-nums">2,480</p>
                  <p className="text-xs text-purple-200 mt-1">Orders today</p>
                </div>
                <div>
                  <p className="text-3xl font-extrabold tracking-tight text-emerald-300 tabular-nums">98.6%</p>
                  <p className="text-xs text-purple-200 mt-1">Fulfillment</p>
                </div>
              </div>

              {/* Mini bar chart */}
              <div className="mt-5 flex items-end gap-1.5 h-14">
                {[45, 62, 38, 70, 52, 80, 60, 90, 55, 74].map((h, i) => (
                  <div
                    key={i}
                    className="flex-1 rounded-t bg-gradient-to-t from-purple-500/40 to-purple-200/80"
                    style={{ height: `${h}%` }}
                  />
                ))}
              </div>
            </div>
          </div>

          {/* Trust stats + copyright */}
          <div className="shrink-0 mt-10 pt-6 border-t border-white/10 max-w-[460px]">
            <div className="grid grid-cols-3 gap-4">
              {[
                { v: '120+', l: 'Regional hubs' },
                { v: '99.9%', l: 'Platform uptime' },
                { v: '24/7', l: 'Live monitoring' },
              ].map((s) => (
                <div key={s.l}>
                  <p className="text-2xl font-bold tracking-tight">{s.v}</p>
                  <p className="text-xs text-purple-300 mt-0.5">{s.l}</p>
                </div>
              ))}
            </div>
            <p className="text-xs text-purple-300/70 font-medium mt-4">
              © 2026 nearledaily · All rights reserved
            </p>
          </div>
        </div>
      </div>

      {/* ── Right form panel ── */}
      <div className="w-full lg:w-1/2 flex items-center justify-center px-6 py-8 sm:px-10 overflow-y-auto">
        <div className="w-full max-w-[400px]">
          {/* Logo / brand (mobile) */}
          <div className="lg:hidden mb-8">
            <img src="/logo.png" alt="nearledaily" className="h-9 w-auto object-contain" />
          </div>

          {/* Heading */}
          <div className="mb-6">
            <h2 className="text-[1.7rem] font-bold text-slate-900 tracking-tight leading-tight">Welcome back</h2>
            <p className="text-slate-500 text-sm mt-2">Sign in to your nearledaily workspace to continue.</p>
          </div>

          <form onSubmit={handleSubmit} className="space-y-4">
            {/* Email or username (the API's `authname` accepts either) */}
            <div className="space-y-2">
              <div className="flex justify-between items-center">
                <label htmlFor="login-email" className="block text-xs font-bold text-slate-600 uppercase tracking-wider">
                  Email or Username
                </label>
                {step === 'password' && (
                  <button
                    type="button"
                    onClick={() => { setStep('email'); setError(''); setPassword(''); }}
                    className="text-xs font-semibold text-purple-600 hover:text-purple-800 bg-transparent border-none cursor-pointer p-0"
                  >
                    Change Email
                  </button>
                )}
              </div>
              <div className="relative">
                <Mail size={16} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none" />
                <input
                  id="login-email"
                  type="text"
                  autoComplete="username"
                  disabled={step === 'password'}
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="you@nearledaily.com"
                  className="w-full h-12 pl-10 pr-4 bg-slate-50 border border-slate-200 rounded-xl text-sm text-slate-800 placeholder-slate-400 focus:outline-none focus:border-purple-500 focus:bg-white focus:ring-4 focus:ring-purple-500/10 transition-all disabled:opacity-75 disabled:cursor-not-allowed"
                />
              </div>
            </div>

            {/* Password */}
            {step === 'password' && (
              <div className="space-y-2">
                <label htmlFor="login-password" className="block text-xs font-bold text-slate-600 uppercase tracking-wider">
                  Password
                </label>
                <div className="relative">
                  <Lock size={16} className="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none" />
                  <input
                    id="login-password"
                    type={showPassword ? 'text' : 'password'}
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    placeholder="••••••••"
                    className="w-full h-12 pl-10 pr-11 bg-slate-50 border border-slate-200 rounded-xl text-sm text-slate-800 placeholder-slate-400 focus:outline-none focus:border-purple-500 focus:bg-white focus:ring-4 focus:ring-purple-500/10 transition-all"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword((s) => !s)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 bg-transparent border-none cursor-pointer p-1"
                    title={showPassword ? 'Hide password' : 'Show password'}
                  >
                    {showPassword ? <EyeOff size={16} /> : <Eye size={16} />}
                  </button>
                </div>
              </div>
            )}

            {error && (
              <p className="text-xs font-semibold text-rose-600 bg-rose-50 border border-rose-100 rounded-lg px-3 py-2.5">
                {error}
              </p>
            )}

            {/* Options row */}
            {step === 'password' && (
              <div className="flex items-center justify-between text-xs">
                <label className="flex items-center gap-2 text-slate-500 font-medium cursor-pointer select-none">
                  <input type="checkbox" className="h-3.5 w-3.5 rounded border-slate-300 text-purple-600 accent-purple-600 focus:ring-purple-500/30" />
                  Remember me
                </label>
                <button type="button" className="font-semibold text-purple-650 hover:text-purple-800 bg-transparent border-none cursor-pointer">
                  Forgot password?
                </button>
              </div>
            )}

            {/* Submit */}
            <button
              type="submit"
              disabled={loading || checkingEmail}
              className="w-full h-12 flex items-center justify-center gap-2 bg-[#581c87] hover:bg-purple-800 text-white font-bold text-sm rounded-xl shadow-sm hover:shadow-lg transition-all active:scale-[0.98] cursor-pointer border-none disabled:opacity-70 disabled:cursor-not-allowed disabled:active:scale-100"
            >
              {loading || checkingEmail ? (
                <>
                  <Loader2 size={16} className="animate-spin" />
                  {checkingEmail ? 'Checking Email…' : 'Verifying…'}
                </>
              ) : (
                <>
                  {step === 'email' ? 'Continue' : 'Sign in'}
                  <ArrowRight size={16} />
                </>
              )}
            </button>
          </form>

          {/* Helper note */}
          <p className="text-center text-xs text-slate-400 mt-6 leading-relaxed">
            Your workspace is set automatically based on your account access.
          </p>
        </div>
      </div>
    </div>
  );
}
