
import React, { useState } from 'react';
import { useData } from '../../context/DataContext';
import { Modal } from '../../components/Modal';
import { useToast } from '../../context/ToastContext';
import { MedicalReport } from '../../types';

export const MedicalReports: React.FC = () => {
  const { medicalReports, patients, addMedicalReport, tenants, clinicType } = useData();
  const { addToast } = useToast();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [previewReport, setPreviewReport] = useState<MedicalReport | null>(null);

  // Get clinic info for header
  const tenant = tenants.find(t => t.clinicType === clinicType);

  const handleCreateReport = (e: React.FormEvent) => {
    e.preventDefault();
    const form = e.target as HTMLFormElement;
    const patientName = (form.elements.namedItem('patientName') as HTMLInputElement).value; // Ideally select ID
    const type = (form.elements.namedItem('type') as HTMLSelectElement).value as any;
    const content = (form.elements.namedItem('content') as HTMLTextAreaElement).value;

    if (patientName) {
        const newReport: MedicalReport = {
            id: `R-${Date.now().toString().slice(-5)}`,
            patientName,
            type,
            date: new Date().toISOString().split('T')[0],
            doctorName: 'د. أحمد خالد',
            content
        };
        addMedicalReport(newReport);
        addToast('تم إنشاء التقرير بنجاح', 'success');
        setIsModalOpen(false);
    }
  };

  const getTypeLabel = (type: string) => {
      switch(type) {
          case 'sick_leave': return { label: 'إجازة مرضية', color: 'bg-yellow-100 text-yellow-800' };
          case 'referral': return { label: 'تحويل طبي', color: 'bg-blue-100 text-blue-800' };
          default: return { label: 'تقرير عام', color: 'bg-gray-100 text-gray-800' };
      }
  };

  const handlePrint = () => {
      window.print();
  };

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center mb-6">
        <div>
          <h2 className="text-2xl font-bold text-gray-800">التقارير الطبية</h2>
          <p className="text-gray-500">إصدار الإجازات المرضية والتقارير الرسمية</p>
        </div>
        <button 
          onClick={() => setIsModalOpen(true)}
          className="bg-primary hover:bg-primary-dark text-white px-5 py-2.5 rounded-xl shadow-md transition-colors flex items-center gap-2"
        >
          <i className="fas fa-file-medical"></i>
          <span>تقرير جديد</span>
        </button>
      </div>

      <div className="grid gap-4">
          {medicalReports.map(report => {
              const typeInfo = getTypeLabel(report.type);
              return (
                  <div key={report.id} className="bg-white p-6 rounded-2xl shadow-sm border border-gray-100 flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                      <div className="flex-1">
                          <div className="flex items-center gap-3 mb-2">
                              <span className={`text-xs px-2 py-1 rounded-lg font-bold ${typeInfo.color}`}>{typeInfo.label}</span>
                              <span className="text-sm text-gray-400">{report.date}</span>
                          </div>
                          <h4 className="font-bold text-gray-800 text-lg mb-1">{report.patientName}</h4>
                          <p className="text-gray-600 text-sm line-clamp-2">{report.content}</p>
                          <p className="text-xs text-gray-400 mt-2">بواسطة: {report.doctorName}</p>
                      </div>
                      <button 
                        onClick={() => setPreviewReport(report)} 
                        className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 text-gray-600 text-sm font-medium transition-colors"
                      >
                          <i className="fas fa-eye mr-2"></i> معاينة وطباعة
                      </button>
                  </div>
              );
          })}
          {medicalReports.length === 0 && (
              <div className="text-center py-12 bg-white rounded-2xl border border-dashed border-gray-200 text-gray-400">
                  لا توجد تقارير طبية صادرة
              </div>
          )}
      </div>

      {/* Creation Modal */}
      <Modal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)} title="إصدار تقرير طبي">
          <form onSubmit={handleCreateReport} className="space-y-4">
              <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">المريض</label>
                  <select name="patientName" className="w-full px-3 py-2 border rounded-lg bg-white text-gray-900" required>
                      <option value="">اختر مريضاً...</option>
                      {patients.map(p => <option key={p.id} value={p.name}>{p.name}</option>)}
                  </select>
              </div>
              <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">نوع التقرير</label>
                  <select name="type" className="w-full px-3 py-2 border rounded-lg bg-white text-gray-900">
                      <option value="sick_leave">إجازة مرضية</option>
                      <option value="referral">تحويل طبي</option>
                      <option value="general">تقرير حالة عام</option>
                  </select>
              </div>
              <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">نص التقرير</label>
                  <textarea name="content" rows={5} className="w-full px-3 py-2 border rounded-lg bg-white text-gray-900" placeholder="اكتب تفاصيل التقرير هنا..." required></textarea>
              </div>
              <button type="submit" className="w-full bg-primary text-white py-2.5 rounded-xl font-bold">إصدار وحفظ</button>
          </form>
      </Modal>

      {/* Preview/Print Modal */}
      {previewReport && (
          <Modal isOpen={!!previewReport} onClose={() => setPreviewReport(null)} title="معاينة التقرير">
              <div className="print-area bg-white p-8 border border-gray-200 shadow-sm mb-4 text-right" id="report-print">
                  {/* Header */}
                  <div className="border-b-2 border-gray-800 pb-4 mb-6 flex justify-between items-center">
                      <div>
                          <h1 className="text-2xl font-bold text-gray-900">{tenant?.clinicName || 'اسم العيادة'}</h1>
                          <p className="text-gray-600 text-sm mt-1">{tenant?.clinicType} Clinic</p>
                      </div>
                      <div className="text-left text-sm text-gray-500">
                          <p>{tenant?.phone}</p>
                          <p>{tenant?.email}</p>
                      </div>
                  </div>

                  {/* Title */}
                  <div className="text-center mb-8">
                      <h2 className="text-xl font-bold underline decoration-2 decoration-gray-400 underline-offset-4">
                          {getTypeLabel(previewReport.type).label}
                      </h2>
                      <p className="text-gray-500 text-sm mt-2">التاريخ: {previewReport.date}</p>
                  </div>

                  {/* Content */}
                  <div className="mb-8 leading-relaxed text-gray-800 whitespace-pre-wrap min-h-[150px]">
                      <p><strong>اسم المريض:</strong> {previewReport.patientName}</p>
                      <br/>
                      <p>{previewReport.content}</p>
                  </div>

                  {/* Footer */}
                  <div className="mt-12 flex justify-between items-end pt-8">
                      <div className="text-center">
                          <p className="font-bold mb-4">التوقيع / الختم</p>
                          <div className="w-32 h-0.5 bg-gray-400"></div>
                      </div>
                      <div className="text-left text-sm font-bold text-gray-800">
                          {previewReport.doctorName}
                      </div>
                  </div>
              </div>
              
              <button onClick={handlePrint} className="w-full bg-gray-800 text-white py-3 rounded-xl font-bold flex items-center justify-center gap-2 hover:bg-gray-900">
                  <i className="fas fa-print"></i> طباعة المستند
              </button>
              
              <style>{`
                  @media print {
                      body * { visibility: hidden; }
                      .print-area, .print-area * { visibility: visible; }
                      .print-area { position: absolute; left: 0; top: 0; width: 100%; border: none; shadow: none; }
                      .modal-close, button { display: none; }
                  }
              `}</style>
          </Modal>
      )}
    </div>
  );
};
