'use client'

import { useEffect, useState } from 'react'
import { useSearchParams } from 'next/navigation'
import Image from 'next/image'
import PublicShell from '@/components/layout/PublicShell'
import { useDashboardI18n } from '@/components/I18nProvider'

export default function VerifyEmailPage() {
  const { language } = useDashboardI18n()
  const searchParams = useSearchParams()
  const token = searchParams.get('token')
  const [status, setStatus] = useState<'loading' | 'success' | 'error'>('loading')
  const [errorDetail, setErrorDetail] = useState<string | null>(null)

  const dict = {
    en: {
      verifying: 'Verifying your email…',
      success: 'Email verified! You can now sign in.',
      error: 'This verification link is invalid or has expired.',
      signIn: 'Go to sign in',
    },
    fr: {
      verifying: 'Vérification de votre email…',
      success: 'Email vérifié ! Vous pouvez maintenant vous connecter.',
      error: 'Ce lien de vérification est invalide ou a expiré.',
      signIn: 'Aller à la connexion',
    },
    ar: {
      verifying: 'جارٍ التحقق من بريدك الإلكتروني…',
      success: 'تم التحقق من البريد الإلكتروني! يمكنك الآن تسجيل الدخول.',
      error: 'رابط التحقق هذا غير صالح أو منتهي الصلاحية.',
      signIn: 'الذهاب إلى تسجيل الدخول',
    },
  }[language]

  useEffect(() => {
    if (!token) {
      setStatus('error')
      return
    }

    let cancelled = false

    async function verify() {
      try {
        const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000/api/v1'
        const url = `${API_BASE}/auth/employee/verify-email`
        const res = await fetch(url, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ token }),
        })

        if (cancelled) return

        if (res.ok) {
          setStatus('success')
        } else {
          let detail = `API returned ${res.status}`
          try {
            const body = await res.json()
            if (body?.error) detail += `: ${body.error}`
            if (body?.message) detail += ` — ${body.message}`
          } catch {
            // response wasn't JSON
          }
          setErrorDetail(detail)
          setStatus('error')
        }
      } catch (err: any) {
        if (!cancelled) {
          setErrorDetail(err?.message ?? 'Network error — could not reach the API')
          setStatus('error')
        }
      }
    }

    verify()

    return () => {
      cancelled = true
    }
  }, [token])

  return (
    <PublicShell>
      <main className="flex flex-1 items-center justify-center px-4 py-16">
        <div className="w-full max-w-md text-center">
          <div className="flex justify-center mb-6">
            <Image
              src="/dashboard/rentaldrivego.png"
              alt="RentalDriveGo"
              width={80}
              height={80}
              priority
              unoptimized
              className="h-20 w-20 rounded-[1.5rem] border border-stone-200/80 bg-white/85 p-1.5 shadow-sm dark:border-blue-800 dark:bg-blue-950/80"
            />
          </div>
          <div className="rounded-[2rem] border border-stone-200/80 bg-white/82 p-8 shadow-[0_30px_80px_rgba(28,25,23,0.08)] backdrop-blur dark:border-blue-900 dark:bg-blue-950/78">
            {status === 'loading' && (
              <>
                <div className="mx-auto mb-4 h-6 w-6 animate-spin rounded-full border-2 border-orange-500 border-t-transparent" />
                <p className="text-sm text-stone-600 dark:text-stone-300">{dict.verifying}</p>
              </>
            )}
            {status === 'success' && (
              <>
                <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-emerald-100 dark:bg-emerald-900/40">
                  <svg className="h-6 w-6 text-emerald-600 dark:text-emerald-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
                  </svg>
                </div>
                <h1 className="text-xl font-black text-blue-950 dark:text-stone-50">{dict.success}</h1>
                <a
                  href="/sign-in"
                  className="mt-6 inline-flex justify-center rounded-full bg-orange-600 px-6 py-3 text-sm font-semibold text-white transition hover:bg-orange-700 dark:bg-orange-500 dark:hover:bg-orange-400"
                >
                  {dict.signIn}
                </a>
              </>
            )}
            {status === 'error' && (
              <>
                <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-red-100 dark:bg-red-900/40">
                  <svg className="h-6 w-6 text-red-600 dark:text-red-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                    <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                  </svg>
                </div>
                <h1 className="text-xl font-black text-blue-950 dark:text-stone-50">{dict.error}</h1>
                {errorDetail && (
                  <p className="mt-2 text-xs text-stone-500 dark:text-stone-400 font-mono break-all">{errorDetail}</p>
                )}
                <a
                  href="/sign-in"
                  className="mt-6 inline-flex justify-center rounded-full bg-orange-600 px-6 py-3 text-sm font-semibold text-white transition hover:bg-orange-700 dark:bg-orange-500 dark:hover:bg-orange-400"
                >
                  {dict.signIn}
                </a>
              </>
            )}
          </div>
        </div>
      </main>
    </PublicShell>
  )
}
