'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Cookies from 'js-cookie';
import { api, NetworkError } from '@/lib/api';
import { toast } from 'react-toastify';
import { applyToJob, getTrackingToken } from '@/lib/careers';
import DemoCredentialsModal from '@/components/DemoCredentialsModal';

const GENERIC_LOGIN_ERROR = 'Unable to log in at the moment. Please try again later.';

/**
 * Maps the backend's stable `errors.code` to the message shown in the toast.
 * Keeping the mapping here means copy changes don't need a backend deploy, and
 * unknown codes fall back to the server's own message.
 */
const LOGIN_ERROR_MESSAGES: Record<string, string> = {
  missing_credentials: 'Please enter your email and password.',
  missing_email: 'Please enter your email address.',
  missing_password: 'Please enter your password.',
  invalid_email_format: 'Please enter a valid email address.',
  email_not_registered: 'No account found with this email address.',
  incorrect_password: 'Incorrect password. Please try again.',
  invalid_credentials: 'Invalid email or password.',
  account_not_verified: 'Please verify your email before logging in.',
  account_disabled: 'Your account has been disabled. Please contact the administrator.',
  account_locked: 'Your account is locked. Please contact the administrator.',
  service_unavailable: GENERIC_LOGIN_ERROR,
};

/** Turns any thrown login error into a specific, user-friendly message. */
function resolveLoginError(err: unknown): string {
  // Never reached the server — offline, DNS, CORS, backend down.
  if (err instanceof NetworkError) return GENERIC_LOGIN_ERROR;

  const { data, status, message } = (err ?? {}) as {
    data?: { errors?: { code?: string } | null; message?: string };
    status?: number;
    message?: string;
  };

  const code = data?.errors?.code;
  if (code && LOGIN_ERROR_MESSAGES[code]) return LOGIN_ERROR_MESSAGES[code];

  // No recognised code — fall back on the HTTP status.
  if (status && status >= 500) return GENERIC_LOGIN_ERROR;
  if (status === 401 || status === 400) {
    return data?.message || message || 'Invalid email or password.';
  }
  return data?.message || message || GENERIC_LOGIN_ERROR;
}

