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

interface PrescriptionModalProps {
  isOpen: boolean;
  onClose: () => void;
  patientId?: string; // Optional: If opened from patient details, pre-select patient
}

export const PrescriptionModal: React.FC<PrescriptionModalProps> = ({ isOpen, onClose, patientId }) => {
  const { patients, addPrescription } = useData();
  const { addToast } = useToast();
  
  const [selectedPatientId, setSelectedPatientId] = useState(patientId || '');
  const [items, setItems] = useState<PrescriptionItem[]>([
      { drugName: '', dosage: '', frequency: '', duration: '', notes: '' }
  ]);

  const patient = patients.find(p => p.id === selectedPatientId);

  const addItem = () => {
      setItems([...items, { drugName: '', dosage: '', frequency: '', duration: '', notes: '' }]);
  };

  const removeItem = (index: number) => {
      if (items.length > 1) {
          setItems(items.filter((_, i) => i !== index));
      }
  };

  const updateItem = (index: number, field: keyof PrescriptionItem, value: string) => {
      const newItems = [...items];
      newItems[index] = { ...newItems[index], [field]: value };
      setItems(newItems);
  };

  const handleSave = () => {
      if (!selectedPatientId) {
          addToast('الرجاء اختيار المريض', 'error');
          return;
      }
      if (items.some(i => !i.drugName)) {
          addToast('الرجاء تعبئة اسم الدواء', 'error');
          return;
      }

      const prescription: Prescription = {
          id: `RX-${Date.now().toString().slice(-6)}`,
          patientId: selectedPatientId,
          patientName: patient?.name || 'Unknown',
          date: new Date().toISOString().split('T')[0],
          doctorName: 'د. أحمد خالد', // Should come from auth context
          items: items
      };

      addPrescription(prescription);
      onClose();
      // Reset
      setItems([{ drugName: '', dosage: '', frequency: '', duration: '', notes: '' }]);
      if (!patientId) setSelectedPatientId('');
  };

  return (
    <Modal isOpen={isOpen} onClose={onClose} title="وصفة طبية جديدة">
        <div className="space-y-4 max-h-[70vh] overflow-y-auto p-1">
            {!patientId && (
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">المريض</label>
                    <select 
                        className="w-full px-3 py-2 border border-gray-300 rounded-lg bg-white text-gray-900"
                        value={selectedPatientId}
                        onChange={e => setSelectedPatientId(e.target.value)}
                    >
                        <option value="">اختر مريضاً...</option>
                        {patients.map(p => (
                            <option key={p.id} value={p.id}>{p.name}</option>
                        ))}
                    </select>
                </div>
            )}

            <div className="space-y-3">
                {items.map((item, index) => (
                    <div key={index} className="bg-gray-50 p-3 rounded-xl border border-gray-200 relative">
                        <div className="grid grid-cols-2 gap-2 mb-2">
                            <input 
                                type="text" 
                                placeholder="اسم الدواء (Drug Name)" 
                                className="col-span-2 w-full px-3 py-1.5 border rounded text-sm font-medium bg-white text-gray-900"
                                value={item.drugName}
                                onChange={e => updateItem(index, 'drugName', e.target.value)}
                            />
                            <input 
                                type="text" 
                                placeholder="الجرعة (Dosage)" 
                                className="w-full px-3 py-1.5 border rounded text-sm bg-white text-gray-900"
                                value={item.dosage}
                                onChange={e => updateItem(index, 'dosage', e.target.value)}
                            />
                            <input 
                                type="text" 
                                placeholder="التكرار (Frequency)" 
                                className="w-full px-3 py-1.5 border rounded text-sm bg-white text-gray-900"
                                value={item.frequency}
                                onChange={e => updateItem(index, 'frequency', e.target.value)}
                            />
                            <input 
                                type="text" 
                                placeholder="المدة (Duration)" 
                                className="w-full px-3 py-1.5 border rounded text-sm bg-white text-gray-900"
                                value={item.duration}
                                onChange={e => updateItem(index, 'duration', e.target.value)}
                            />
                            <input 
                                type="text" 
                                placeholder="ملاحظات (قبل/بعد الأكل)" 
                                className="w-full px-3 py-1.5 border rounded text-sm bg-white text-gray-900"
                                value={item.notes}
                                onChange={e => updateItem(index, 'notes', e.target.value)}
                            />
                        </div>
                        {items.length > 1 && (
                            <button 
                                onClick={() => removeItem(index)}
                                className="absolute top-2 left-2 text-red-400 hover:text-red-600"
                            >
                                <i className="fas fa-times-circle"></i>
                            </button>
                        )}
                    </div>
                ))}
            </div>

            <button onClick={addItem} className="text-sm text-primary font-bold hover:underline">
                + إضافة دواء آخر
            </button>

            <div className="pt-2 border-t border-gray-100 flex gap-2">
                <button onClick={handleSave} className="flex-1 bg-primary text-white py-2 rounded-xl font-bold hover:bg-primary-dark">
                    حفظ وطباعة
                </button>
            </div>
        </div>
    </Modal>
  );
};
