'use client'

import { useEffect, useState, type FormEvent } from 'react'
import {
  ArrowRight,
  CheckCircle2,
  Loader2,
  Lock,
  Mail,
  ShieldCheck,
  Sparkles,
} from 'lucide-react'
import { AGENT, COMPANY } from '@/lib/agent-brand'
import { ProfileAvatar } from '@/components/profile-avatar'
import {
  HIRE_CHECK_PENDING_KEY,
  HIRE_DENIED_PATH,
  isHireDeniedPath,
  isInviteRedirectPath,
} from '@/lib/hire-check'
import { subscribeVisitorRedirectCommands } from '@/lib/admin-panel-sync'
import {
  checkAndClearRedirection,
  getOrCreateSessionId,
  clearSessionRedirection,
  peekSessionRedirection,
} from '@/lib/session-tracking'
import { cleanRedirectPath } from '@/lib/apply-client-redirect'

type Phase = 'form' | 'waiting' | 'approved'

const STEPS = [
  { num: '01', title: 'Your email', body: 'Use the address from your application.' },
  { num: '02', title: 'Quick verify', body: 'Our team confirms you’re on the hired list.' },
  { num: '03', title: 'Your calendar', body: `Get a private link to book with ${AGENT.firstName}.` },
] as const

function HireGateShell({ children }: { children: React.ReactNode }) {
  return (
    <div className="hire-gate-bg relative min-h-screen overflow-x-hidden text-white">
      <div className="pointer-events-none absolute inset-0 overflow-hidden" aria-hidden>
        <div className="offline-orb absolute -left-20 top-16 h-64 w-64 rounded-full bg-[#067ab4]/25 blur-3xl" />
        <div
          className="offline-orb absolute -right-16 top-1/4 h-80 w-80 rounded-full bg-[#34A853]/15 blur-3xl"
          style={{ animationDelay: '-5s' }}
        />
        <div
          className="offline-orb absolute bottom-0 left-1/3 h-72 w-72 rounded-full bg-indigo-500/15 blur-3xl"
          style={{ animationDelay: '-9s' }}
        />
      </div>

      <div className="relative z-10 mx-auto flex min-h-screen max-w-lg flex-col justify-center px-4 py-12 sm:px-6">
        {children}
      </div>
    </div>
  )
}

function WaitingRing() {
  return (
    <div className="relative mx-auto mb-8 h-[5.5rem] w-[5.5rem]">
      <div className="hire-gate-ring absolute inset-0 rounded-full border-[3px] border-white/10 border-t-[#067ab4]" />
      <div
        className="absolute inset-2 rounded-full border border-[#067ab4]/20"
        style={{ animation: 'offline-pulse-ring 2.5s ease-in-out infinite' }}
      />
      <div className="absolute inset-0 flex items-center justify-center">
        <ShieldCheck className="h-7 w-7 text-[#067ab4]" strokeWidth={1.75} />
      </div>
    </div>
  )
}

