'use client';

import { useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { api, apiPaths } from '@/lib/api';
import { useI18n } from '@/lib/i18n/context';
import PhoneCountryRow from '@/app/components/PhoneCountryRow';

/** نفس تسجيل الدخول: أرقام فقط وبدون صفر أولي */
function normalizePhone(value: string): string {
  return value.replace(/\D/g, '').replace(/^0/, '');
}

export default function ForgotPasswordPage() {
  const router = useRouter();
  const { t, isRtl } = useI18n();
  const [phone, setPhone] = useState('');
  const [countryKey, setCountryKey] = useState('966');
  const [loading, setLoading] = useState(false);
  const [phoneError, setPhoneError] = useState('');
  const [submitError, setSubmitError] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setPhoneError('');
    setSubmitError('');
    const normalized = normalizePhone(phone);
    if (normalized.length < 7) {
      setPhoneError(t('auth.phoneInvalid'));
      return;
    }
    if (!countryKey) {
      setPhoneError(t('auth.selectCountry'));
      return;
    }
    setLoading(true);

    const res = await api.postWithoutAuth(apiPaths.user.forgotPassword, {
      phone: normalized,
      country_code: String(countryKey),
    });

    setLoading(false);

    if (res.key === 'success') {
      sessionStorage.setItem('reset_phone', normalized);
      sessionStorage.setItem('reset_country_code', String(countryKey));
      router.push('/verify-reset-otp');
    } else {
      setSubmitError(res.msg || t('forgotPassword.errorGeneric'));
    }
  };

  return (
    <div
      dir={isRtl ? 'rtl' : 'ltr'}
      className="min-h-screen bg-gradient-to-br from-blue-600 to-blue-800 flex items-center justify-center p-4"
    >
      <div className="w-full max-w-md">
        <div className="bg-white rounded-2xl shadow-2xl p-8">
          <div className="text-center mb-8">
            <div className="w-16 h-16 bg-blue-100 rounded-2xl flex items-center justify-center mx-auto mb-4">
              <i className="ri-lock-password-line text-3xl text-blue-600"></i>
            </div>
            <h1 className="text-2xl font-bold text-gray-900">{t('forgotPassword.title')}</h1>
            <p className="text-gray-500 mt-2">{t('forgotPassword.subtitle')}</p>
          </div>

          <form onSubmit={handleSubmit} className="space-y-5">
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">{t('forgotPassword.phoneLabel')}</label>
              <PhoneCountryRow
                phone={phone}
                onPhoneChange={(v) => {
                  setPhone(v);
                  setPhoneError('');
                }}
                countryKey={countryKey}
                onCountryKeyChange={(k) => {
                  setCountryKey(k);
                  setPhoneError('');
                }}
                isRtl={isRtl}
                disabled={loading}
                error={phoneError}
                labels={{
                  countryPlaceholder: t('login.countryPlaceholder'),
                  searchCountry: t('login.searchCountry'),
                  noResults: t('login.noResults'),
                }}
              />
            </div>

            {submitError && (
              <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm flex items-center gap-2">
                <i className="ri-error-warning-line"></i>
                {submitError}
              </div>
            )}

            <button
              type="submit"
              disabled={loading}
              className="w-full bg-blue-600 text-white py-3.5 rounded-xl font-semibold hover:bg-blue-700 disabled:bg-gray-300 transition-colors"
            >
              {loading ? (
                <span className="flex items-center justify-center gap-2">
                  <div className="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                  {t('forgotPassword.sending')}
                </span>
              ) : (
                t('forgotPassword.sendCode')
              )}
            </button>
          </form>

          <p className="text-center text-gray-500 mt-6 text-sm">
            {t('forgotPassword.remember')}{' '}
            <Link href="/login" className="text-blue-600 font-semibold hover:text-blue-700">
              {t('forgotPassword.login')}
            </Link>
          </p>
        </div>
      </div>
    </div>
  );
}
