'use client';

import { useState, useEffect, Suspense } from 'react';
import { useRouter } from 'next/navigation';
import { api, apiPaths } from '@/lib/api';
import { setUser, setToken } from '@/lib/auth';
import type { ApiUser } from '@/lib/auth';

type ActivateData = { user: ApiUser; go_to_register_step?: boolean; token?: string };

function VerifyOTPContent() {
  const router = useRouter();
  const [phone, setPhone]           = useState('');
  const [countryCode, setCountryCode] = useState('966');
  const [countryFlag, setCountryFlag] = useState('');
  const [otp, setOtp]               = useState(['', '', '', '', '', '']);
  const [loading, setLoading]       = useState(false);
  const [error, setError]           = useState('');
  const [resendCooldown, setResendCooldown] = useState(0);

  useEffect(() => {
    const savedPhone = sessionStorage.getItem('otp_phone') || '';
    const savedCode  = sessionStorage.getItem('otp_country_code') || '966';
    const savedFlag  = sessionStorage.getItem('otp_country_flag') || '';
    const backPath = sessionStorage.getItem('otp_back') || '/login';
    if (!savedPhone) {
      router.replace(backPath);
      return;
    }
    setPhone(savedPhone);
    setCountryCode(savedCode);
    setCountryFlag(savedFlag);
  }, [router]);

  const handleChange = (index: number, value: string) => {
    if (value.length > 1) return;
    const newOtp = [...otp];
    newOtp[index] = value.replace(/\D/g, '').slice(0, 1);
    setOtp(newOtp);
    setError('');
    if (value && index < 5) {
      document.getElementById(`otp-${index + 1}`)?.focus();
    }
  };

  const handleKeyDown = (index: number, e: React.KeyboardEvent) => {
    if (e.key === 'Backspace' && !otp[index] && index > 0) {
      document.getElementById(`otp-${index - 1}`)?.focus();
    }
  };

  const handlePaste = (e: React.ClipboardEvent) => {
    const text = e.clipboardData.getData('text').replace(/\D/g, '').slice(0, 6);
    if (text.length === 6) {
      setOtp(text.split(''));
      document.getElementById(`otp-5`)?.focus();
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const otpValue = otp.join('');
    if (otpValue.length !== 6) {
      setError('أدخل رمز التحقق المكون من 6 أرقام');
      return;
    }
    setError('');
    setLoading(true);
    try {
      const res = await api.postWithoutAuth<ActivateData>(apiPaths.user.checkCode, {
        code:         otpValue,
        phone:        phone,
        country_code: countryCode,
        device_id:    'web',
        device_type:  'web',
        lang:         'ar',
      });
      if (res.key === 'success' && res.data?.user) {
        const raw = res.data as ActivateData;
        const u = raw.user as ApiUser & { token?: string };
        const bearer = (u.token ?? raw.token ?? '').trim();
        if (bearer) setToken(bearer);
        setUser({ ...u, token: bearer || u.token });
        sessionStorage.removeItem('otp_phone');
        sessionStorage.removeItem('otp_country_code');
        sessionStorage.removeItem('otp_back');
        if (res.data.go_to_register_step) {
          router.push('/register');
          return;
        }
        if (u.is_approved === false) {
          router.push('/account-pending');
          return;
        }
        router.push('/');
        return;
      }
      setError(res.msg || 'رمز غير صحيح، حاول مرة أخرى');
    } catch {
      setError('تعذر الاتصال بالخادم');
    } finally {
      setLoading(false);
    }
  };

  const handleResend = async () => {
    if (resendCooldown > 0 || !phone) return;
    setError('');
    setLoading(true);
    try {
      const res = await api.postWithoutAuth(apiPaths.user.resendCode, {
        phone,
        country_code: countryCode,
      });
      if (res.key === 'success') {
        setOtp(['', '', '', '', '', '']);
        setResendCooldown(60);
        const t = setInterval(() => {
          setResendCooldown((c) => {
            if (c <= 1) { clearInterval(t); return 0; }
            return c - 1;
          });
        }, 1000);
      } else {
        setError(res.msg || 'فشل إعادة الإرسال');
      }
    } catch {
      setError('تعذر الاتصال بالخادم');
    } finally {
      setLoading(false);
    }
  };

  if (!phone) return null;

  const maskedPhone = phone.length > 4
    ? phone.slice(0, 2) + '****' + phone.slice(-3)
    : phone;


  return (
    <div dir="rtl" className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-gray-50 flex items-center justify-center px-4">
      <div className="w-full max-w-md">
        <div className="bg-white rounded-2xl shadow-xl p-8">
          <div className="text-center mb-8">
            <div className="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
              <i className="ri-mail-check-line text-3xl text-blue-600"></i>
            </div>
            <h1 className="text-2xl font-bold text-gray-800">تأكيد رقم الجوال</h1>
            <p className="text-gray-600 mt-2">تم إرسال رمز التحقق إلى</p>
            <div className="flex items-center justify-center gap-2 mt-1">
              {countryFlag && (
                <img src={countryFlag} alt="" className="w-6 h-4 object-cover rounded-sm" />
              )}
              <span className="text-blue-600 font-semibold" dir="ltr">+{countryCode} {maskedPhone}</span>
            </div>
          </div>

          <form onSubmit={handleSubmit} className="space-y-6">
            <div>
              <label className="block text-gray-700 font-semibold mb-3 text-center">
                أدخل رمز التحقق
              </label>
              <div className="flex justify-center gap-2" dir="ltr" onPaste={handlePaste}>
                {otp.map((digit, index) => (
                  <input
                    key={index}
                    id={`otp-${index}`}
                    type="text"
                    inputMode="numeric"
                    maxLength={1}
                    value={digit}
                    onChange={(e) => handleChange(index, e.target.value)}
                    onKeyDown={(e) => handleKeyDown(index, e)}
                    className="w-12 h-12 text-center text-xl font-bold border-2 border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                  />
                ))}
              </div>
            </div>

            {error && <p className="text-red-600 text-sm text-center">{error}</p>}

            <button
              type="submit"
              disabled={loading || otp.join('').length !== 6}
              className="w-full bg-blue-600 text-white py-3 rounded-lg hover:bg-blue-700 transition-colors font-semibold whitespace-nowrap cursor-pointer disabled:opacity-70"
            >
              {loading ? 'جاري التحقق...' : 'تأكيد الرمز'}
            </button>
          </form>

          <div className="mt-6 text-center">
            <p className="text-gray-600 mb-2">لم تستلم الرمز؟</p>
            <button
              type="button"
              onClick={handleResend}
              disabled={loading || resendCooldown > 0}
              className="text-blue-600 hover:text-blue-700 font-semibold cursor-pointer whitespace-nowrap disabled:opacity-50"
            >
              {resendCooldown > 0 ? `إعادة إرسال خلال ${resendCooldown}ث` : 'إعادة إرسال الرمز'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

export default function VerifyOTPPage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-gray-50 flex items-center justify-center">
        <div className="w-16 h-16 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
      </div>
    }>
      <VerifyOTPContent />
    </Suspense>
  );
}
