'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 { localizedModePath, modeFromPathname, type Locale } from '@/lib/localization/config';
import { usePathname, useSearchParams } from 'next/navigation';
import { Suspense, useState } from 'react';
import styles from './AuthForms.module.css';

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 mode = modeFromPathname(usePathname());
  const token = searchParams.get('token');

  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [confirm, setConfirm] = useState('');
  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 {
      // 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 (error: unknown) {
      setError(error instanceof Error ? error.message : dict.errorGeneric);
    } finally {
      setLoading(false);
    }
  }

  const signInHref = localizedModePath('sign-in', locale, mode);
  const forgotHref = localizedModePath('forgot-password', locale, mode);

  if (!token) {
    return (
      <AuthShell locale={locale} title={dict.title}>
        <p className={styles.noToken}>
          {dict.noToken}
        </p>
        <div className={styles.actionWrap}>
          <a href={forgotHref}>
            <Button intent="primary">{dict.requestNew}</Button>
          </a>
        </div>
      </AuthShell>
    );
  }

  if (done) {
    return (
      <AuthShell locale={locale} title={dict.title}>
        <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 className={styles.actionWrap}>
            <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}
        className={styles.formStack}
      >
        {error ? (
          <div className={styles.error}>
            {error}
          </div>
        ) : null}

        <FormField id="reset-password" label={dict.newPassword} required>
          <div className={styles.passwordField}>
            <input
              id="reset-password"
              type={showPassword ? 'text' : 'password'}
              required
              minLength={8}
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="••••••••"
              autoComplete="new-password"
              className={styles.passwordInput}
            />
            <button
              type="button"
              onClick={() => setShowPassword((v) => !v)}
              tabIndex={-1}
              className={styles.passwordToggle}
            >
              {showPassword ? (
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" 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" width="20" height="20" 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>
        </FormField>

        <FormField id="reset-confirm" label={dict.confirmPassword} required>
          <div className={styles.passwordField}>
            <input
              id="reset-confirm"
              type={showConfirm ? 'text' : 'password'}
              required
              minLength={8}
              value={confirm}
              onChange={(e) => setConfirm(e.target.value)}
              placeholder="••••••••"
              autoComplete="new-password"
              className={styles.passwordInput}
            />
            <button
              type="button"
              onClick={() => setShowConfirm((v) => !v)}
              tabIndex={-1}
              className={styles.passwordToggle}
            >
              {showConfirm ? (
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" 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" width="20" height="20" 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>
        </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>
  );
}

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