
import React, { useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Modal } from '../../components/Modal';
import { useData } from '../../context/DataContext';
import { useToast } from '../../context/ToastContext';
import { Visit } from '../../types';
import { SmartField } from '../../components/ui/SmartField';
import { DentalChart } from '../../components/specialties/DentalChart';
import { PregnancyTracker } from '../../components/specialties/PregnancyTracker';
import { GrowthChart } from '../../components/specialties/GrowthChart';
import { PatientMedia } from '../../components/specialties/PatientMedia';
import { PrescriptionModal } from '../../components/specialties/PrescriptionModal';

export const PatientDetails: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { patients, visits, addVisit, clinicType, fieldConfigs, updatePatient } = useData();
  const { addToast } = useToast();
  
  // Tab State
  type TabType = 'personal' | 'history' | 'obgyn' | 'pediatric' | 'visits' | 'surgery' | 'dental' | 'followup' | 'consultation' | 'files';
  const [activeTab, setActiveTab] = useState<TabType>('personal');
  
  // Edit Mode State (Central Control)
  const [isEditMode, setIsEditMode] = useState(false);
  
  // Modals
  const [isVisitModalOpen, setIsVisitModalOpen] = useState(false);
  const [isPrescriptionModalOpen, setIsPrescriptionModalOpen] = useState(false);

  const patient = patients.find(p => p.id === id);
  const patientVisits = visits.filter(v => v.patientId === id);

  if (!patient) return <div className="h-screen flex items-center justify-center text-gray-500 text-lg">لم يتم العثور على المريض</div>;

  const handleAddVisit = (e: React.FormEvent) => {
    e.preventDefault();
    const form = e.target as HTMLFormElement;
    const date = (form.elements.namedItem('date') as HTMLInputElement).value;
    const cost = (form.elements.namedItem('cost') as HTMLInputElement).value;
    const notes = (form.elements.namedItem('notes') as HTMLTextAreaElement).value;

    if (id && date) {
      const newVisit: Visit = {
        id: Date.now().toString(),
        patientId: id,
        date,
        type: 'زيارة',
        cost: Number(cost),
        paid: Number(cost),
        notes
      };
      addVisit(newVisit);
      addToast('تم تسجيل الزيارة بنجاح', 'success');
      setIsVisitModalOpen(false);
    }
  };

  // --- Dynamic Field Logic ---

  // Handle saving dynamic data to patient record
  const handleFieldChange = (fieldId: string, value: any) => {
      const updatedPatient = { ...patient };
      // Check if it's a root property or custom data
      if (['name', 'phone', 'email', 'address', 'age', 'gender'].includes(fieldId.replace('p_', ''))) {
           // Handle legacy root props if needed, but primarily we use customData for everything now to be safe
           // For this demo, we map specific IDs back to root props for backward compatibility
           if(fieldId === 'p_name') updatedPatient.name = value;
           if(fieldId === 'p_phone') updatedPatient.phone = value;
           if(fieldId === 'p_age') updatedPatient.age = Number(value);
      }
      
      // Update customData
      updatedPatient.customData = { ...updatedPatient.customData, [fieldId]: value };
      updatePatient(updatedPatient);
  };

  // Helper to get value
  const getFieldValue = (fieldId: string) => {
      // Check legacy root props
      if(fieldId === 'p_name') return patient.name;
      if(fieldId === 'p_phone') return patient.phone;
      if(fieldId === 'p_age') return patient.age;
      
      // Check customData
      return patient.customData?.[fieldId] || '';
  };

  // Filter fields by section and sort by order
  const getSectionFields = (section: string) => {
      return fieldConfigs
        .filter(f => f.section === section)
        .sort((a, b) => a.order - b.order);
  };

  const tabs: { id: TabType; label: string; icon: string; color: string; show?: boolean }[] = [
      { id: 'personal', label: 'البيانات الشخصية', icon: 'fa-id-card', color: 'text-blue-600', show: true },
      { id: 'history', label: 'السجل الطبي', icon: 'fa-heartbeat', color: 'text-red-500', show: true },
      { id: 'visits', label: 'الزيارات', icon: 'fa-calendar-check', color: 'text-purple-600', show: true },
      // Show specialized tabs based on clinic type OR if explicitly enabled via edit mode/config
      { id: 'dental', label: 'الأسنان', icon: 'fa-tooth', color: 'text-emerald-600', show: clinicType === 'dental' || clinicType === 'general' },
      { id: 'obgyn', label: 'الحمل والولادة', icon: 'fa-baby-carriage', color: 'text-pink-500', show: clinicType === 'obgyn' || clinicType === 'general' },
      { id: 'pediatric', label: 'الأطفال', icon: 'fa-child', color: 'text-orange-500', show: clinicType === 'pediatrics' || clinicType === 'general' },
      { id: 'surgery', label: 'الجراحة', icon: 'fa-procedures', color: 'text-red-700', show: clinicType === 'surgery' || clinicType === 'general' },
      { id: 'followup', label: 'المتابعة', icon: 'fa-chart-line', color: 'text-indigo-600', show: true },
      { id: 'consultation', label: 'الاستشارات', icon: 'fa-comments', color: 'text-cyan-600', show: true },
      { id: 'files', label: 'المرفقات', icon: 'fa-folder-open', color: 'text-yellow-600', show: true },
  ];

  return (
    <div className="min-h-screen bg-gray-50 pb-20">
      {/* Top Bar / Header */}
      <div className="bg-white shadow-sm border-b border-gray-200 sticky top-0 z-20">
          <div className="container mx-auto px-4 py-3">
              <div className="flex flex-col md:flex-row justify-between items-center gap-4">
                  <div className="flex items-center gap-4 w-full md:w-auto">
                      <button onClick={() => navigate(-1)} className="w-10 h-10 bg-gray-100 rounded-full flex items-center justify-center hover:bg-gray-200 transition-colors text-gray-600">
                          <i className="fas fa-arrow-right"></i>
                      </button>
                      <div>
                          <h1 className="text-xl font-bold text-gray-900 flex items-center gap-2">
                              {patient.name}
                              <span className={`text-xs px-2 py-0.5 rounded-full ${patient.gender === 'male' ? 'bg-blue-100 text-blue-700' : 'bg-pink-100 text-pink-700'}`}>
                                  {patient.gender === 'male' ? 'ذكر' : 'أنثى'}
                              </span>
                          </h1>
                          <p className="text-xs text-gray-500 mt-0.5">رقم الملف: #{patient.id} | العمر: {patient.age} سنة</p>
                      </div>
                  </div>

                  {/* Action Buttons */}
                  <div className="flex gap-2 w-full md:w-auto overflow-x-auto pb-1 md:pb-0 items-center">
                      {/* --- EDIT MODE TOGGLE --- */}
                      <div className={`flex items-center gap-2 px-3 py-1.5 rounded-xl border transition-all ${isEditMode ? 'bg-orange-50 border-orange-200 shadow-inner' : 'bg-gray-100 border-gray-200'}`}>
                          <span className={`text-xs font-bold ${isEditMode ? 'text-orange-700' : 'text-gray-500'}`}>
                              {isEditMode ? 'وضع التعديل مفعل' : 'تخصيص النموذج'}
                          </span>
                          <button 
                            onClick={() => setIsEditMode(!isEditMode)} 
                            className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors focus:outline-none ${isEditMode ? 'bg-orange-500' : 'bg-gray-300'}`}
                          >
                              <span className={`inline-block h-3 w-3 transform rounded-full bg-white transition-transform ${isEditMode ? 'translate-x-1' : 'translate-x-5'}`} />
                          </button>
                      </div>

                      <button onClick={() => setIsPrescriptionModalOpen(true)} className="bg-emerald-50 text-emerald-700 hover:bg-emerald-100 px-4 py-2 rounded-lg text-sm font-bold flex items-center gap-2 whitespace-nowrap transition-colors border border-emerald-200">
                          <i className="fas fa-file-prescription"></i> وصفة
                      </button>
                      <button onClick={() => setIsVisitModalOpen(true)} className="bg-blue-50 text-blue-700 hover:bg-blue-100 px-4 py-2 rounded-lg text-sm font-bold flex items-center gap-2 whitespace-nowrap transition-colors border border-blue-200">
                          <i className="fas fa-plus"></i> زيارة
                      </button>
                      <button className="bg-gray-800 text-white px-4 py-2 rounded-lg text-sm font-bold flex items-center gap-2 whitespace-nowrap hover:bg-gray-900 shadow-md transition-colors">
                          <i className="fas fa-print"></i> طباعة
                      </button>
                  </div>
              </div>
          </div>
      </div>

      <div className="container mx-auto px-4 py-6">
          <div className="flex flex-col lg:flex-row gap-6 items-start">
              
              {/* Navigation Sidebar (Sticky) */}
              <div className="w-full lg:w-72 bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden lg:sticky lg:top-24 shrink-0">
                  <div className="p-4 bg-gray-50 border-b border-gray-100 font-bold text-gray-700 text-sm">
                      أقسام الملف الطبي
                  </div>
                  <nav className="flex lg:flex-col overflow-x-auto lg:overflow-visible p-2 gap-1 custom-scrollbar">
                      {tabs.filter(t => t.show).map(tab => (
                          <button 
                            key={tab.id}
                            onClick={() => setActiveTab(tab.id)}
                            className={`flex items-center gap-3 px-4 py-3 rounded-xl text-sm font-medium transition-all whitespace-nowrap ${
                                activeTab === tab.id 
                                ? 'bg-primary text-white shadow-md transform scale-105' 
                                : 'text-gray-600 hover:bg-gray-100 hover:text-gray-900'
                            }`}
                          >
                              <div className={`w-6 text-center ${activeTab === tab.id ? 'text-white' : tab.color}`}>
                                  <i className={`fas ${tab.icon}`}></i>
                              </div>
                              {tab.label}
                          </button>
                      ))}
                  </nav>
              </div>

              {/* Main Content Area */}
              <div className={`flex-1 w-full bg-white rounded-3xl shadow-sm border border-gray-200 p-6 md:p-8 min-h-[600px] animate-fade-in relative transition-all ${isEditMode ? 'ring-4 ring-orange-100 ring-offset-2' : ''}`}>
                  
                  {isEditMode && (
                      <div className="absolute top-0 left-0 w-full bg-orange-50 text-orange-800 text-xs py-1 text-center font-bold border-b border-orange-200 rounded-t-3xl z-10">
                          <i className="fas fa-pen mr-1"></i> وضع التعديل: يمكنك الآن إخفاء/إظهار الحقول، تفعيلها/تعطيلها، أو تغيير أسمائها.
                      </div>
                  )}

                  {/* Title of Section */}
                  <div className="mb-8 border-b border-gray-100 pb-4 flex justify-between items-center mt-4">
                      <h2 className="text-2xl font-bold text-gray-800 flex items-center gap-3">
                          <div className={`w-10 h-10 rounded-xl bg-gray-50 flex items-center justify-center ${tabs.find(t => t.id === activeTab)?.color}`}>
                              <i className={`fas ${tabs.find(t => t.id === activeTab)?.icon}`}></i>
                          </div>
                          {tabs.find(t => t.id === activeTab)?.label}
                      </h2>
                      <div className="hidden md:block text-sm text-gray-400">
                          {isEditMode ? <span className="text-orange-500 font-bold animate-pulse">● Live Editing</span> : `آخر تحديث: ${new Date().toLocaleDateString('ar-EG')}`}
                      </div>
                  </div>

                  {/* --- DYNAMIC SECTIONS --- */}
                  
                  {/* 1. Personal Data */}
                  {activeTab === 'personal' && (
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-6 animate-fade-in">
                          {getSectionFields('personal').map(field => (
                              <SmartField 
                                  key={field.id} 
                                  config={field} 
                                  value={getFieldValue(field.id)} 
                                  onChange={(val) => handleFieldChange(field.id, val)}
                                  isEditMode={isEditMode}
                              />
                          ))}
                      </div>
                  )}

                  {/* 2. Medical History */}
                  {activeTab === 'history' && (
                      <div className="space-y-8 animate-fade-in">
                          <div className={`bg-red-50 p-6 rounded-2xl border border-red-100 ${isEditMode ? 'border-dashed border-2 border-red-300' : ''}`}>
                              <h4 className="font-bold text-red-800 mb-4 flex items-center gap-2">
                                  <i className="fas fa-exclamation-circle"></i> تنبيهات طبية هامة
                              </h4>
                              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                  {getSectionFields('history').slice(0, 4).map(field => ( // First 4 are critical
                                      <SmartField key={field.id} config={field} value={getFieldValue(field.id)} onChange={v => handleFieldChange(field.id, v)} isEditMode={isEditMode} />
                                  ))}
                              </div>
                          </div>
                          
                          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                              {getSectionFields('history').slice(4).map(field => (
                                  <SmartField key={field.id} config={field} value={getFieldValue(field.id)} onChange={v => handleFieldChange(field.id, v)} isEditMode={isEditMode} />
                              ))}
                          </div>
                      </div>
                  )}

                  {/* 3. OB/GYN */}
                  {activeTab === 'obgyn' && (
                      <div className="space-y-6 animate-fade-in">
                          {/* Tracker Component Toggle */}
                          <div className={`transition-opacity ${isEditMode ? 'p-2 border-2 border-dashed border-pink-300 rounded-xl relative' : ''}`}>
                              {isEditMode && <span className="absolute -top-3 right-4 bg-pink-100 text-pink-800 text-xs px-2 rounded font-bold">تفاعلي: مخطط الحمل</span>}
                              <PregnancyTracker />
                          </div>
                          
                          <div className="mt-8">
                              <h3 className="font-bold text-gray-800 mb-4 border-b pb-2">سجل الحمل والولادة</h3>
                              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                  {getSectionFields('obgyn').map(field => (
                                      <SmartField key={field.id} config={field} value={getFieldValue(field.id)} onChange={v => handleFieldChange(field.id, v)} isEditMode={isEditMode} />
                                  ))}
                              </div>
                          </div>
                      </div>
                  )}

                  {/* 4. Pediatrics */}
                  {activeTab === 'pediatric' && (
                      <div className="space-y-6 animate-fade-in">
                          {/* Growth Chart Toggle */}
                          <div className={`transition-opacity ${isEditMode ? 'p-2 border-2 border-dashed border-orange-300 rounded-xl relative' : ''}`}>
                              {isEditMode && <span className="absolute -top-3 right-4 bg-orange-100 text-orange-800 text-xs px-2 rounded font-bold">تفاعلي: مخطط النمو</span>}
                              <GrowthChart />
                          </div>

                          <div className="mt-8">
                              <h3 className="font-bold text-gray-800 mb-4 border-b pb-2">تفاصيل الطفل</h3>
                              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                  {getSectionFields('pediatric').map(field => (
                                      <SmartField key={field.id} config={field} value={getFieldValue(field.id)} onChange={v => handleFieldChange(field.id, v)} isEditMode={isEditMode} />
                                  ))}
                              </div>
                          </div>
                      </div>
                  )}

                  {/* 5. Visits */}
                  {activeTab === 'visits' && (
                      <div className="space-y-4 animate-fade-in">
                          <div className="flex justify-between items-center mb-4">
                              <h3 className="font-bold text-gray-700">سجل الزيارات السابقة</h3>
                              <button onClick={() => setIsVisitModalOpen(true)} className="text-primary text-sm font-bold hover:underline">
                                  + إضافة زيارة يدوياً
                              </button>
                          </div>
                          {patientVisits.length > 0 ? (
                              <div className="space-y-4">
                                  {patientVisits.map(v => (
                                      <div key={v.id} className="border border-gray-200 p-5 rounded-2xl hover:shadow-md transition-all bg-gray-50/50">
                                          <div className="flex justify-between items-start mb-2">
                                              <div>
                                                  <span className="text-primary font-bold text-lg ml-2">{v.date}</span>
                                                  <span className="bg-white border border-gray-200 px-3 py-1 rounded-full text-xs text-gray-600">{v.type}</span>
                                              </div>
                                              <span className="font-mono font-bold text-gray-800">{v.cost} $</span>
                                          </div>
                                          <div className="bg-white p-3 rounded-xl border border-gray-100 text-gray-600 text-sm leading-relaxed">
                                              {v.notes}
                                          </div>
                                      </div>
                                  ))}
                              </div>
                          ) : (
                              <div className="text-center py-12 bg-gray-50 rounded-2xl border border-dashed border-gray-200">
                                  <i className="fas fa-calendar-times text-4xl text-gray-300 mb-3"></i>
                                  <p className="text-gray-500">لا توجد زيارات سابقة مسجلة</p>
                              </div>
                          )}
                      </div>
                  )}

                  {/* 6. Surgery */}
                  {activeTab === 'surgery' && (
                      <div className="space-y-6 animate-fade-in">
                          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                              {getSectionFields('surgery').map(field => (
                                  <SmartField key={field.id} config={field} value={getFieldValue(field.id)} onChange={v => handleFieldChange(field.id, v)} isEditMode={isEditMode} />
                              ))}
                          </div>
                      </div>
                  )}

                  {/* 7. Dental */}
                  {activeTab === 'dental' && (
                      <div className="space-y-8 animate-fade-in">
                          <div className={`transition-all ${isEditMode ? 'p-4 border-2 border-dashed border-emerald-300 rounded-xl relative' : ''}`}>
                              {isEditMode && <span className="absolute -top-3 right-4 bg-emerald-100 text-emerald-800 text-xs px-2 rounded font-bold">تفاعلي: مخطط الأسنان</span>}
                              <DentalChart />
                          </div>
                          
                          <div className="bg-emerald-50 p-6 rounded-2xl border border-emerald-100">
                              <h4 className="font-bold text-emerald-800 mb-4">تفاصيل العلاج</h4>
                              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                  {getSectionFields('dental').map(field => (
                                      <SmartField key={field.id} config={field} value={getFieldValue(field.id)} onChange={v => handleFieldChange(field.id, v)} isEditMode={isEditMode} />
                                  ))}
                              </div>
                          </div>
                      </div>
                  )}

                  {/* 8. Follow-up */}
                  {activeTab === 'followup' && (
                      <div className="space-y-6 animate-fade-in">
                          <div className="bg-indigo-50 p-4 rounded-xl border border-indigo-100 mb-4 flex items-center gap-3">
                              <i className="fas fa-info-circle text-indigo-500 text-xl"></i>
                              <p className="text-sm text-indigo-800">يستخدم هذا النموذج للحالات المزمنة أو التي تتطلب مراقبة طويلة الأمد.</p>
                          </div>
                          <div className="grid grid-cols-1 gap-6">
                              {getSectionFields('followup').map(field => (
                                  <SmartField key={field.id} config={field} value={getFieldValue(field.id)} onChange={v => handleFieldChange(field.id, v)} isEditMode={isEditMode} />
                              ))}
                          </div>
                      </div>
                  )}

                  {/* 9. Consultations */}
                  {activeTab === 'consultation' && (
                      <div className="space-y-6 animate-fade-in">
                          <div className="grid grid-cols-1 gap-6">
                              {getSectionFields('consultation').map(field => (
                                  <SmartField key={field.id} config={field} value={getFieldValue(field.id)} onChange={v => handleFieldChange(field.id, v)} isEditMode={isEditMode} />
                              ))}
                          </div>
                      </div>
                  )}

                  {/* Files */}
                  {activeTab === 'files' && (
                      <div className={`transition-all ${isEditMode ? 'p-2 border-2 border-dashed border-gray-300 rounded-xl relative' : ''}`}>
                          {isEditMode && <span className="absolute -top-3 right-4 bg-gray-200 text-gray-700 text-xs px-2 rounded font-bold">مدير الملفات (File Manager)</span>}
                          <PatientMedia />
                      </div>
                  )}

              </div>
          </div>
      </div>

      {/* Modals */}
      <Modal isOpen={isVisitModalOpen} onClose={() => setIsVisitModalOpen(false)} title="تسجيل زيارة جديدة">
        <form className="space-y-4" onSubmit={handleAddVisit}>
            <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">تاريخ الزيارة</label>
                <input name="date" type="date" defaultValue={new Date().toISOString().split('T')[0]} className="w-full px-3 py-2 border border-gray-300 rounded-lg bg-white text-gray-900" />
            </div>
            <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">التكلفة</label>
                <input name="cost" type="number" className="w-full px-3 py-2 border border-gray-300 rounded-lg bg-white text-gray-900" />
            </div>
            <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">ملاحظات وتشخيص</label>
                <textarea name="notes" rows={4} className="w-full px-3 py-2 border border-gray-300 rounded-lg bg-white text-gray-900"></textarea>
            </div>
            <button type="submit" className="w-full bg-primary text-white py-2 rounded-xl font-bold">حفظ</button>
        </form>
      </Modal>

      <PrescriptionModal 
        isOpen={isPrescriptionModalOpen} 
        onClose={() => setIsPrescriptionModalOpen(false)} 
        patientId={id} 
      />
    </div>
  );
};