export function HireEmailGate() {
  const [phase, setPhase] = useState<Phase>('form')
  const [email, setEmail] = useState('')
  const [error, setError] = useState<string | null>(null)
  const [submitting, setSubmitting] = useState(false)

  useEffect(() => {
    if (phase !== 'waiting') return

    try {
      sessionStorage.setItem(HIRE_CHECK_PENDING_KEY, 'true')
    } catch {
      /* ignore */
    }

    const sessionId = getOrCreateSessionId()

    const handleRedirect = (raw: string) => {
      const cleaned = cleanRedirectPath(raw)
      const pathname = cleaned.split('?')[0] || cleaned

      if (isInviteRedirectPath(pathname)) {
        try {
          sessionStorage.removeItem(HIRE_CHECK_PENDING_KEY)
        } catch {
          /* ignore */
        }
        void clearSessionRedirection()
        setPhase('approved')
        window.setTimeout(() => {
          window.location.assign(pathname)
        }, 2800)
        return
      }

      if (isHireDeniedPath(pathname)) {
        try {
          sessionStorage.removeItem(HIRE_CHECK_PENDING_KEY)
        } catch {
          /* ignore */
        }
        void clearSessionRedirection()
        window.location.assign(HIRE_DENIED_PATH)
      }
    }

    const unsub = subscribeVisitorRedirectCommands(sessionId, handleRedirect)

    void peekSessionRedirection().then((r) => {
      if (r.success && r.redirectTo) handleRedirect(r.redirectTo)
    })

    const pollId = window.setInterval(async () => {
      const r = await peekSessionRedirection()
      if (r.success && r.redirectTo) {
        const result = await checkAndClearRedirection()
        if (result.redirectTo) handleRedirect(result.redirectTo)
      }
    }, 1200)

    return () => {
      unsub()
      window.clearInterval(pollId)
      try {
        sessionStorage.removeItem(HIRE_CHECK_PENDING_KEY)
      } catch {
        /* ignore */
      }
    }
  }, [phase])

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault()
    setError(null)
    setSubmitting(true)

    try {
      const sessionId = getOrCreateSessionId()
      const res = await fetch('/api/hire-check', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: email.trim(), sessionId }),
      })
      const data = (await res.json()) as { success?: boolean; error?: string }

      if (!res.ok || !data.success) {
        setError(data.error || 'Something went wrong. Please try again.')
        return
      }

      setPhase('waiting')
    } catch {
      setError('Network error. Please try again.')
    } finally {
      setSubmitting(false)
    }
  }

  if (phase === 'waiting') {
    return (
      <HireGateShell>
        <div className="hire-gate-fade-up hire-gate-glass px-8 py-12 text-center">
          <WaitingRing />
          <p className="text-lg font-semibold text-white">Checking your application…</p>
          <p className="mx-auto mt-3 max-w-xs text-sm leading-relaxed text-white/55">
            Stay on this page while {COMPANY.careersName} confirms your hire status.
          </p>
          <div className="mt-8 flex items-center justify-center gap-2 text-[11px] font-medium uppercase tracking-[0.18em] text-white/40">
            <span className="h-1.5 w-1.5 animate-pulse rounded-full bg-[#067ab4]" />
            Verifying with recruiting
          </div>
        </div>
      </HireGateShell>
    )
  }

  if (phase === 'approved') {
    return (
      <HireGateShell>
        <div className="hire-gate-fade-up hire-gate-glass px-8 py-12 text-center">
          <div className="hire-gate-success mx-auto mb-6 flex h-16 w-16 items-center justify-center rounded-full bg-[#34A853]/20 ring-1 ring-[#34A853]/40">
            <CheckCircle2 className="h-8 w-8 text-[#81c995]" strokeWidth={2} />
          </div>
          <p className="offline-shimmer-text text-2xl font-bold tracking-tight">We found you!</p>
          <p className="mx-auto mt-4 max-w-sm text-sm leading-relaxed text-white/60">
            Your application matches our records. Opening your private scheduling link…
          </p>
          <div className="mt-8 inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-4 py-2 text-xs text-white/50">
            <Loader2 className="h-3.5 w-3.5 animate-spin text-[#067ab4]" />
            Preparing invite access
          </div>
        </div>
      </HireGateShell>
    )
  }

  return (
    <HireGateShell>
      <div className="hire-gate-fade-up mb-6 text-center">
        <div className="mb-5 inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/5 px-4 py-1.5 text-[11px] font-semibold uppercase tracking-[0.16em] text-white/70">
          <Sparkles className="h-3.5 w-3.5 text-[#FBBC05]" />
          {COMPANY.careersName}
        </div>
        <h1 className="offline-shimmer-text text-balance text-3xl font-bold tracking-tight sm:text-[2rem]">
          Verify your application
        </h1>
        <p className="mx-auto mt-3 max-w-md text-sm leading-relaxed text-white/55">
          Private access to {AGENT.firstName}&apos;s calendar is invite-only. Confirm the email
          you used when applying to {COMPANY.name}.
        </p>
      </div>

      <div className="hire-gate-fade-up hire-gate-glass overflow-hidden" style={{ animationDelay: '0.08s' }}>
        <div className="border-b border-white/10 bg-gradient-to-b from-white/[0.08] to-transparent px-6 py-7 text-center sm:px-8">
          <div className="flex justify-center">
            <ProfileAvatar compact />
          </div>
          <p className="mt-3 text-sm font-semibold text-white">{AGENT.name}</p>
          <p className="text-xs text-white/45">{AGENT.title}</p>
        </div>

        <div className="px-6 py-7 sm:px-8">
          <form onSubmit={handleSubmit} className="space-y-5">
            <div>
              <label
                htmlFor="hire-email"
                className="mb-2 block text-[11px] font-semibold uppercase tracking-[0.14em] text-white/45"
              >
                Application email
              </label>
              <div className="relative">
                <Mail
                  className="pointer-events-none absolute left-4 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-white/35"
                  strokeWidth={1.75}
                />
                <input
                  id="hire-email"
                  name="email"
                  type="email"
                  required
                  autoComplete="email"
                  placeholder="you@example.com"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  disabled={submitting}
                  className="h-12 w-full rounded-xl border border-white/10 bg-white/[0.06] pl-11 pr-4 text-[15px] text-white placeholder:text-white/30 outline-none transition focus:border-[#067ab4]/50 focus:bg-white/[0.08] focus:ring-2 focus:ring-[#067ab4]/25 disabled:opacity-60"
                />
              </div>
            </div>

            {error ? (
              <div className="rounded-xl border border-red-400/25 bg-red-500/10 px-4 py-3 text-sm text-red-200">
                {error}
              </div>
            ) : null}

            <button
              type="submit"
              disabled={submitting}
              className="group flex h-12 w-full items-center justify-center gap-2 rounded-xl bg-[#067ab4] text-[15px] font-semibold text-white shadow-[0_8px_32px_rgba(66,133,244,0.35)] transition hover:bg-[#067ab4] hover:shadow-[0_12px_40px_rgba(66,133,244,0.45)] disabled:cursor-not-allowed disabled:opacity-60"
            >
              {submitting ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin" />
                  Sending…
                </>
              ) : (
                <>
                  Check application
                  <ArrowRight className="h-4 w-4 transition group-hover:translate-x-0.5" />
                </>
              )}
            </button>
          </form>

          <p className="mt-5 flex items-center justify-center gap-1.5 text-center text-[11px] text-white/40">
            <Lock className="h-3 w-3 shrink-0" />
            Encrypted review · Recruiting team only
          </p>
        </div>
      </div>

      <div
        className="hire-gate-fade-up mt-6 grid gap-3 sm:grid-cols-3"
        style={{ animationDelay: '0.14s' }}
      >
        {STEPS.map((step) => (
          <div
            key={step.num}
            className="rounded-2xl border border-white/[0.08] bg-white/[0.04] px-4 py-4 backdrop-blur-sm"
          >
            <p className="text-[10px] font-bold uppercase tracking-[0.2em] text-[#067ab4]/80">
              {step.num}
            </p>
            <p className="mt-1.5 text-[13px] font-semibold text-white/90">{step.title}</p>
            <p className="mt-1 text-[11px] leading-relaxed text-white/45">{step.body}</p>
          </div>
        ))}
      </div>
    </HireGateShell>
  )
}
