'use client';

import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { Suspense, useState, useEffect } from 'react';
import Cookies from 'js-cookie';
import { toast } from 'react-toastify';
import {
  CAREERS_API, applyToJob, fetchPublicJob,
  captureTracking, getTrackingToken, getLegacySource,
} from '@/lib/careers';

function RegisterInner() {
  const router = useRouter();
  const params = useSearchParams();
  const jobId = params.get('job');
  // Opaque encrypted tracking token carried over from the careers link; the
  // platform is resolved server-side. `source` is the legacy plain fallback.
  const rawToken = params.get('t');
  const rawSource = params.get('source') || params.get('utm_source');
  const [jobTitle, setJobTitle] = useState<string | null>(null);
  const loginHref = jobId ? `/login?job=${jobId}` : '/login';

  // Store the tracking token so it survives a detour to "log in instead"
  // (someone who landed straight on this URL never passed the careers page).
  useEffect(() => {
    captureTracking(rawToken, rawSource);
  }, [rawToken, rawSource]);

  useEffect(() => {
    if (jobId) fetchPublicJob(jobId).then((j) => setJobTitle(j.title)).catch(() => setJobTitle(null));
  }, [jobId]);

  const [form, setForm] = useState({ first_name: '', last_name: '', email: '', phone: '', password: '' });
  const [resume, setResume] = useState<File | null>(null);
  const [otp, setOtp] = useState('');
  const [showPw, setShowPw] = useState(false);
  const [otpSent, setOtpSent] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');
  const [otpError, setOtpError] = useState('');
  const [alreadyRegistered, setAlreadyRegistered] = useState(false);

  const set = (k: string, v: string) => setForm((f) => ({ ...f, [k]: v }));

  const validate = () => {
    if (!form.first_name || !form.last_name || !form.email || !form.phone) return 'Please fill in all fields.';
    if (!/^\S+@\S+\.\S+$/.test(form.email)) return 'Enter a valid email address.';
    if (form.phone.length !== 10) return 'Phone number must be exactly 10 digits.';
    if (form.password.length < 8) return 'Password must be at least 8 characters.';
    if (!resume) return 'Please upload your résumé.';
    return '';
  };

  const sendOtp = async () => {
    setError(''); setOtpError(''); setAlreadyRegistered(false);
    const v = validate();
    if (v) { setError(v); return; }
    setBusy(true);
    try {
      const res = await fetch(`${CAREERS_API}/auth/register/send-otp/`, {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: form.email, mobile: form.phone }),
      });
      const json = await res.json().catch(() => ({}));
      if (res.status === 409) { setAlreadyRegistered(true); setError(json?.message || 'This email is already registered.'); return; }
      if (!res.ok) { setError(json?.message || 'Could not send verification code.'); return; }
      setOtpSent(true);
      toast.success(json?.message || 'Verification code sent to your email & mobile.');
    } catch { setError('Network error — please try again.'); }
    finally { setBusy(false); }
  };

  const createAccount = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(''); setOtpError('');
    if (otp.trim().length < 6) { setOtpError('Enter the 6-digit code sent to your email & mobile.'); return; }
    setBusy(true);
    try {
      const trackingToken = getTrackingToken(rawToken);
      const finalSource = getLegacySource(rawSource) || 'direct';

      const fd = new FormData();
      Object.entries(form).forEach(([k, v]) => fd.append(k, v));
      fd.append('otp', otp.trim());
      if (resume) fd.append('resume', resume);
      if (jobId) fd.append('job_id', jobId);
      // The backend prefers the token and falls back to `source` for old links.
      if (trackingToken) fd.append('t', trackingToken);
      fd.append('source', finalSource);

      const res = await fetch(`${CAREERS_API}/auth/register/`, { method: 'POST', body: fd });
      const json = await res.json().catch(() => ({}));
      if (res.status === 409) { setAlreadyRegistered(true); setError(json?.message || 'This email is already registered.'); setBusy(false); return; }
      if (!res.ok) {
        const msg = json?.message || 'Registration failed.';
        // OTP-related errors belong next to the code field, not the top banner.
        if (/code|otp/i.test(msg)) { setOtpError(msg); toast.error(msg); }
        else setError(msg);
        setBusy(false);
        return;
      }

      Cookies.set('access_token', json.data.access, { expires: 1 });
      Cookies.set('refresh_token', json.data.refresh, { expires: 7 });
      // Hand the résumé-parsed values to the profile-completion modal (shown
      // after login) so it can pre-fill high-confidence fields. Only fields the
      // parser was confident about are present; the rest stay for manual entry.
      try {
        if (json.data?.parsed_data && typeof json.data.parsed_data === 'object') {
          sessionStorage.setItem('resume_parsed_profile', JSON.stringify(json.data.parsed_data));
        }
      } catch { /* sessionStorage unavailable — modal simply won't pre-fill */ }
      if (jobId && !json.data.applied_to_job) await applyToJob(jobId, finalSource, trackingToken);
      toast.success(jobId ? 'Registered & applied! Welcome aboard.' : 'Welcome! Your profile is ready.');
      router.push('/dashboard');
    } catch { setError('Network error — please try again.'); setBusy(false); }
  };

  return (
    <div className="min-h-screen grid lg:grid-cols-2">
      {/* Brand panel */}
      <div className="hidden lg:flex flex-col justify-between p-12 text-white" style={{ background: 'linear-gradient(135deg,#405189 0%,#23b7e5 100%)' }}>
        <Link href="/" className="flex items-center gap-2">
          <span className="w-9 h-9 flex items-center justify-center bg-white text-[#405189] font-black">TA</span>
          <span className="font-black text-xl">Indovision Careers</span>
        </Link>
        <div>
          <h2 className="text-3xl font-black leading-tight">Create your candidate profile</h2>
          <p className="mt-3 text-white/85 max-w-sm">Verify your email, upload your résumé once, and apply to any open role in a single click.</p>
        </div>
        <p className="text-xs text-white/60">© {new Date().getFullYear()} Indovision Services</p>
      </div>

      {/* Form */}
      <div className="flex items-center justify-center p-6 sm:p-12 bg-slate-50">
        <form onSubmit={createAccount} className="w-full max-w-md">
          <h1 className="text-2xl font-black text-slate-800">Register</h1>
          {jobId ? (
            <p className="text-sm text-slate-500 mt-1">
              Applying for{' '}
              <span className="font-bold text-[#405189]">{jobTitle || `Job #${jobId}`}</span>. Complete your profile to apply.
            </p>
          ) : (
            <p className="text-sm text-slate-500 mt-1">Join to browse and apply for jobs.</p>
          )}

          {error && (
            <div className="mt-4 p-3 bg-rose-50 border border-rose-200 text-rose-700 text-sm">
              {error}
              {alreadyRegistered && (
                <> <Link href={loginHref} className="font-bold underline">Log in here</Link>.</>
              )}
            </div>
          )}

          <fieldset disabled={otpSent} className={otpSent ? 'opacity-60' : ''}>
            <div className="grid grid-cols-2 gap-3 mt-5">
              <Field label="First name" value={form.first_name} onChange={(v) => set('first_name', v)} />
              <Field label="Last name" value={form.last_name} onChange={(v) => set('last_name', v)} />
            </div>
            <Field label="Email" type="email" value={form.email} onChange={(v) => set('email', v)} className="mt-3" />
            <Field
              label="Phone"
              value={form.phone}
              onChange={(v) => set('phone', v.replace(/\D/g, '').slice(0, 10))}
              maxLength={10}
              inputMode="numeric"
              className="mt-3"
            />

            <div className="mt-3">
              <label className="block text-xs font-bold uppercase tracking-wide text-slate-500 mb-1">
                Password <span className="text-rose-500">*</span>
              </label>
              <div className="flex border border-slate-300 bg-white">
                <input
                  type={showPw ? 'text' : 'password'}
                  value={form.password}
                  onChange={(e) => set('password', e.target.value)}
                  minLength={8}
                  className="flex-1 px-3 py-2.5 text-sm focus:outline-none"
                />
                <button type="button" onClick={() => setShowPw((s) => !s)} className="px-3 text-slate-400 hover:text-slate-600">
                  <i className={`fa-solid ${showPw ? 'fa-eye-slash' : 'fa-eye'}`} />
                </button>
              </div>
              <p className="text-[11px] text-slate-400 mt-1">At least 8 characters.</p>
            </div>

            <div className="mt-3">
              <label className="block text-xs font-bold uppercase tracking-wide text-slate-500 mb-1">
                Résumé (PDF/DOCX) <span className="text-rose-500">*</span>
              </label>
              <input
                type="file"
                accept=".pdf,.doc,.docx"
                required
                onChange={(e) => setResume(e.target.files?.[0] ?? null)}
                className="block w-full text-sm text-slate-600 file:mr-3 file:py-2 file:px-4 file:border-0 file:bg-[#405189] file:text-white file:font-bold file:text-xs hover:file:bg-[#334267]"
              />
            </div>
          </fieldset>

          {!otpSent ? (
            <button type="button" onClick={sendOtp} disabled={busy} className="mt-6 w-full py-3 bg-[#405189] text-white font-bold text-sm hover:bg-[#334267] transition disabled:opacity-50">
              {busy ? 'Sending code…' : 'Send verification code'}
            </button>
          ) : (
            <>
              <div className="mt-5 p-4 border border-[#405189]/20 bg-[#405189]/5">
                <label className="block text-xs font-bold uppercase tracking-wide text-slate-600 mb-1">
                  Enter the code sent to {form.email}
                </label>
                <input
                  value={otp}
                  onChange={(e) => { setOtp(e.target.value.replace(/\D/g, '').slice(0, 6)); if (otpError) setOtpError(''); }}
                  inputMode="numeric"
                  placeholder="6-digit code"
                  className={`w-full px-3 py-2.5 text-sm border bg-white focus:outline-none tracking-[0.4em] font-bold ${otpError ? 'border-rose-400 focus:border-rose-500' : 'border-slate-300 focus:border-[#405189]'}`}
                />
                {otpError && (
                  <p className="mt-1.5 text-xs font-semibold text-rose-600 flex items-center gap-1">
                    <i className="fa-solid fa-circle-exclamation" /> {otpError}
                  </p>
                )}
                <div className="flex items-center justify-between mt-2">
                  <button type="button" onClick={() => { setOtpSent(false); setOtp(''); }} className="text-[11px] text-slate-500 hover:text-slate-700">← Edit details</button>
                  <button type="button" onClick={sendOtp} disabled={busy} className="text-[11px] font-bold text-[#405189] hover:underline disabled:opacity-50">Resend code</button>
                </div>
              </div>
              <button type="submit" disabled={busy} className="mt-4 w-full py-3 bg-[#405189] text-white font-bold text-sm hover:bg-[#334267] transition disabled:opacity-50">
                {busy ? 'Creating account…' : jobId ? 'Verify & apply' : 'Verify & create account'}
              </button>
            </>
          )}

          <p className="text-sm text-slate-500 mt-4 text-center">
            Already have an account? <Link href={loginHref} className="font-bold text-[#405189] hover:underline">Log in</Link>
          </p>
        </form>
      </div>
    </div>
  );
}

function Field({ label, value, onChange, type = 'text', className = '', required = true, maxLength, inputMode }: {
  label: string; value: string; onChange: (v: string) => void; type?: string; className?: string; required?: boolean; maxLength?: number; inputMode?: string;
}) {
  return (
    <div className={className}>
      <label className="block text-xs font-bold uppercase tracking-wide text-slate-500 mb-1">
        {label}{required && <span className="text-rose-500 ml-0.5">*</span>}
      </label>
      <input
        type={type}
        value={value}
        required={required}
        maxLength={maxLength}
        inputMode={inputMode as any}
        onChange={(e) => onChange(e.target.value)}
        className="w-full px-3 py-2.5 text-sm border border-slate-300 bg-white focus:outline-none focus:border-[#405189]"
      />
    </div>
  );
}

export default function RegisterPage() {
  return (
    <Suspense fallback={<div className="min-h-screen bg-slate-50" />}>
      <RegisterInner />
    </Suspense>
  );
}
