'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';

type Step = 1 | 2 | 3;

export default function CaptainRegisterScreen() {
  const [currentStep, setCurrentStep] = useState<Step>(1);
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [location, setLocation] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [profileImage, setProfileImage] = useState<string | null>(null);
  const [busType, setBusType] = useState('');
  const [licenseFile, setLicenseFile] = useState<string | null>(null);
  const [busImage, setBusImage] = useState<string | null>(null);
  const [agreedToTerms, setAgreedToTerms] = useState(false);
  const router = useRouter();

  const passwordsMatch = password && confirmPassword && password === confirmPassword;
  const isStep1Valid = name && phone && password && confirmPassword && passwordsMatch && location;
  const isStep2Valid = busType && licenseFile && busImage;
  const isStep3Valid = agreedToTerms;

  const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => setProfileImage(reader.result as string);
      reader.readAsDataURL(file);
    }
  };

  const handleLicenseUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => setLicenseFile(reader.result as string);
      reader.readAsDataURL(file);
    }
  };

  const handleBusImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onloadend = () => setBusImage(reader.result as string);
      reader.readAsDataURL(file);
    }
  };

  const handleNext = () => {
    if (currentStep === 1 && isStep1Valid) setCurrentStep(2);
    else if (currentStep === 2 && isStep2Valid) setCurrentStep(3);
  };

  const handleSubmit = () => {
    if (isStep3Valid) router.push('/captain/pending-approval');
  };

  const inputStyle = {
    borderColor: '#C7D2FE',
  };

  const focusStyle = (e: React.FocusEvent<HTMLInputElement>) => {
    e.target.style.boxShadow = '0 0 0 2px #C7D2FE';
    e.target.style.borderColor = '#1E3A8A';
  };
  const blurStyle = (e: React.FocusEvent<HTMLInputElement>) => {
    e.target.style.boxShadow = 'none';
    e.target.style.borderColor = '#C7D2FE';
  };

  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={() => currentStep === 1 ? router.back() : setCurrentStep((currentStep - 1) as Step)}
          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="bg-white border-b px-4 py-4" style={{ borderColor: '#E0E7FF' }}>
        <div className="flex items-center justify-between mb-2">
          <div className="flex-1 flex items-center">
            <div className="w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold" style={{ background: currentStep >= 1 ? '#1E3A8A' : '#E0E7FF', color: currentStep >= 1 ? 'white' : '#A5B4FC' }}>
              {currentStep > 1 ? <i className="ri-check-line"></i> : '1'}
            </div>
            <div className="flex-1 h-1 mx-2" style={{ background: currentStep > 1 ? '#1E3A8A' : '#E0E7FF' }}></div>
          </div>
          <div className="flex-1 flex items-center">
            <div className="w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold" style={{ background: currentStep >= 2 ? '#1E3A8A' : '#E0E7FF', color: currentStep >= 2 ? 'white' : '#A5B4FC' }}>
              {currentStep > 2 ? <i className="ri-check-line"></i> : '2'}
            </div>
            <div className="flex-1 h-1 mx-2" style={{ background: currentStep > 2 ? '#1E3A8A' : '#E0E7FF' }}></div>
          </div>
          <div className="w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold" style={{ background: currentStep >= 3 ? '#1E3A8A' : '#E0E7FF', color: currentStep >= 3 ? 'white' : '#A5B4FC' }}>
            3
          </div>
        </div>
        <div className="flex items-center justify-between text-[10px] text-slate-500 mt-2">
          <span style={{ color: currentStep === 1 ? '#1E3A8A' : undefined, fontWeight: currentStep === 1 ? 700 : 400 }}>البيانات الشخصية</span>
          <span style={{ color: currentStep === 2 ? '#1E3A8A' : undefined, fontWeight: currentStep === 2 ? 700 : 400 }}>بيانات الباص</span>
          <span style={{ color: currentStep === 3 ? '#1E3A8A' : undefined, fontWeight: currentStep === 3 ? 700 : 400 }}>التأكيد</span>
        </div>
      </div>

      <div className="px-4 py-6 pb-24">
        {currentStep === 1 && (
          <>
            <div className="flex flex-col items-center mb-6">
              <div className="relative">
                <label htmlFor="profile-upload" className="cursor-pointer">
                  <div className="w-20 h-20 rounded-full border-2 border-dashed flex items-center justify-center overflow-hidden" style={{ background: '#EEF2FF', borderColor: '#A5B4FC' }}>
                    {profileImage ? (
                      <img src={profileImage} alt="Profile" className="w-full h-full object-cover" />
                    ) : (
                      <i className="ri-camera-line text-[28px]" style={{ color: '#818CF8' }}></i>
                    )}
                  </div>
                  <div className="absolute bottom-0 left-0 w-6 h-6 rounded-full flex items-center justify-center shadow-md" style={{ background: '#1E3A8A' }}>
                    <i className="ri-add-line text-white text-xs"></i>
                  </div>
                </label>
                <input id="profile-upload" type="file" accept="image/*" onChange={handleImageUpload} className="hidden" />
              </div>
              <p className="text-xs text-slate-500 mt-2">إضافة صورة (اختياري)</p>
            </div>

            <div className="space-y-4">
              {[
                { label: 'الاسم الكامل *', type: 'text', value: name, onChange: setName, placeholder: 'أدخل اسمك الكامل', icon: 'ri-user-line' },
              ].map((field, i) => (
                <div key={i}>
                  <label className="block text-[13px] font-semibold text-slate-600 mb-2 text-right">{field.label}</label>
                  <div className="relative">
                    <input
                      type={field.type}
                      value={field.value}
                      onChange={(e) => field.onChange(e.target.value)}
                      placeholder={field.placeholder}
                      className="w-full h-[52px] bg-white border rounded-xl pr-12 pl-4 text-slate-900 text-sm focus:outline-none transition-all"
                      style={inputStyle}
                      onFocus={focusStyle}
                      onBlur={blurStyle}
                    />
                    <div className="absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5 flex items-center justify-center">
                      <i className={`${field.icon} text-lg`} style={{ color: '#A5B4FC' }}></i>
                    </div>
                  </div>
                </div>
              ))}

              <div>
                <label className="block text-[13px] font-semibold text-slate-600 mb-2 text-right">رقم الجوال *</label>
                <div className="relative">
                  <input
                    type="tel"
                    value={phone}
                    onChange={(e) => setPhone(e.target.value)}
                    placeholder="5XXXXXXXX"
                    className="w-full h-[52px] bg-white border rounded-xl pr-24 pl-4 text-slate-900 text-sm focus:outline-none transition-all"
                    style={inputStyle}
                    onFocus={focusStyle}
                    onBlur={blurStyle}
                    dir="ltr"
                  />
                  <div className="absolute right-4 top-1/2 -translate-y-1/2 flex items-center gap-2 text-slate-600 text-sm">
                    <span>🇸🇦</span><span>+966</span>
                  </div>
                </div>
              </div>

              <div>
                <label className="block text-[13px] font-semibold text-slate-600 mb-2 text-right">كلمة المرور *</label>
                <div className="relative">
                  <input
                    type={showPassword ? 'text' : 'password'}
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    placeholder="••••••••"
                    className="w-full h-[52px] bg-white border rounded-xl px-4 text-slate-900 text-sm focus:outline-none transition-all"
                    style={inputStyle}
                    onFocus={focusStyle}
                    onBlur={blurStyle}
                  />
                  <button onClick={() => setShowPassword(!showPassword)} className="absolute left-4 top-1/2 -translate-y-1/2 cursor-pointer w-5 h-5 flex items-center justify-center" style={{ color: '#A5B4FC' }}>
                    <i className={`${showPassword ? 'ri-eye-line' : 'ri-eye-off-line'} text-lg`}></i>
                  </button>
                </div>
              </div>

              <div>
                <label className="block text-[13px] font-semibold text-slate-600 mb-2 text-right">تأكيد كلمة المرور *</label>
                <div className="relative">
                  <input
                    type={showConfirmPassword ? 'text' : 'password'}
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                    placeholder="••••••••"
                    className="w-full h-[52px] bg-white border rounded-xl px-4 pr-10 text-slate-900 text-sm focus:outline-none transition-all"
                    style={{ borderColor: passwordsMatch ? '#1E3A8A' : '#C7D2FE' }}
                    onFocus={focusStyle}
                    onBlur={blurStyle}
                  />
                  <button onClick={() => setShowConfirmPassword(!showConfirmPassword)} className="absolute left-4 top-1/2 -translate-y-1/2 cursor-pointer w-5 h-5 flex items-center justify-center" style={{ color: '#A5B4FC' }}>
                    <i className={`${showConfirmPassword ? 'ri-eye-line' : 'ri-eye-off-line'} text-lg`}></i>
                  </button>
                  {passwordsMatch && (
                    <div className="absolute right-4 top-1/2 -translate-y-1/2 w-5 h-5 flex items-center justify-center">
                      <i className="ri-checkbox-circle-fill text-lg" style={{ color: '#1E3A8A' }}></i>
                    </div>
                  )}
                </div>
              </div>

              <div>
                <label className="block text-[13px] font-semibold text-slate-600 mb-2 text-right">الموقع الجغرافي *</label>
                <button
                  onClick={() => setLocation('حي النزهة، الرياض')}
                  className="w-full h-[52px] border-2 border-dashed rounded-xl flex items-center justify-center gap-2 font-semibold text-sm cursor-pointer transition-all"
                  style={{ background: '#EEF2FF', borderColor: '#818CF8', color: '#1E3A8A' }}
                >
                  <div className="w-5 h-5 flex items-center justify-center">
                    <i className="ri-map-pin-line text-lg"></i>
                  </div>
                  {location || 'اضغط لتحديد موقعك'}
                </button>
              </div>
            </div>

            <button
              onClick={handleNext}
              disabled={!isStep1Valid}
              className="w-full h-[52px] rounded-xl font-semibold text-base transition-all whitespace-nowrap mt-8"
              style={{ background: isStep1Valid ? '#1E3A8A' : '#E0E7FF', color: isStep1Valid ? 'white' : '#A5B4FC', cursor: isStep1Valid ? 'pointer' : 'not-allowed' }}
            >
              التالي
            </button>
          </>
        )}

        {currentStep === 2 && (
          <>
            <div className="space-y-4">
              <div>
                <label className="block text-[13px] font-semibold text-slate-600 mb-2 text-right">نوع الباص *</label>
                <div className="flex gap-2">
                  {['ميني باص 14 راكب', 'باص 30 راكب', 'باص 50 راكب'].map((type) => (
                    <button
                      key={type}
                      onClick={() => setBusType(type)}
                      className="flex-1 h-11 rounded-xl text-xs font-semibold transition-all cursor-pointer whitespace-nowrap"
                      style={{
                        background: busType === type ? '#1E3A8A' : 'white',
                        color: busType === type ? 'white' : '#64748b',
                        border: busType === type ? 'none' : '1px solid #C7D2FE',
                      }}
                    >
                      {type}
                    </button>
                  ))}
                </div>
              </div>

              {[
                { id: 'license-upload', label: 'رخصة القيادة *', file: licenseFile, onChange: handleLicenseUpload, doneText: 'تم رفع الرخصة', uploadText: 'ارفع صورة رخصة القيادة' },
                { id: 'bus-upload', label: 'صورة الباص *', file: busImage, onChange: handleBusImageUpload, doneText: 'تم رفع صورة الباص', uploadText: 'ارفع صورة الباص' },
              ].map((item) => (
                <div key={item.id}>
                  <label className="block text-[13px] font-semibold text-slate-600 mb-2 text-right">{item.label}</label>
                  <label htmlFor={item.id} className="cursor-pointer">
                    <div className="w-full h-20 border-2 border-dashed rounded-xl flex flex-col items-center justify-center transition-all" style={{ background: item.file ? '#EEF2FF' : '#f8fafc', borderColor: item.file ? '#1E3A8A' : '#C7D2FE' }}>
                      {item.file ? (
                        <div className="flex items-center gap-2" style={{ color: '#1E3A8A' }}>
                          <i className="ri-checkbox-circle-fill text-xl"></i>
                          <span className="text-sm font-semibold">{item.doneText}</span>
                        </div>
                      ) : (
                        <>
                          <div className="w-8 h-8 flex items-center justify-center">
                            <i className="ri-upload-cloud-line text-[32px]" style={{ color: '#818CF8' }}></i>
                          </div>
                          <p className="text-[13px] text-slate-500 mt-1">{item.uploadText}</p>
                        </>
                      )}
                    </div>
                  </label>
                  <input id={item.id} type="file" accept="image/*" onChange={item.onChange} className="hidden" />
                </div>
              ))}
            </div>

            <button
              onClick={handleNext}
              disabled={!isStep2Valid}
              className="w-full h-[52px] rounded-xl font-semibold text-base transition-all whitespace-nowrap mt-8"
              style={{ background: isStep2Valid ? '#1E3A8A' : '#E0E7FF', color: isStep2Valid ? 'white' : '#A5B4FC', cursor: isStep2Valid ? 'pointer' : 'not-allowed' }}
            >
              التالي
            </button>
          </>
        )}

        {currentStep === 3 && (
          <>
            <div className="bg-white rounded-2xl p-4 mb-6 shadow-sm">
              <div className="flex items-center gap-3 mb-4 pb-4 border-b" style={{ borderColor: '#E0E7FF' }}>
                <div className="w-14 h-14 rounded-full overflow-hidden flex-shrink-0" style={{ background: '#EEF2FF' }}>
                  {profileImage ? (
                    <img src={profileImage} alt="Profile" className="w-full h-full object-cover" />
                  ) : (
                    <div className="w-full h-full flex items-center justify-center">
                      <i className="ri-user-line text-2xl" style={{ color: '#818CF8' }}></i>
                    </div>
                  )}
                </div>
                <div className="flex-1">
                  <h3 className="text-base font-bold text-slate-900">{name}</h3>
                  <p className="text-sm text-slate-500 mt-0.5" dir="ltr">+966 {phone}</p>
                </div>
              </div>
              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <span className="text-sm text-slate-500">نوع الباص</span>
                  <span className="text-sm font-semibold text-slate-900">{busType}</span>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm text-slate-500">رخصة القيادة</span>
                  <div className="flex items-center gap-1" style={{ color: '#1E3A8A' }}>
                    <i className="ri-checkbox-circle-fill text-base"></i>
                    <span className="text-sm font-semibold">تم رفع الرخصة</span>
                  </div>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm text-slate-500">صورة الباص</span>
                  <div className="flex items-center gap-1" style={{ color: '#1E3A8A' }}>
                    <i className="ri-checkbox-circle-fill text-base"></i>
                    <span className="text-sm font-semibold">تم رفع الصورة</span>
                  </div>
                </div>
              </div>
            </div>

            <div className="flex items-start gap-3 mb-6">
              <label className="flex items-start gap-3 cursor-pointer flex-1">
                <div className="relative flex-shrink-0 mt-0.5">
                  <input type="checkbox" checked={agreedToTerms} onChange={(e) => setAgreedToTerms(e.target.checked)} className="peer sr-only" />
                  <div className="w-5 h-5 border-2 rounded bg-white transition-all flex items-center justify-center" style={{ borderColor: agreedToTerms ? '#1E3A8A' : '#C7D2FE', background: agreedToTerms ? '#1E3A8A' : 'white' }}>
                    {agreedToTerms && <i className="ri-check-line text-white text-xs"></i>}
                  </div>
                </div>
                <span className="text-[13px] text-slate-600 text-right leading-relaxed">
                  أوافق على{' '}
                  <Link href="#" className="font-semibold cursor-pointer" style={{ color: '#1E3A8A' }}>الشروط والأحكام</Link>
                  {' '}و{' '}
                  <Link href="#" className="font-semibold cursor-pointer" style={{ color: '#1E3A8A' }}>السياسة الخاصة</Link>
                </span>
              </label>
            </div>

            <button
              onClick={handleSubmit}
              disabled={!isStep3Valid}
              className="w-full h-[52px] rounded-xl font-semibold text-base transition-all whitespace-nowrap mb-4 flex items-center justify-center gap-2"
              style={{ background: isStep3Valid ? '#1E3A8A' : '#E0E7FF', color: isStep3Valid ? 'white' : '#A5B4FC', cursor: isStep3Valid ? 'pointer' : 'not-allowed' }}
            >
              <span>إرسال الطلب للإدارة</span>
              <i className="ri-send-plane-fill text-lg"></i>
            </button>

            <div className="bg-amber-50 border border-amber-200 rounded-xl p-3 flex items-start gap-3">
              <div className="w-5 h-5 flex items-center justify-center flex-shrink-0 mt-0.5">
                <i className="ri-time-line text-amber-600 text-lg"></i>
              </div>
              <p className="text-[13px] text-amber-800 leading-relaxed">ستصلك رسالة موافقة خلال 24 ساعة</p>
            </div>
          </>
        )}
      </div>

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