
import React, { useState } from 'react';
import { UserRole, ClinicType } from '../types';
import { useData } from '../context/DataContext';
import { useToast } from '../context/ToastContext';

interface LandingProps {
  onLogin: (role: UserRole) => void;
}

export const Landing: React.FC<LandingProps> = ({ onLogin }) => {
  const { setClinicType, tenants, activateTenant } = useData();
  const { addToast } = useToast();

  const [showLoginModal, setShowLoginModal] = useState(false);
  const [showActivationModal, setShowActivationModal] = useState(false);
  
  const [selectedRole, setSelectedRole] = useState<UserRole | null>(null);
  const [selectedClinicType, setSelectedClinicType] = useState<ClinicType>('general');
  
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [activationCode, setActivationCode] = useState('');
  const [loading, setLoading] = useState(false);

  const handleRoleSelect = (role: UserRole) => {
    setSelectedRole(role);
    setShowLoginModal(true);
    // Pre-fill
    if (role === UserRole.SUPER_ADMIN) {
      setEmail('admin@clinicpro.com');
      setPassword('password');
    } else {
      setEmail('ahmed@clinic.com'); // Matches mock tenant
      setPassword('password');
    }
  };

  const handleLoginSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);

    // Simulate API delay
    setTimeout(() => {
      setLoading(false);

      if (selectedRole === UserRole.SUPER_ADMIN) {
          onLogin(UserRole.SUPER_ADMIN);
      } else {
          // DOCTOR LOGIC
          // Check if tenant exists
          const tenant = tenants.find(t => t.email === email);
          
          if (!tenant) {
              // Fallback for demo if email doesn't match mock data
              setClinicType(selectedClinicType);
              onLogin(UserRole.DOCTOR);
              return;
          }

          if (tenant.isActivated) {
              // Tenant is activated, proceed
              setClinicType(selectedClinicType); // In real app, this comes from tenant config
              onLogin(UserRole.DOCTOR);
          } else {
              // Tenant needs activation
              setShowLoginModal(false);
              setShowActivationModal(true);
          }
      }
    }, 800);
  };

  const handleActivationSubmit = (e: React.FormEvent) => {
      e.preventDefault();
      setLoading(true);

      setTimeout(() => {
          setLoading(false);
          const success = activateTenant(email, activationCode);
          if (success) {
              addToast('تم تفعيل نسختك بنجاح! جاري الدخول...', 'success');
              setShowActivationModal(false);
              setClinicType(selectedClinicType);
              onLogin(UserRole.DOCTOR);
          } else {
              addToast('كود التفعيل غير صحيح', 'error');
          }
      }, 800);
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-primary to-primary-dark flex flex-col items-center justify-center p-4 relative overflow-hidden">
      
      {/* Background Decor */}
      <div className="absolute top-0 left-0 w-full h-full overflow-hidden z-0 pointer-events-none">
        <div className="absolute top-10 right-10 w-64 h-64 bg-white opacity-5 rounded-full blur-3xl"></div>
        <div className="absolute bottom-10 left-10 w-96 h-96 bg-blue-300 opacity-10 rounded-full blur-3xl"></div>
      </div>

      <div className="bg-white/95 backdrop-blur-sm rounded-3xl shadow-2xl p-8 md:p-12 w-full max-w-5xl grid md:grid-cols-2 gap-10 z-10 relative">
        
        {/* Left Side */}
        <div className="flex flex-col justify-center text-center md:text-right">
          <div className="mb-6 flex justify-center md:justify-start items-center gap-3">
            <div className="w-12 h-12 bg-primary rounded-xl flex items-center justify-center text-white shadow-lg rotate-3 hover:rotate-6 transition-transform">
              <i className="fas fa-cubes text-2xl"></i>
            </div>
            <div>
                <h1 className="text-2xl font-bold text-gray-800 leading-none">نظام خالد قصرين</h1>
                <span className="text-xs text-primary font-bold tracking-widest uppercase">الإصدار المطور</span>
            </div>
          </div>
          <h2 className="text-4xl md:text-5xl font-extrabold text-gray-900 mb-6 leading-tight">
            الحل الأمثل <span className="text-primary">لإدارة العيادات</span>
          </h2>
          <p className="text-gray-600 mb-8 text-lg leading-relaxed">
            منصة سحابية متكاملة تتيح لك إدارة عيادتك، مرضاك، ومواعيدك بكل سهولة وكفاءة. يدعم جميع التخصصات مع ميزات التخصيص الكامل.
          </p>
        </div>

        {/* Right Side */}
        <div className="flex flex-col gap-5 justify-center">
          <div 
            className="group bg-white p-6 rounded-2xl border-2 border-gray-100 hover:border-primary hover:shadow-lg transition-all cursor-pointer relative overflow-hidden" 
            onClick={() => handleRoleSelect(UserRole.SUPER_ADMIN)}
          >
            <div className="flex items-center justify-between mb-4 relative z-10">
              <div className="w-14 h-14 bg-blue-50 rounded-2xl flex items-center justify-center text-primary group-hover:bg-primary group-hover:text-white transition-colors">
                <i className="fas fa-user-shield text-2xl"></i>
              </div>
              <span className="bg-gray-100 text-gray-600 px-3 py-1 rounded-full text-xs font-bold">Admin Portal</span>
            </div>
            <h3 className="text-xl font-bold text-gray-800 mb-2">مدير النظام (خالد قصرين)</h3>
            <p className="text-sm text-gray-500">لوحة التحكم الكاملة لإدارة المشتركين والخطط.</p>
          </div>

          <div 
            className="group bg-white p-6 rounded-2xl border-2 border-gray-100 hover:border-success hover:shadow-lg transition-all cursor-pointer relative overflow-hidden" 
            onClick={() => handleRoleSelect(UserRole.DOCTOR)}
          >
            <div className="flex items-center justify-between mb-4 relative z-10">
              <div className="w-14 h-14 bg-green-50 rounded-2xl flex items-center justify-center text-success group-hover:bg-success group-hover:text-white transition-colors">
                <i className="fas fa-stethoscope text-2xl"></i>
              </div>
              <span className="bg-gray-100 text-gray-600 px-3 py-1 rounded-full text-xs font-bold">Doctor Portal</span>
            </div>
            <h3 className="text-xl font-bold text-gray-800 mb-2">الطبيب / العيادة</h3>
            <p className="text-sm text-gray-500">تجربة النظام كطبيب (11+ تخصص مدعوم).</p>
          </div>
        </div>
      </div>
      
      {/* Login Modal */}
      {showLoginModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
          <div className="bg-white rounded-3xl shadow-2xl w-full max-w-md overflow-hidden animate-slide-up">
            <div className="p-8">
              <div className="flex justify-between items-center mb-6">
                <h3 className="text-2xl font-bold text-gray-800">تسجيل الدخول</h3>
                <button onClick={() => setShowLoginModal(false)} className="text-gray-400 hover:text-gray-600">
                  <i className="fas fa-times text-xl"></i>
                </button>
              </div>

              {selectedRole === UserRole.DOCTOR && (
                <div className="mb-6">
                    <label className="block text-sm font-medium text-gray-700 mb-2">اختر نوع العيادة للتجربة:</label>
                    <select 
                        value={selectedClinicType}
                        onChange={(e) => setSelectedClinicType(e.target.value as any)}
                        className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary bg-white text-gray-900"
                    >
                        <option value="general">طبيب عام (General)</option>
                        <option value="dental">أسنان (Dental)</option>
                        <option value="vet">بيطري (Vet)</option>
                        <option value="ophthalmology">عيون (Ophthalmology)</option>
                        <option value="orthopedics">عظام (Orthopedics)</option>
                        <option value="surgery">جراحة (Surgery)</option>
                        <option value="pediatrics">أطفال (Pediatrics)</option>
                        <option value="neurology">دماغ وأعصاب (Neurology)</option>
                        <option value="dermatology">جلدية (Dermatology)</option>
                        <option value="obgyn">نسائية وتوليد (OB/GYN)</option>
                    </select>
                </div>
              )}
              
              <form onSubmit={handleLoginSubmit} className="space-y-4">
                <div>
                   <label className="block text-sm font-medium text-gray-700 mb-1">البريد الإلكتروني</label>
                   <input 
                        type="email" 
                        value={email} 
                        onChange={e => setEmail(e.target.value)} 
                        className="w-full px-4 py-3 rounded-xl border border-gray-300 focus:ring-primary focus:border-primary bg-white text-gray-900" 
                        dir="ltr" 
                    />
                </div>
                 <div>
                   <label className="block text-sm font-medium text-gray-700 mb-1">كلمة المرور</label>
                   <input 
                        type="password" 
                        value={password} 
                        onChange={e => setPassword(e.target.value)} 
                        className="w-full px-4 py-3 rounded-xl border border-gray-300 focus:ring-primary focus:border-primary bg-white text-gray-900" 
                        dir="ltr" 
                    />
                </div>
                <button 
                  type="submit" 
                  disabled={loading}
                  className="w-full bg-primary hover:bg-primary-dark text-white py-3.5 rounded-xl font-bold shadow-lg flex items-center justify-center gap-2"
                >
                  {loading ? 'جاري التحقق...' : 'دخول'}
                </button>
              </form>
            </div>
          </div>
        </div>
      )}

      {/* Activation Modal */}
      {showActivationModal && (
         <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4">
          <div className="bg-white rounded-3xl shadow-2xl w-full max-w-md overflow-hidden animate-slide-up">
            <div className="bg-warning p-6 text-center">
                <div className="w-16 h-16 bg-white/20 rounded-full flex items-center justify-center mx-auto mb-3">
                    <i className="fas fa-lock text-3xl text-yellow-900"></i>
                </div>
                <h3 className="text-xl font-bold text-yellow-900">تفعيل النسخة</h3>
                <p className="text-yellow-800 text-sm mt-1">هذه النسخة تتطلب التفعيل</p>
            </div>
            <div className="p-8">
              <div className="mb-6 p-4 bg-yellow-50 border border-yellow-200 rounded-xl text-center">
                  <p className="font-bold text-gray-800 text-sm mb-1">لتفعيل الموقع تواصل مع:</p>
                  <p className="text-lg font-bold text-primary">خالد قصرين</p>
                  <a href="tel:0985075127" className="text-2xl font-black text-gray-900 font-mono block mt-1 dir-ltr hover:text-primary transition-colors">
                      0985075127
                  </a>
              </div>

              <form onSubmit={handleActivationSubmit} className="space-y-6">
                <div>
                   <label className="block text-sm font-medium text-gray-700 mb-2 text-center">أدخل كود التفعيل المستلم</label>
                   <input 
                      type="text" 
                      value={activationCode} 
                      onChange={e => setActivationCode(e.target.value)} 
                      className="w-full px-4 py-3 rounded-xl border-2 border-gray-300 focus:border-warning text-center text-2xl tracking-widest uppercase font-mono bg-white text-gray-900" 
                      placeholder="XXXX-XXXX"
                      dir="ltr"
                      autoFocus
                   />
                </div>
                <button 
                  type="submit" 
                  disabled={loading}
                  className="w-full bg-warning hover:bg-yellow-500 text-yellow-900 py-3.5 rounded-xl font-bold shadow-lg flex items-center justify-center gap-2"
                >
                  {loading ? 'جاري التفعيل...' : 'تفعيل الآن'}
                </button>
              </form>
               <button onClick={() => setShowActivationModal(false)} className="w-full mt-4 text-gray-400 text-sm hover:text-gray-600">
                  إلغاء والعودة
               </button>
            </div>
          </div>
        </div>
      )}

      <p className="mt-8 text-white/80 text-sm z-10">© 2024 نظام خالد قصرين. جميع الحقوق محفوظة.</p>
    </div>
  );
};
