'use client'

import { Button } from '@/components/actions/Button'
import { TextInput } from '@/components/forms/TextInput'
import { FormField } from '@/components/forms/FormField'
import { AuthShell } from '@/components/auth/AuthShell'
import { API_BASE } from '@/lib/api'
import { localizedModePath, modeFromPathname, type Locale } from '@/lib/localization/config'
import { usePathname } from 'next/navigation'
import { useState } from 'react'
import styles from './AuthForms.module.css'

interface Dict {
  title: string
  subtitle: string
  email: string
  emailPlaceholder: string
  submit: string
  submitting: string
  backToLogin: string
  successTitle: string
  successBody: string
  error: string
}

const dicts: Record<string, Dict> = {
  en: {
    title: 'Forgot your password?',
    subtitle: "Enter your work email and we'll send you a reset link.",
    email: 'Email',
    emailPlaceholder: 'owner@company.com',
    submit: 'Send reset link',
    submitting: 'Sending…',
    backToLogin: 'Back to sign in',
    successTitle: 'Check your email',
    successBody: 'If that email is registered, a reset link has been sent. It expires in 60 minutes.',
    error: 'Something went wrong. Please try again.',
  },
  fr: {
    title: 'Mot de passe oublié ?',
    subtitle: "Entrez votre email professionnel et nous vous enverrons un lien de réinitialisation.",
    email: 'Email',
    emailPlaceholder: 'owner@company.com',
    submit: 'Envoyer le lien',
    submitting: 'Envoi…',
    backToLogin: 'Retour à la connexion',
    successTitle: 'Vérifiez votre email',
    successBody: "Si cet email est enregistré, un lien de réinitialisation a été envoyé. Il expire dans 60 minutes.",
    error: 'Une erreur est survenue. Veuillez réessayer.',
  },
  ar: {
    title: 'نسيت كلمة المرور؟',
    subtitle: 'أدخل بريدك الإلكتروني وسنرسل لك رابط إعادة التعيين.',
    email: 'البريد الإلكتروني',
    emailPlaceholder: 'owner@company.com',
    submit: 'إرسال رابط إعادة التعيين',
    submitting: 'جارٍ الإرسال…',
    backToLogin: 'العودة إلى تسجيل الدخول',
    successTitle: 'تحقق من بريدك الإلكتروني',
    successBody: 'إذا كان البريد الإلكتروني مسجلاً، فقد تم إرسال رابط إعادة التعيين. تنتهي صلاحيته خلال 60 دقيقة.',
    error: 'حدث خطأ ما. يرجى المحاولة مرة أخرى.',
  },
}

export function ForgotPasswordForm({ locale }: { locale: Locale }) {
  const dict = (dicts[locale] ?? dicts.en) as Dict
  const mode = modeFromPathname(usePathname())
  const [email, setEmail] = useState('')
  const [loading, setLoading] = useState(false)
  const [sent, setSent] = useState(false)
  const [error, setError] = useState<string | null>(null)

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setLoading(true)
    setError(null)
    try {
      const [empRes, adminRes] = await Promise.all([
        fetch(`${API_BASE}/auth/employee/forgot-password`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ email }),
        }),
        fetch(`${API_BASE}/admin/auth/forgot-password`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ email }),
        }),
      ])
      if (!empRes.ok && !adminRes.ok) throw new Error()
      setSent(true)
    } catch {
      setError(dict.error)
    } finally {
      setLoading(false)
    }
  }

  const signInHref = localizedModePath('sign-in', locale, mode)

  return (
    <AuthShell locale={locale} title={dict.title} subtitle={dict.subtitle}>
      {sent ? (
        <div className={styles.center}>
          <div className={styles.successIcon}>
            <svg
              className={styles.successIconSvg}
              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={styles.statusTitle}>
            {dict.successTitle}
          </h2>
          <p className={styles.statusBody}>
            {dict.successBody}
          </p>
        </div>
      ) : (
        <form onSubmit={handleSubmit} className={styles.formStack}>
          {error ? (
            <div className={styles.error}>
              {error}
            </div>
          ) : null}

          <FormField id="forgot-email" label={dict.email} required>
            <TextInput
              id="forgot-email"
              type="email"
              required
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder={dict.emailPlaceholder}
              autoComplete="email"
            />
          </FormField>

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

      <div className={styles.footer}>
        <a href={signInHref} className={styles.footerLink}>
          {dict.backToLogin}
        </a>
      </div>
    </AuthShell>
  )
}
