/**
 * @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, PasswordSetupRequiredError } from '../services/auth';
import type { AuthUser } from '../services/auth';
import { useLogin, useSetPassword } 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' | 'setup'>('email');
  const [checkingEmail, setCheckingEmail] = useState(false);

  // First-time login: the account exists but has never had a password set
  // (a freshly onboarded tenant admin or store login). Captured off
  // PasswordSetupRequiredError so the create-password step knows which
  // userid to write to.
  const [setupUserId, setSetupUserId] = useState<number | null>(null);
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showNewPassword, setShowNewPassword] = useState(false);

  const login = useLogin();
  const setPasswordMut = useSetPassword();
  const loading = login.isPending || setPasswordMut.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 result = await checkEmailRequest(email);
        if (result.exists && result.needsSetup && result.userid != null) {
          // No point asking for a password this account doesn't have yet —
          // go straight to creating one.
          setSetupUserId(result.userid);
          setStep('setup');
        } else if (result.exists) {
          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 (step === 'password') {
      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) => {
            if (err instanceof PasswordSetupRequiredError) {
              // First login for this account — no password set yet (a fresh
              // tenant admin or store login). Send them to create one instead
              // of showing this as a failure.
              setSetupUserId(err.userid);
              setStep('setup');
              return;
            }
            setError(err instanceof Error ? err.message : 'Sign in failed. Please try again.');
          },
        },
      );
    } else {
      // step === 'setup'
      if (setupUserId == null) {
        setError('Something went wrong. Please start over.');
        setStep('email');
        return;
      }
      if (newPassword.length < 6) {
        setError('Password must be at least 6 characters.');
        return;
      }
      if (newPassword !== confirmPassword) {
        setError('Passwords do not match.');
        return;
      }
      setError('');
      setPasswordMut.mutate(
        { userid: setupUserId, password: newPassword },
        {
          onSuccess: () => {
            // Password is set — sign in with it right away instead of making
            // them type it again.
            login.mutate(
              { email, password: newPassword },
              {
                onSuccess: (user) => onLogin(user),
                onError: (err) =>
                  setError(err instanceof Error ? err.message : 'Sign in failed. Please try again.'),
              },
            );
          },
          onError: (err) =>
            setError(err instanceof Error ? err.message : 'Could not set password. 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-[#531b6e] via-[#3d1653] to-slate-950 text-white flex-col p-8 xl:p-14 2xl:p-20 justify-center items-center">
        {/* Layered ambient glows */}
        <div className="absolute -top-24 -right-24 w-96 h-96 bg-purple-500/20 rounded-full blur-[120px] pointer-events-none" />
        <div className="absolute -bottom-24 -left-24 w-[24rem] h-[24rem] bg-indigo-500/15 rounded-full blur-[140px] pointer-events-none" />
        {/* Subtle dot-grid texture */}
        <div
          className="absolute inset-0 opacity-[0.05] pointer-events-none"
          style={{ backgroundImage: 'radial-gradient(circle, #ffffff 1px, transparent 1px)', backgroundSize: '24px 24px' }}
        />

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

          {/* Eyebrow badge */}
          <div className="inline-flex items-center gap-1.5 text-xs font-semibold tracking-wider text-purple-200 bg-white/10 border border-white/15 rounded-full px-3.5 py-1.5 backdrop-blur-md self-start">
            <ShieldCheck size={14} className="text-purple-300 shrink-0" />
            <span>Secure Merchant Console</span>
          </div>

          <h1 className="text-4xl lg:text-5xl xl:text-6xl font-extrabold tracking-tight leading-[1.1] mt-6">
            All Operations <br />
            <span className="bg-gradient-to-r from-white via-purple-100 to-purple-300 bg-clip-text text-transparent">
              In One Console
            </span>
          </h1>
          
          <p className="text-purple-200/90 text-base xl:text-lg leading-relaxed mt-5 max-w-[460px]">
            Monitor regional hubs, track live order operations, and manage your entire store network from a single command center.
          </p>
        </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">
              {step === 'setup' ? 'Create your password' : 'Welcome back'}
            </h2>
            <p className="text-slate-500 text-sm mt-2">
              {step === 'setup'
                ? 'This is your first sign-in — set a password to finish activating your account.'
                : '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' || step === 'setup') && (
                  <button
                    type="button"
                    onClick={() => {
                      setStep('email');
                      setError('');
                      setPassword('');
                      setSetupUserId(null);
                      setNewPassword('');
                      setConfirmPassword('');
                    }}
                    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' || step === 'setup'}
                  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>

            {/* First-login password setup */}
            {step === 'setup' && (
              <div className="space-y-4">
                <div className="space-y-2">
                  <label htmlFor="new-password" className="block text-xs font-bold text-slate-600 uppercase tracking-wider">
                    New 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="new-password"
                      type={showNewPassword ? 'text' : 'password'}
                      value={newPassword}
                      onChange={(e) => setNewPassword(e.target.value)}
                      placeholder="At least 6 characters"
                      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={() => setShowNewPassword((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={showNewPassword ? 'Hide password' : 'Show password'}
                    >
                      {showNewPassword ? <EyeOff size={16} /> : <Eye size={16} />}
                    </button>
                  </div>
                </div>
                <div className="space-y-2">
                  <label htmlFor="confirm-password" className="block text-xs font-bold text-slate-600 uppercase tracking-wider">
                    Confirm 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="confirm-password"
                      type={showNewPassword ? 'text' : 'password'}
                      value={confirmPassword}
                      onChange={(e) => setConfirmPassword(e.target.value)}
                      placeholder="Re-enter password"
                      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"
                    />
                  </div>
                </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-[#662582] 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…' : setPasswordMut.isPending ? 'Setting Password…' : 'Verifying…'}
                </>
              ) : (
                <>
                  {step === 'email' ? 'Continue' : step === 'setup' ? 'Set Password & Sign In' : '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>
  );
}
