
import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { useData } from '../../context/DataContext';
import { useToast } from '../../context/ToastContext';
import { Tenant, Appointment } from '../../types';

export const PatientWebsite: React.FC = () => {
  const { domain } = useParams<{ domain: string }>();
  const { tenants, templates, services, addAppointment, appointments } = useData();
  const { addToast } = useToast();
  const [tenant, setTenant] = useState<Tenant | undefined>(undefined);
  const [loading, setLoading] = useState(true);

  // Booking Form State
  const [bookingName, setBookingName] = useState('');
  const [bookingPhone, setBookingPhone] = useState('');
  const [bookingDate, setBookingDate] = useState('');
  const [bookingService, setBookingService] = useState('');
  const [selectedTimeSlot, setSelectedTimeSlot] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Appointment Lookup State
  const [lookupPhone, setLookupPhone] = useState('');
  const [myAppointments, setMyAppointments] = useState<Appointment[]>([]);
  const [showLookupResult, setShowLookupResult] = useState(false);

  // Generate Mock Time Slots
  const timeSlots = ['09:00', '09:30', '10:00', '10:30', '11:00', '11:30', '12:00', '16:00', '16:30', '17:00', '17:30', '18:00', '18:30'];

  useEffect(() => {
    const found = tenants.find(t => t.domain === domain || t.domain.includes(domain || ''));
    setTenant(found);
    setLoading(false);
  }, [domain, tenants]);

  const handleBooking = (e: React.FormEvent) => {
      e.preventDefault();
      if (!bookingName || !bookingPhone || !bookingDate || !selectedTimeSlot) {
          alert('يرجى تعبئة جميع الحقول واختيار الوقت');
          return;
      }

      setIsSubmitting(true);

      // Simulate network request
      setTimeout(() => {
          const newAppointment: Appointment = {
              id: `pub_${Date.now()}`,
              patientName: bookingName,
              date: bookingDate,
              time: selectedTimeSlot, 
              type: bookingService || 'كشف عام',
              status: 'pending',
              notes: `حجز أونلاين - رقم الهاتف: ${bookingPhone}`
          };

          addAppointment(newAppointment);
          setIsSubmitting(false);
          alert('تم إرسال طلب الحجز بنجاح! رقم الحجز هو ' + newAppointment.id);
          
          // Reset Form
          setBookingName('');
          setBookingPhone('');
          setBookingDate('');
          setBookingService('');
          setSelectedTimeSlot('');
      }, 1500);
  };

  const handleLookup = (e: React.FormEvent) => {
      e.preventDefault();
      // Simple mock logic: Assuming patient name in appointment usually matches, but for demo we filter by a mock property or just simulate finding one
      // Since appointments don't store phone numbers in the main interface strictly, we'll simulate a search result
      const found = appointments.filter(a => a.notes?.includes(lookupPhone) || Math.random() > 0.7); 
      setMyAppointments(found);
      setShowLookupResult(true);
  };

  const handleTour = () => {
      document.getElementById('services')?.scrollIntoView({ behavior: 'smooth' });
  };

  if (loading) return <div className="h-screen flex items-center justify-center">جاري التحميل...</div>;
  if (!tenant) return <div className="h-screen flex items-center justify-center flex-col gap-4">
      <h1 className="text-4xl font-bold text-gray-800">404</h1>
      <p className="text-gray-500">عذراً، هذا الموقع غير موجود أو انتهى اشتراكه.</p>
  </div>;

  const template = templates.find(t => t.id === tenant.template) || templates[0];
  const content = tenant.siteContent;

  const getTheme = () => {
    switch (template.category) {
        case 'أسنان':
            return {
                primary: 'bg-emerald-600',
                text: 'text-emerald-700',
                heroImg: 'https://images.unsplash.com/photo-1606811841689-23dfddce3e95?ixlib=rb-4.0.3&auto=format&fit=crop&w=1600&q=80',
                icon: 'fa-tooth'
            };
        case 'نسائية':
            return {
                primary: 'bg-rose-500',
                text: 'text-rose-600',
                heroImg: 'https://images.unsplash.com/photo-1555252333-9f8e92e65df9?ixlib=rb-4.0.3&auto=format&fit=crop&w=1600&q=80',
                icon: 'fa-baby'
            };
        default:
            return {
                primary: 'bg-blue-600',
                text: 'text-blue-700',
                heroImg: 'https://images.unsplash.com/photo-1505751172876-fa1923c5c528?ixlib=rb-4.0.3&auto=format&fit=crop&w=1600&q=80',
                icon: 'fa-stethoscope'
            };
    }
  };

  const theme = getTheme();

  return (
    <div className="font-sans min-h-screen flex flex-col" dir="rtl">
      {/* Navbar */}
      <nav className="bg-white shadow-sm sticky top-0 z-50">
        <div className="container mx-auto px-6 py-4 flex justify-between items-center">
            <div className="flex items-center gap-2">
                <div className={`w-10 h-10 rounded-lg ${theme.primary} flex items-center justify-center text-white text-xl`}>
                    <i className={`fas ${theme.icon}`}></i>
                </div>
                <h1 className="text-xl font-bold text-gray-800">{tenant.clinicName}</h1>
            </div>
            <div className="hidden md:flex gap-6 text-gray-600 font-medium">
                <a href="#home" className="hover:text-primary transition-colors">الرئيسية</a>
                <a href="#services" className="hover:text-primary transition-colors">خدماتنا</a>
                <a href="#booking" className="hover:text-primary transition-colors">حجز موعد</a>
                <a href="#my-appointments" className="hover:text-primary transition-colors">مواعيدي</a>
            </div>
            <a href="#booking" className={`${theme.primary} text-white px-5 py-2 rounded-full font-bold shadow-md hover:opacity-90 transition-opacity`}>
                احجز الآن
            </a>
        </div>
      </nav>

      {/* Hero Section */}
      <header id="home" className="relative h-[600px] flex items-center">
          <div className="absolute inset-0 z-0">
              <img src={theme.heroImg} alt="Clinic" className="w-full h-full object-cover" />
              <div className="absolute inset-0 bg-gradient-to-r from-white/90 to-white/40"></div>
          </div>
          <div className="container mx-auto px-6 relative z-10 grid md:grid-cols-2">
              <div className="animate-slide-up">
                  <span className={`inline-block px-4 py-1 rounded-full bg-white border border-gray-200 text-sm font-bold mb-4 shadow-sm ${theme.text}`}>
                      نرحب بكم في {tenant.clinicName}
                  </span>
                  <h2 className="text-5xl md:text-6xl font-extrabold text-gray-900 mb-6 leading-tight">
                      {content?.heroTitle || 'رعايتكم الصحية أولويتنا القصوى'}
                  </h2>
                  <p className="text-xl text-gray-600 mb-8 max-w-lg leading-relaxed">
                      {content?.heroSubtitle || 'نقدم أفضل الخدمات الطبية بأحدث التقنيات لضمان صحتكم وراحتكم.'}
                  </p>
                  <div className="flex gap-4">
                      <a href="#booking" className={`${theme.primary} text-white px-8 py-4 rounded-xl font-bold shadow-lg hover:-translate-y-1 transition-transform flex items-center gap-2`}>
                          <i className="fas fa-calendar-check"></i>
                          احجز موعدك
                      </a>
                      <button 
                        onClick={handleTour}
                        className="bg-white text-gray-800 px-8 py-4 rounded-xl font-bold shadow-md hover:-translate-y-1 transition-transform border border-gray-100"
                      >
                          <i className="fas fa-play-circle mr-2 text-gray-400"></i>
                          جولة في العيادة
                      </button>
                  </div>
              </div>
          </div>
      </header>

      {/* Services Section */}
      <section id="services" className="py-20 bg-gray-50">
          <div className="container mx-auto px-6">
              <div className="text-center mb-16">
                  <h3 className={`text-sm font-bold uppercase tracking-wider mb-2 ${theme.text}`}>خدماتنا المميزة</h3>
                  <h2 className="text-3xl font-bold text-gray-900">ماذا نقدم لكم؟</h2>
              </div>
              
              <div className="grid md:grid-cols-3 gap-8">
                  {services.slice(0, 3).map((service, idx) => (
                      <div key={idx} className="bg-white p-8 rounded-2xl shadow-sm border border-gray-100 hover:shadow-xl transition-shadow group">
                          <div className={`w-14 h-14 rounded-2xl ${theme.primary} bg-opacity-10 flex items-center justify-center mb-6 group-hover:scale-110 transition-transform duration-300`}>
                              <i className={`fas ${idx === 0 ? 'fa-user-md' : idx === 1 ? 'fa-procedures' : 'fa-notes-medical'} text-2xl ${theme.text}`}></i>
                          </div>
                          <h4 className="text-xl font-bold text-gray-800 mb-3">{service.name}</h4>
                          <p className="text-gray-500 leading-relaxed mb-4">
                              {service.description || 'خدمة طبية متكاملة بأحدث الأجهزة والتقنيات لضمان أفضل النتائج.'}
                          </p>
                          <span className={`text-sm font-bold ${theme.text}`}>
                              ابتداءً من {service.price}$
                          </span>
                      </div>
                  ))}
                  <div className="bg-white p-8 rounded-2xl shadow-sm border border-gray-100 hover:shadow-xl transition-shadow group flex flex-col items-center justify-center text-center">
                       <div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4 text-gray-400">
                           <i className="fas fa-arrow-left text-2xl"></i>
                       </div>
                       <h4 className="font-bold text-gray-800">والمزيد من الخدمات...</h4>
                  </div>
              </div>
          </div>
      </section>

      {/* Booking Section */}
      <section id="booking" className="py-20 relative overflow-hidden">
          <div className={`absolute inset-0 ${theme.primary} opacity-5`}></div>
          <div className="container mx-auto px-6 relative z-10">
              <div className="bg-white rounded-3xl shadow-2xl overflow-hidden grid md:grid-cols-2">
                  <div className={`p-10 ${theme.primary} text-white flex flex-col justify-center`}>
                      <h3 className="text-3xl font-bold mb-4">حجز موعد أونلاين</h3>
                      <p className="text-white/80 mb-8 leading-relaxed">
                          وفر وقت الانتظار واحجز موعدك الآن بكل سهولة. سيقوم فريقنا بتأكيد الموعد معك قريباً.
                      </p>
                      <ul className="space-y-4">
                          <li className="flex items-center gap-3">
                              <i className="fas fa-check-circle text-white/60"></i>
                              <span>تأكيد فوري عبر الرسائل</span>
                          </li>
                           <li className="flex items-center gap-3">
                              <i className="fas fa-check-circle text-white/60"></i>
                              <span>تذكير قبل الموعد</span>
                          </li>
                           <li className="flex items-center gap-3">
                              <i className="fas fa-check-circle text-white/60"></i>
                              <span>إلغاء مجاني قبل 24 ساعة</span>
                          </li>
                      </ul>
                  </div>
                  <div className="p-10">
                      <form className="space-y-4" onSubmit={handleBooking}>
                          <div className="grid grid-cols-2 gap-4">
                              <input 
                                required
                                type="text" 
                                placeholder="الاسم الكامل" 
                                className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:border-gray-400 text-gray-900" 
                                value={bookingName}
                                onChange={e => setBookingName(e.target.value)}
                              />
                              <input 
                                required
                                type="tel" 
                                placeholder="رقم الهاتف" 
                                className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:border-gray-400 text-gray-900" 
                                value={bookingPhone}
                                onChange={e => setBookingPhone(e.target.value)}
                              />
                          </div>
                          
                          <select 
                            className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:border-gray-400 text-gray-900"
                            value={bookingService}
                            onChange={e => setBookingService(e.target.value)}
                          >
                              <option value="">اختر الخدمة المطلوبة</option>
                              {services.map(s => <option key={s.id} value={s.name}>{s.name}</option>)}
                          </select>

                          <div>
                              <label className="block text-sm font-medium text-gray-700 mb-2">التاريخ</label>
                              <input 
                                required
                                type="date" 
                                className="w-full px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:border-gray-400 text-gray-900" 
                                value={bookingDate}
                                onChange={e => setBookingDate(e.target.value)}
                              />
                          </div>

                          {bookingDate && (
                              <div className="animate-fade-in">
                                  <label className="block text-sm font-medium text-gray-700 mb-2">اختر الوقت المناسب</label>
                                  <div className="grid grid-cols-4 gap-2">
                                      {timeSlots.map(time => (
                                          <button
                                            key={time}
                                            type="button"
                                            onClick={() => setSelectedTimeSlot(time)}
                                            className={`py-2 rounded-lg text-sm font-medium transition-colors ${
                                                selectedTimeSlot === time 
                                                ? `${theme.primary} text-white shadow-md` 
                                                : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                                            }`}
                                          >
                                              {time}
                                          </button>
                                      ))}
                                  </div>
                              </div>
                          )}

                          <button 
                            type="submit" 
                            disabled={isSubmitting}
                            className={`w-full py-3 rounded-xl font-bold text-white shadow-lg ${theme.primary} hover:opacity-90 flex justify-center items-center gap-2 mt-4`}
                          >
                              {isSubmitting ? 'جاري الإرسال...' : 'تأكيد الحجز'}
                              {!isSubmitting && <i className="fas fa-paper-plane"></i>}
                          </button>
                      </form>
                  </div>
              </div>
          </div>
      </section>

      {/* Check Appointment Section */}
      <section id="my-appointments" className="py-16 bg-gray-100">
          <div className="container mx-auto px-6 max-w-2xl">
              <div className="text-center mb-8">
                  <h3 className="text-2xl font-bold text-gray-800">متابعة حجوزاتي</h3>
                  <p className="text-gray-500">أدخل رقم هاتفك للاستعلام عن حالة مواعيدك</p>
              </div>
              <div className="bg-white p-6 rounded-2xl shadow-sm border border-gray-200">
                  <form onSubmit={handleLookup} className="flex gap-2">
                      <input 
                        type="tel" 
                        placeholder="رقم الهاتف المسجل..." 
                        className="flex-1 px-4 py-3 bg-gray-50 border border-gray-200 rounded-xl focus:outline-none focus:border-gray-400 text-gray-900"
                        value={lookupPhone}
                        onChange={e => setLookupPhone(e.target.value)}
                        required
                      />
                      <button type="submit" className="bg-gray-800 text-white px-6 rounded-xl font-bold hover:bg-gray-900 transition-colors">
                          بحث
                      </button>
                  </form>

                  {showLookupResult && (
                      <div className="mt-6 space-y-3 animate-fade-in">
                          {myAppointments.length > 0 ? (
                              myAppointments.map(app => (
                                  <div key={app.id} className="flex justify-between items-center p-4 bg-blue-50 border border-blue-100 rounded-xl">
                                      <div>
                                          <h4 className="font-bold text-gray-800">{app.type}</h4>
                                          <p className="text-sm text-gray-600">{app.date} - {app.time}</p>
                                      </div>
                                      <span className={`px-3 py-1 rounded-full text-xs font-bold ${
                                          app.status === 'confirmed' ? 'bg-green-100 text-green-700' :
                                          app.status === 'pending' ? 'bg-yellow-100 text-yellow-700' :
                                          'bg-gray-200 text-gray-600'
                                      }`}>
                                          {app.status === 'confirmed' ? 'مؤكد' : app.status === 'pending' ? 'قيد الانتظار' : app.status}
                                      </span>
                                  </div>
                              ))
                          ) : (
                              <div className="text-center text-gray-500 py-4">
                                  لم يتم العثور على حجوزات بهذا الرقم.
                              </div>
                          )}
                      </div>
                  )}
              </div>
          </div>
      </section>

      {/* Footer */}
      <footer id="contact" className="bg-gray-900 text-white py-12 mt-auto">
          <div className="container mx-auto px-6">
              <div className="grid md:grid-cols-4 gap-8 mb-8">
                  <div className="col-span-1 md:col-span-2">
                      <h2 className="text-2xl font-bold mb-4">{content?.aboutTitle || 'من نحن'}</h2>
                      <p className="text-gray-400 leading-relaxed max-w-sm">
                          {content?.aboutText || 'نلتزم بتقديم أعلى معايير الرعاية الصحية لمرضانا. عيادتنا مجهزة بأحدث التقنيات وفريق طبي ذو خبرة عالية.'}
                      </p>
                  </div>
                  <div>
                      <h4 className="font-bold mb-4 text-gray-300">تواصل معنا</h4>
                      <ul className="space-y-2 text-gray-400">
                          <li><i className="fas fa-phone-alt ml-2"></i> {content?.contactPhone || tenant.phone}</li>
                          <li><i className="fas fa-envelope ml-2"></i> {content?.contactEmail || tenant.email}</li>
                          <li><i className="fas fa-map-marker-alt ml-2"></i> {content?.contactAddress || 'العنوان المسجل'}</li>
                      </ul>
                  </div>
                   <div>
                      <h4 className="font-bold mb-4 text-gray-300">ساعات العمل</h4>
                      <ul className="space-y-2 text-gray-400">
                          <li className="flex justify-between"><span>السبت - الخميس</span> <span>9:00 - 21:00</span></li>
                          <li className="flex justify-between"><span>الجمعة</span> <span>مغلق</span></li>
                      </ul>
                  </div>
              </div>
              <div className="border-t border-gray-800 pt-8 text-center text-gray-500 text-sm">
                  <p>حقوق النشر © 2024 {tenant.clinicName}. جميع الحقوق محفوظة.</p>
                  <p className="mt-1">Powered by <span className="text-white font-bold">Khaled Qasreen</span></p>
              </div>
          </div>
      </footer>
    </div>
  );
};
