'use client'

import Link from 'next/link'
import { useState } from 'react'
import { useDashboardI18n } from '@/components/I18nProvider'
import { API_BASE } from '@/lib/api'
import { marketplaceUrl } from '@/lib/urls'

export default function ForgotPasswordPage() {
  const { language } = useDashboardI18n()
  const dict = {
    en: {
      title: 'Forgot your password?',
      subtitle: "Enter your work email and we'll send you a reset link.",
      email: 'Email',
      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',
      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: 'البريد الإلكتروني',
      submit: 'إرسال رابط الإعادة',
      submitting: 'جارٍ الإرسال…',
      backToLogin: 'العودة إلى تسجيل الدخول',
      successTitle: 'تحقق من بريدك الإلكتروني',
      successBody: 'إذا كان البريد الإلكتروني مسجلاً، فقد تم إرسال رابط إعادة التعيين. تنتهي صلاحيته خلال 60 دقيقة.',
      error: 'حدث خطأ ما. يرجى المحاولة مرة أخرى.',
    },
  }[language]

  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 res = await fetch(`${API_BASE}/auth/employee/forgot-password`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      })
      if (!res.ok) throw new Error()
      setSent(true)
    } catch {
      setError(dict.error)
    } finally {
      setLoading(false)
    }
  }

  return (
    <main className="flex min-h-screen items-center justify-center bg-[radial-gradient(circle_at_top,#dbeafe,transparent_35%),linear-gradient(180deg,#f8fafc,white)] px-4 py-12">
      <div className="w-full max-w-md">
        <div className="mb-8 text-center">
          <Link href={marketplaceUrl} className="text-xs font-semibold uppercase tracking-[0.24em] text-blue-600">
            RentalDriveGo
          </Link>
          <h1 className="mt-3 text-3xl font-black tracking-tight text-slate-900">{dict.title}</h1>
          <p className="mt-2 text-sm text-slate-500">{dict.subtitle}</p>
        </div>

        <section className="rounded-[2rem] border border-slate-200 bg-white p-8 shadow-sm">
          {sent ? (
            <div className="space-y-4 text-center">
              <div className="mx-auto flex h-14 w-14 items-center justify-center rounded-full bg-green-100">
                <svg className="h-7 w-7 text-green-600" 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-slate-900">{dict.successTitle}</h2>
              <p className="text-sm text-slate-500">{dict.successBody}</p>
            </div>
          ) : (
            <form onSubmit={handleSubmit} className="space-y-5">
              {error && (
                <div className="rounded-2xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">{error}</div>
              )}
              <div>
                <label className="mb-1.5 block text-sm font-medium text-slate-700">{dict.email}</label>
                <input
                  type="email"
                  required
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  placeholder="owner@company.com"
                  className="input-field"
                />
              </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-slate-200 pt-6 text-center text-sm text-slate-500">
            <Link href="/sign-in" className="font-semibold text-slate-900 underline decoration-slate-300 underline-offset-4">
              {dict.backToLogin}
            </Link>
          </div>
        </section>
      </div>
    </main>
  )
}
