'use client'

import Link from 'next/link'
import { Suspense, useState } from 'react'
import { useSearchParams } from 'next/navigation'
import { useDashboardI18n } from '@/components/I18nProvider'
import PublicShell from '@/components/layout/PublicShell'
import { resolveApiBase } from '@/lib/api'

export default function ResetPasswordPageClient({ embedded = false }: { embedded?: boolean }) {
  return (
    <Suspense>
      <ResetPasswordContent embedded={embedded} />
    </Suspense>
  )
}

function ResetPasswordContent({ embedded = false }: { embedded?: boolean }) {
  const { language } = useDashboardI18n()
  const dict = {
    en: {
      title: 'Set new password',
      subtitle: 'Choose a strong password for your workspace account.',
      newPassword: 'New password',
      confirmPassword: 'Confirm password',
      submit: 'Reset password',
      submitting: 'Resetting…',
      backToLogin: 'Back to sign in',
      successTitle: 'Password updated',
      successBody: 'Your password has been reset. You can now sign in with your new password.',
      signIn: 'Sign in',
      errorMismatch: 'Passwords do not match.',
      errorShort: 'Password must be at least 8 characters.',
      errorInvalidToken: 'This reset link is invalid or has expired. Please request a new one.',
      errorGeneric: 'Something went wrong. Please try again.',
      noToken: 'No reset token found. Please request a new password reset.',
      requestNew: 'Request new reset link',
    },
    fr: {
      title: 'Nouveau mot de passe',
      subtitle: "Choisissez un mot de passe fort pour votre compte.",
      newPassword: 'Nouveau mot de passe',
      confirmPassword: 'Confirmer le mot de passe',
      submit: 'Réinitialiser',
      submitting: 'Traitement…',
      backToLogin: 'Retour à la connexion',
      successTitle: 'Mot de passe mis à jour',
      successBody: 'Votre mot de passe a été réinitialisé. Vous pouvez maintenant vous connecter.',
      signIn: 'Se connecter',
      errorMismatch: 'Les mots de passe ne correspondent pas.',
      errorShort: 'Le mot de passe doit contenir au moins 8 caractères.',
      errorInvalidToken: 'Ce lien est invalide ou a expiré. Veuillez en demander un nouveau.',
      errorGeneric: 'Une erreur est survenue. Veuillez réessayer.',
      noToken: 'Aucun jeton de réinitialisation trouvé. Veuillez demander un nouveau lien.',
      requestNew: 'Demander un nouveau lien',
    },
    ar: {
      title: 'تعيين كلمة مرور جديدة',
      subtitle: 'اختر كلمة مرور قوية لحساب مساحة العمل.',
      newPassword: 'كلمة المرور الجديدة',
      confirmPassword: 'تأكيد كلمة المرور',
      submit: 'إعادة تعيين',
      submitting: 'جارٍ المعالجة…',
      backToLogin: 'العودة إلى تسجيل الدخول',
      successTitle: 'تم تحديث كلمة المرور',
      successBody: 'تم إعادة تعيين كلمة المرور. يمكنك الآن تسجيل الدخول.',
      signIn: 'تسجيل الدخول',
      errorMismatch: 'كلمتا المرور غير متطابقتين.',
      errorShort: 'يجب أن تتكون كلمة المرور من 8 أحرف على الأقل.',
      errorInvalidToken: 'رابط إعادة التعيين غير صالح أو منتهي الصلاحية.',
      errorGeneric: 'حدث خطأ ما. يرجى المحاولة مرة أخرى.',
      noToken: 'لم يتم العثور على رمز إعادة التعيين. يرجى طلب رابط جديد.',
      requestNew: 'طلب رابط جديد',
    },
  }[language]

  const searchParams = useSearchParams()
  const token = searchParams.get('token')

  const [password, setPassword] = useState('')
  const [confirm, setConfirm] = useState('')
  const [showPassword, setShowPassword] = useState(false)
  const [showConfirm, setShowConfirm] = useState(false)
  const [loading, setLoading] = useState(false)
  const [done, setDone] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    if (password.length < 8) { setError(dict.errorShort); return }
    if (password !== confirm) { setError(dict.errorMismatch); return }
    setLoading(true)
    setError(null)
    try {
      const res = await fetch(`${resolveApiBase()}/auth/employee/reset-password`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ token, password }),
      })
      const json = await res.json()
      if (!res.ok) {
        if (json?.error === 'invalid_token') throw new Error(dict.errorInvalidToken)
        throw new Error(dict.errorGeneric)
      }
      setDone(true)
    } catch (err: any) {
      setError(err.message ?? dict.errorGeneric)
    } finally {
      setLoading(false)
    }
  }

  if (!token) {
    return (
      <ResetShell embedded={embedded} title={dict.title}>
        <p className="text-center text-sm text-stone-500 dark:text-stone-400">{dict.noToken}</p>
        <div className="mt-4 text-center">
          <Link href="/forgot-password" className="btn-primary inline-flex">{dict.requestNew}</Link>
        </div>
      </ResetShell>
    )
  }

  if (done) {
    return (
      <ResetShell embedded={embedded} title={dict.title}>
        <div className="space-y-4 text-center">
          <div className="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-emerald-100 dark:bg-emerald-950/50">
            <svg className="h-7 w-7 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>
          <h2 className="text-xl font-bold text-stone-900 dark:text-stone-100">{dict.successTitle}</h2>
          <p className="text-sm text-stone-500 dark:text-stone-400">{dict.successBody}</p>
          <Link href="/sign-in" className="btn-primary inline-flex justify-center">{dict.signIn}</Link>
        </div>
      </ResetShell>
    )
  }

  return (
    <ResetShell embedded={embedded} title={dict.title} subtitle={dict.subtitle}>
      <form onSubmit={handleSubmit} className="space-y-5">
        {error && (
          <div className="rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700 dark:border-rose-800 dark:bg-rose-950/40 dark:text-rose-400">{error}</div>
        )}
        <div>
          <label className="mb-1.5 block text-sm font-medium text-stone-700 dark:text-stone-300">{dict.newPassword}</label>
          <div className="relative">
          <input
            type={showPassword ? 'text' : 'password'}
            required
            minLength={8}
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            placeholder="••••••••"
            className="input-field pr-10"
          />
          <button
            type="button"
            onClick={() => setShowPassword((v) => !v)}
            className="absolute inset-y-0 right-3 flex items-center text-stone-400 hover:text-stone-700 dark:text-stone-500 dark:hover:text-stone-200"
            tabIndex={-1}
          >
            {showPassword ? (
              <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
              </svg>
            ) : (
              <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                <path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
              </svg>
            )}
          </button>
          </div>
        </div>
        <div>
          <label className="mb-1.5 block text-sm font-medium text-stone-700 dark:text-stone-300">{dict.confirmPassword}</label>
          <div className="relative">
          <input
            type={showConfirm ? 'text' : 'password'}
            required
            minLength={8}
            value={confirm}
            onChange={(e) => setConfirm(e.target.value)}
            placeholder="••••••••"
            className="input-field pr-10"
          />
          <button
            type="button"
            onClick={() => setShowConfirm((v) => !v)}
            className="absolute inset-y-0 right-3 flex items-center text-stone-400 hover:text-stone-700 dark:text-stone-500 dark:hover:text-stone-200"
            tabIndex={-1}
          >
            {showConfirm ? (
              <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
              </svg>
            ) : (
              <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                <path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
              </svg>
            )}
          </button>
          </div>
        </div>
        <button
          type="submit"
          disabled={loading}
          className="btn-primary w-full justify-center disabled:cursor-not-allowed disabled:opacity-60"
        >
          {loading ? dict.submitting : dict.submit}
        </button>
      </form>

      <div className="mt-6 border-t border-stone-200 pt-6 text-center text-sm text-stone-500 dark:border-blue-900 dark:text-stone-400">
        <Link href="/sign-in" className="font-semibold text-stone-900 underline decoration-stone-300 underline-offset-4 dark:text-stone-100 dark:decoration-stone-700">
          {dict.backToLogin}
        </Link>
      </div>
    </ResetShell>
  )
}

function ResetShell({
  embedded = false,
  title,
  subtitle,
  children,
}: {
  embedded?: boolean
  title: string
  subtitle?: string
  children: React.ReactNode
}) {
  return (
    <PublicShell embedded={embedded}>
      <main className="flex min-h-[calc(100vh-80px)] items-center justify-center px-4 py-12">
        <div className="w-full max-w-md">
          <div className="mb-8 text-center">
            <h1 className="mt-3 text-3xl font-black tracking-tight text-stone-900 dark:text-stone-100">{title}</h1>
            {subtitle && <p className="mt-2 text-sm text-stone-500 dark:text-stone-400">{subtitle}</p>}
          </div>
          <section className="rounded-[2rem] border border-stone-200 bg-white p-8 shadow-sm transition-colors dark:border-blue-900 dark:bg-blue-950">
            {children}
          </section>
        </div>
      </main>
    </PublicShell>
  )
}