export default function LoginPage() {
  const router = useRouter();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [mfaCode, setMfaCode] = useState('');
  const [needMfa, setNeedMfa] = useState(false);
  const [mfaMethod, setMfaMethod] = useState('totp');
  const [loading, setLoading] = useState(false);
  const [cooldown, setCooldown] = useState(0);
  const [showDemoModal, setShowDemoModal] = useState(false);
  const [showPassword, setShowPassword] = useState(false);

  useEffect(() => {
    if (cooldown <= 0) return;
    const t = setTimeout(() => setCooldown((c) => c - 1), 1000);
    return () => clearTimeout(t);
  }, [cooldown]);

  const handleResend = async () => {
    try {
      await api.post('/auth/resend-otp/', { email });
      toast.info('A new code has been emailed.');
      setCooldown(30);
    } catch (err) {
      toast.error(err instanceof NetworkError ? GENERIC_LOGIN_ERROR
        : err instanceof Error ? err.message : 'Could not resend the code. Please try again.');
    }
  };

  const saveTokensAndGo = async (data: { access: string; refresh: string }) => {
    Cookies.set('access_token', data.access, { expires: 1 });
    Cookies.set('refresh_token', data.refresh, { expires: 7 });
    const params = typeof window !== 'undefined' ? new URLSearchParams(window.location.search) : null;
    const job = params?.get('job') ?? null;
    if (job) {
      // Preserve the source attribution of the link the visitor arrived on
      // (stored when they landed on the careers page) across the login detour.
      const res = await applyToJob(job, undefined, getTrackingToken(params?.get('t')));
      if (res.ok) {
        toast.success(res.message);
        router.push(`/careers/jobs/${job}`);
        return;
      }
    }
    // Came here from a JD-approval email's "View JD" link — resume it instead
    // of dropping the visitor on the dashboard.
    const review = params?.get('review') ?? null;
    if (review) {
      router.push(`/jobs?review=${encodeURIComponent(review)}`);
      return;
    }
    router.push('/dashboard');
  };

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();

    // Empty-field checks run client-side so the user gets immediate feedback
    // without a round-trip. The backend enforces the same rules independently.
    const trimmedEmail = email.trim();
    if (!trimmedEmail && !password) {
      toast.error('Please enter your email and password.');
      return;
    }
    if (!trimmedEmail) {
      toast.error('Please enter your email address.');
      return;
    }
    if (!password) {
      toast.error('Please enter your password.');
      return;
    }

    setLoading(true);
    try {
      const res = await api.post('/auth/login/', { email: trimmedEmail, password }) as any;
      if (res.data?.mfa_required) {
        setMfaMethod(res.data.method || 'totp');
        setNeedMfa(true);
      } else {
        saveTokensAndGo(res.data);
      }
    } catch (err) {
      toast.error(resolveLoginError(err));
    } finally {
      setLoading(false);
    }
  };

  const handleVerifyMfa = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!mfaCode.trim()) {
      toast.error('Please enter the verification code.');
      return;
    }
    setLoading(true);
    try {
      const res = await api.post('/auth/verify-mfa/', { email: email.trim(), mfa_code: mfaCode }) as any;
      saveTokensAndGo(res.data);
    } catch (err) {
      toast.error(resolveLoginError(err));
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex flex-col md:flex-row">
      {/* Left brand panel (6) */}
      <div className="hidden md:flex md:w-1/2 text-white flex-col justify-center px-10 lg:px-16 py-16 relative overflow-hidden">
        {/* Blurred background image */}
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img
          src="/ats.png"
          alt=""
          className="absolute inset-0 w-full h-full object-cover blur-[3px] scale-105"
        />
        {/* Indigo overlay for readable text */}
        <div className="absolute inset-0 bg-gradient-to-br from-[#405189]/60 via-[#3b4a7e]/55 to-[#28345c]/70" />
        <div className="relative z-10 max-w-md">
          <div className="inline-flex items-center justify-center w-14 h-14 rounded-none bg-white/15 text-white text-2xl mb-6">
            <i className="fa-solid fa-briefcase"></i>
          </div>
          <h2 className="text-3xl font-semibold leading-tight uppercase tracking-widest text-center">ATS Dashboard</h2>
          <p className="text-white/90 mt-3 text-base leading-relaxed">
            Applicant Tracking System — streamline hiring from job posting to offer, all in one place.
          </p>
          <ul className="mt-8 space-y-3 text-sm text-white/85">
            <li className="flex items-center gap-3"><i className="fa-solid fa-circle-check text-[#0ab39c]"></i> Manage jobs, clients & candidates</li>
            <li className="flex items-center gap-3"><i className="fa-solid fa-circle-check text-[#0ab39c]"></i> Role-based access & permissions</li>
            <li className="flex items-center gap-3"><i className="fa-solid fa-circle-check text-[#0ab39c]"></i> Secure login with MFA</li>
          </ul>
        </div>
      </div>

      {/* Right form panel (6) */}
      <div className="md:w-1/2 bg-white flex items-center justify-center px-6 sm:px-10 py-16">
        <div className="w-full max-w-md">
        {/* Heading */}
        <div className="mb-8">
          <h1 className="text-2xl font-semibold text-[#232a45]">
            {!needMfa ? 'Welcome back!' : 'Verify it’s you'}
          </h1>
          <p className="text-sm text-vz-muted mt-1">
            {!needMfa
              ? 'Sign-in to continue to TA-ATS'
              : mfaMethod === 'email'
                ? 'Enter the 6-digit code we emailed you'
                : 'Enter the code from your authenticator app'}
          </p>
        </div>

        {/* noValidate on the login form: we surface empty/invalid-field errors as
            toasts (see handleLogin) rather than the browser's native bubbles. */}
        {!needMfa ? (
          <form onSubmit={handleLogin} noValidate className="space-y-5">
            <button
              type="button"
              onClick={() => setShowDemoModal(true)}
              className="w-full border border-dashed border-[#405189]/40 text-[#405189] py-2.5 rounded-none text-sm font-medium hover:bg-[#405189]/5 transition flex items-center justify-center gap-2 cursor-pointer"
            >
              <i className="fa-solid fa-flask text-xs"></i> View Demo Accounts
            </button>

            <div className="relative">
              <i className="fa-solid fa-envelope absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-sm"></i>
              <input
                type="email" placeholder="Email address" value={email} required
                onChange={(e) => setEmail(e.target.value)}
                className="w-full border border-vz-border rounded-none pl-10 pr-3 py-2.5 text-sm focus:ring-2 focus:ring-[#405189]/25 focus:border-[#405189] focus:outline-none"
              />
            </div>
            <div className="relative">
              <i className="fa-solid fa-lock absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400 text-sm"></i>
              <input
                type={showPassword ? 'text' : 'password'} placeholder="Password" value={password} required
                onChange={(e) => setPassword(e.target.value)}
                className="w-full border border-vz-border rounded-none pl-10 pr-10 py-2.5 text-sm focus:ring-2 focus:ring-[#405189]/25 focus:border-[#405189] focus:outline-none"
              />
              <button
                type="button"
                onClick={() => setShowPassword((s) => !s)}
                className="absolute right-3.5 top-1/2 -translate-y-1/2 text-slate-400 hover:text-[#405189] transition cursor-pointer"
                title={showPassword ? 'Hide password' : 'Show password'}
                aria-label={showPassword ? 'Hide password' : 'Show password'}
              >
                <i className={`fa-solid ${showPassword ? 'fa-eye-slash' : 'fa-eye'} text-sm`}></i>
              </button>
            </div>
            <div className="flex items-center justify-between text-sm">
              <label className="flex items-center gap-2 text-slate-500 select-none">
                <input type="checkbox" className="accent-[#405189]" /> Remember me
              </label>
              <a href="/forgot-password" className="text-[#405189] font-medium hover:underline">
                Forgot password?
              </a>
            </div>
            <button type="submit" disabled={loading}
              className="w-full bg-[#405189] text-white py-2.5 rounded-none text-sm font-medium hover:bg-[#364574] transition disabled:opacity-50">
              {loading ? 'Signing in...' : 'Log In'}
            </button>

            <div className="pt-1 text-center text-sm text-slate-500">
              New here?{' '}
              <a href="/register" className="text-[#405189] font-semibold hover:underline">Create an account</a>
            </div>
            <div className="text-center text-xs text-slate-400">
              <a href="/careers/jobs" className="hover:underline">Browse open jobs &rarr;</a>
            </div>
          </form>
        ) : (
          <form onSubmit={handleVerifyMfa} className="space-y-5">
            <input
              type="text" maxLength={6} placeholder="0  0  0  0  0  0" value={mfaCode} required
              onChange={(e) => setMfaCode(e.target.value.replace(/\D/g, ''))}
              className="w-full border border-vz-border rounded-none px-3 py-3 text-center tracking-[0.4em] text-xl font-semibold focus:ring-2 focus:ring-[#405189]/25 focus:border-[#405189] focus:outline-none"
            />
            <button type="submit" disabled={loading}
              className="w-full bg-[#405189] text-white py-2.5 rounded-none text-sm font-medium hover:bg-[#364574] transition disabled:opacity-50">
              {loading ? 'Verifying...' : 'Verify'}
            </button>
            {mfaMethod === 'email' && (
              <div className="text-center text-sm">
                {cooldown > 0 ? (
                  <span className="text-slate-400">Resend code in {cooldown}s</span>
                ) : (
                  <button type="button" onClick={handleResend} className="text-[#405189] font-medium hover:underline">
                    Resend code
                  </button>
                )}
              </div>
            )}
          </form>
        )}
        </div>
      </div>

      <DemoCredentialsModal
        isOpen={showDemoModal}
        onClose={() => setShowDemoModal(false)}
        onUse={(demoEmail, demoPassword) => {
          setEmail(demoEmail);
          setPassword(demoPassword);
        }}
      />
    </div>
  );
}
