'use client';

import { useState, useRef, useEffect } from 'react';
import { useRouter } from 'next/navigation';

export default function CaptainOTPScreen() {
  const [otp, setOtp] = useState(['', '', '', '']);
  const [timer, setTimer] = useState(59);
  const inputRefs = [
    useRef<HTMLInputElement>(null),
    useRef<HTMLInputElement>(null),
    useRef<HTMLInputElement>(null),
    useRef<HTMLInputElement>(null)
  ];
  const router = useRouter();

  useEffect(() => {
    if (timer > 0) {
      const interval = setInterval(() => setTimer(prev => prev - 1), 1000);
      return () => clearInterval(interval);
    }
  }, [timer]);

  const handleChange = (index: number, value: string) => {
    if (value.length > 1) return;
    const newOtp = [...otp];
    newOtp[index] = value;
    setOtp(newOtp);
    if (value && index < 3) inputRefs[index + 1].current?.focus();
  };

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

  const handleResend = () => {
    if (timer === 0) {
      setTimer(59);
      setOtp(['', '', '', '']);
      inputRefs[0].current?.focus();
    }
  };

  const handleVerify = () => {
    if (otp.every(digit => digit !== '')) router.push('/captain/home');
  };

  return (
    <div className="min-h-screen" dir="rtl" style={{ maxWidth: '390px', margin: '0 auto', background: '#EEF2FF' }}>
      <div className="h-11"></div>

      <div className="h-14 bg-white shadow-sm flex items-center justify-center px-4 relative">
        <button onClick={() => router.back()} className="absolute right-4 w-10 h-10 flex items-center justify-center cursor-pointer">
          <i className="ri-arrow-right-line text-slate-900 text-xl"></i>
        </button>
        <h1 className="text-lg font-bold text-slate-900">التحقق من الرقم</h1>
      </div>

      <div className="px-6 py-12 text-center">
        <div className="w-20 h-20 rounded-full flex items-center justify-center mx-auto mb-4" style={{ background: '#E0E7FF' }}>
          <i className="ri-smartphone-line text-4xl" style={{ color: '#1E3A8A' }}></i>
        </div>

        <h2 className="text-[22px] font-bold text-slate-900 mb-3">أدخل كود التحقق</h2>
        <p className="text-sm text-slate-600 mb-1">أرسلنا كود مكون من 4 أرقام إلى</p>
        <p className="text-[15px] font-bold mb-8" style={{ color: '#1E3A8A' }}>+966 5XX XXX XXX</p>

        <div className="flex justify-center gap-3 mb-6" dir="ltr">
          {otp.map((digit, index) => (
            <input
              key={index}
              ref={inputRefs[index]}
              type="text"
              inputMode="numeric"
              maxLength={1}
              value={digit}
              onChange={(e) => handleChange(index, e.target.value)}
              onKeyDown={(e) => handleKeyDown(index, e)}
              className="w-16 h-16 text-center text-2xl font-bold rounded-xl transition-all focus:outline-none"
              style={{
                background: digit ? '#EEF2FF' : 'white',
                border: digit ? '2px solid #1E3A8A' : '1px solid #C7D2FE',
                color: '#172554',
              }}
            />
          ))}
        </div>

        <div className="mb-8">
          {timer > 0 ? (
            <p className="text-sm text-slate-600">إعادة الإرسال بعد 0:{timer.toString().padStart(2, '0')}</p>
          ) : (
            <button onClick={handleResend} className="text-sm font-semibold cursor-pointer" style={{ color: '#1E3A8A' }}>
              إعادة إرسال الكود
            </button>
          )}
        </div>

        <button
          onClick={handleVerify}
          disabled={!otp.every(digit => digit !== '')}
          className="w-full h-[52px] rounded-xl font-semibold text-base transition-all whitespace-nowrap"
          style={{
            background: otp.every(d => d !== '') ? '#1E3A8A' : '#E0E7FF',
            color: otp.every(d => d !== '') ? 'white' : '#A5B4FC',
            cursor: otp.every(d => d !== '') ? 'pointer' : 'not-allowed',
          }}
        >
          تأكيد
        </button>
      </div>

      <div className="h-[34px]"></div>
    </div>
  );
}
