'use client';

import { useState, useEffect, useRef } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { api, apiPaths } from '@/lib/api';

function normalizePhone(value: string): string {
  return value.replace(/\D/g, '').replace(/^0/, '');
}

function normalizeCountryCode(cc: string): string {
  const n = cc.replace(/^\+/, '').replace(/\D/g, '');
  return n || '966';
}

export default function VerifyResetOTPPage() {
  const router = useRouter();
  const [code, setCode] = useState(['', '', '', '', '', '']);
  const [phone, setPhone] = useState('');
  const [countryCode, setCountryCode] = useState('966');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [resending, setResending] = useState(false);
  const [resendTimer, setResendTimer] = useState(60);
  const inputRefs = useRef<(HTMLInputElement | null)[]>([]);

  useEffect(() => {
    const rawPhone = sessionStorage.getItem('reset_phone') || '';
    const rawCc = sessionStorage.getItem('reset_country_code') || '966';
    const savedPhone = normalizePhone(rawPhone);
    const savedCC = normalizeCountryCode(rawCc);
    if (savedPhone) {
      sessionStorage.setItem('reset_phone', savedPhone);
      sessionStorage.setItem('reset_country_code', savedCC);
    }
    setPhone(savedPhone);
    setCountryCode(savedCC);
    if (!savedPhone) router.push('/forgot-password');

    const timer = setInterval(() => {
      setResendTimer((t) => (t > 0 ? t - 1 : 0));
    }, 1000);
    return () => clearInterval(timer);
  }, [router]);

  const handleChange = (index: number, value: string) => {
    const digit = value.replace(/\D/g, '').slice(-1);
    const newCode = [...code];
    newCode[index] = digit;
    setCode(newCode);
    if (digit && index < 5) inputRefs.current[index + 1]?.focus();
  };

  const handleKeyDown = (index: number, e: React.KeyboardEvent) => {
    if (e.key === 'Backspace' && !code[index] && index > 0) {
      inputRefs.current[index - 1]?.focus();
    }
  };

  const handleVerify = async () => {
    const fullCode = code.join('');
    if (fullCode.length < 4) { setError('الرجاء إدخال الكود كاملاً'); return; }
    setError('');
    setLoading(true);

    const res = await api.postWithoutAuth<{ reset_token: string }>(apiPaths.user.verifyResetCode, {
      phone: normalizePhone(phone),
      country_code: normalizeCountryCode(countryCode),
      code: fullCode,
    });

    setLoading(false);

    if (res.key === 'success' && res.data) {
      const data = res.data as { reset_token: string };
      // حفظ توكن إعادة التعيين
      sessionStorage.setItem('reset_token', data.reset_token);
      router.push('/reset-password');
    } else {
      setError(res.msg || 'الكود غير صحيح أو منتهي الصلاحية');
    }
  };

  const handleResend = async () => {
    if (resendTimer > 0) return;
    setResending(true);
    await api.postWithoutAuth(apiPaths.user.forgotPassword, {
      phone: normalizePhone(phone),
      country_code: normalizeCountryCode(countryCode),
    });
    setResendTimer(60);
    setResending(false);
    setCode(['', '', '', '', '', '']);
  };

  return (
    <div dir="rtl" 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-message-3-line text-3xl text-blue-600"></i>
            </div>
            <h1 className="text-2xl font-bold text-gray-900">أدخل كود التحقق</h1>
            <p className="text-gray-500 mt-2">
              تم إرسال كود إلى{' '}
              <span className="font-semibold text-gray-800" dir="ltr">+{countryCode} {phone}</span>
            </p>
          </div>

          <div className="flex gap-2 justify-center mb-6" dir="ltr">
            {code.map((digit, i) => (
              <input
                key={i}
                ref={(el) => { inputRefs.current[i] = el; }}
                type="text"
                inputMode="numeric"
                maxLength={1}
                value={digit}
                onChange={(e) => handleChange(i, e.target.value)}
                onKeyDown={(e) => handleKeyDown(i, e)}
                className="w-12 h-14 text-center text-2xl font-bold border-2 border-gray-200 rounded-xl focus:border-blue-500 focus:outline-none transition-colors"
              />
            ))}
          </div>

          {error && (
            <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm text-center">
              {error}
            </div>
          )}

          <button
            onClick={handleVerify}
            disabled={loading || code.join('').length < 4}
            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 mb-4"
          >
            {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>
                جاري التحقق...
              </span>
            ) : 'تحقق'}
          </button>

          <p className="text-center text-sm text-gray-500">
            لم تستلم الكود؟{' '}
            {resendTimer > 0 ? (
              <span className="text-gray-400">إعادة الإرسال بعد {resendTimer}ث</span>
            ) : (
              <button
                onClick={handleResend}
                disabled={resending}
                className="text-blue-600 font-semibold hover:text-blue-700 cursor-pointer"
              >
                {resending ? 'جاري الإرسال...' : 'إعادة الإرسال'}
              </button>
            )}
          </p>

          <p className="text-center text-gray-500 mt-4 text-sm">
            <Link href="/forgot-password" className="text-blue-600 font-semibold hover:text-blue-700">
              ← تغيير رقم الجوال
            </Link>
          </p>
        </div>
      </div>
    </div>
  );
}
