'use client'

import { Button } from '@/components/actions/Button'
import { FormField } from '@/components/forms/FormField'
import { AuthShell } from '@/components/auth/AuthShell'
import { API_BASE } from '@/lib/api'
import { localizedPath, type Locale } from '@/lib/localization/config'
import { useSearchParams } from 'next/navigation'
import { Suspense, useState } from 'react'

interface Dict {
  title: string
  subtitle: string
  newPassword: string
  confirmPassword: string
  submit: string
  submitting: string
  backToLogin: string
  successTitle: string
  successBody: string
  signIn: string
  errorMismatch: string
  errorShort: string
  errorInvalidToken: string
  errorGeneric: string
  noToken: string
  requestNew: string
}

const dicts: Record<string, Dict> = {
  en: {
    title: 'Set new password',
    subtitle: 'Choose a strong password for your 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: 'طلب رابط جديد',
  },
}

function ResetPasswordContent({ locale }: { locale: Locale }) {
  const dict = (dicts[locale] ?? dicts.en) as Dict
  const searchParams = useSearchParams()
  const token = searchParams.get('token')

  const [password, setPassword] = useState('')
  const [confirm, setConfirm] = useState('')
  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 {
      // Try employee endpoint first, fall back to admin
      let res = await fetch(`${API_BASE}/auth/employee/reset-password`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ token, password }),
      })

      if (!res.ok) {
        res = await fetch(`${API_BASE}/admin/auth/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)
    }
  }

  const signInHref = localizedPath('sign-in', locale)
  const forgotHref = localizedPath('forgot-password', locale)

  if (!token) {
    return (
      <AuthShell locale={locale} title={dict.title}>
        <p style={{ textAlign: 'center', fontSize: '0.875rem', color: 'var(--color-text-secondary)' }}>
          {dict.noToken}
        </p>
        <div style={{ marginTop: '1rem', textAlign: 'center' }}>
          <a href={forgotHref}>
            <Button intent="primary">{dict.requestNew}</Button>
          </a>
        </div>
      </AuthShell>
    )
  }

  if (done) {
    return (
      <AuthShell locale={locale} title={dict.title}>
        <div style={{ textAlign: 'center' }}>
          <div
            style={{
              margin: '0 auto 1rem',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              width: '3.5rem',
              height: '3.5rem',
              borderRadius: '50%',
              background: 'var(--color-success-bg, #ecfdf5)',
            }}
          >
            <svg
              style={{ width: '1.75rem', height: '1.75rem', color: 'var(--color-success-text, #059669)' }}
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth={2}
            >
              <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
            </svg>
          </div>
          <h2 style={{ fontSize: '1.25rem', fontWeight: 700, color: 'var(--color-heading)' }}>
            {dict.successTitle}
          </h2>
          <p style={{ marginTop: '0.5rem', fontSize: '0.875rem', color: 'var(--color-text-secondary)' }}>
            {dict.successBody}
          </p>
          <div style={{ marginTop: '1rem' }}>
            <a href={signInHref}>
              <Button intent="primary" fullWidth>{dict.signIn}</Button>
            </a>
          </div>
        </div>
      </AuthShell>
    )
  }

  return (
    <AuthShell locale={locale} title={dict.title} subtitle={dict.subtitle}>
      <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '1.25rem' }}>
        {error ? (
          <div
            style={{
              borderRadius: '1.5rem',
              border: '1px solid var(--color-error-border, #fecaca)',
              background: 'var(--color-error-bg, #fef2f2)',
              padding: '0.75rem 1rem',
              fontSize: '0.875rem',
              color: 'var(--color-error-text, #b91c1c)',
            }}
          >
            {error}
          </div>
        ) : null}

        <FormField id="reset-password" label={dict.newPassword} required>
            <input
              id="reset-password"
              type="password"
              required
              minLength={8}
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="••••••••"
              autoComplete="new-password"
              style={{
                width: '100%',
                minHeight: '2.875rem',
                padding: 'var(--space-3) var(--space-4)',
                border: '1px solid var(--border-strong)',
                borderRadius: 'var(--radius-sm)',
                background: 'var(--surface-primary)',
                color: 'var(--text-primary)',
                fontSize: '0.875rem',
              }}
            />
          </FormField>

          <FormField id="reset-confirm" label={dict.confirmPassword} required>
            <input
              id="reset-confirm"
              type="password"
              required
              minLength={8}
              value={confirm}
              onChange={(e) => setConfirm(e.target.value)}
              placeholder="••••••••"
              autoComplete="new-password"
              style={{
                width: '100%',
                minHeight: '2.875rem',
                padding: 'var(--space-3) var(--space-4)',
                border: '1px solid var(--border-strong)',
                borderRadius: 'var(--radius-sm)',
                background: 'var(--surface-primary)',
                color: 'var(--text-primary)',
                fontSize: '0.875rem',
              }}
            />
          </FormField>

        <Button type="submit" intent="primary" fullWidth loading={loading} disabled={loading}>
          {loading ? dict.submitting : dict.submit}
        </Button>
      </form>

      <div
        style={{
          marginTop: '1.5rem',
          borderTop: '1px solid var(--color-border)',
          paddingTop: '1.5rem',
          textAlign: 'center',
          fontSize: '0.875rem',
        }}
      >
        <a
          href={signInHref}
          style={{
            fontWeight: 600,
            color: 'var(--color-heading)',
            textDecoration: 'underline',
            textUnderlineOffset: '4px',
          }}
        >
          {dict.backToLogin}
        </a>
      </div>
    </AuthShell>
  )
}

export function ResetPasswordForm({ locale }: { locale: Locale }) {
  return (
    <Suspense>
      <ResetPasswordContent locale={locale} />
    </Suspense>
  )
}
