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

export const Inventory: React.FC = () => {
  const { inventory, addInventoryItem, updateInventoryItem, deleteInventoryItem } = useData();
  const { addToast } = useToast();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingItem, setEditingItem] = useState<InventoryItem | null>(null);

  const handleSave = (e: React.FormEvent) => {
      e.preventDefault();
      const form = e.target as HTMLFormElement;
      const name = (form.elements.namedItem('name') as HTMLInputElement).value;
      const quantity = (form.elements.namedItem('quantity') as HTMLInputElement).value;
      const unit = (form.elements.namedItem('unit') as HTMLInputElement).value;
      const minThreshold = (form.elements.namedItem('minThreshold') as HTMLInputElement).value;
      const category = (form.elements.namedItem('category') as HTMLSelectElement).value as any;
      const expiryDate = (form.elements.namedItem('expiryDate') as HTMLInputElement).value;

      if (name && quantity) {
          const itemData: InventoryItem = {
              id: editingItem ? editingItem.id : `inv_${Date.now()}`,
              name,
              quantity: Number(quantity),
              unit,
              minThreshold: Number(minThreshold),
              category,
              expiryDate
          };

          if (editingItem) {
              updateInventoryItem(itemData);
              addToast('تم تحديث المادة بنجاح', 'success');
          } else {
              addInventoryItem(itemData);
              addToast('تم إضافة المادة للمخزون', 'success');
          }
          setIsModalOpen(false);
          setEditingItem(null);
      }
  };

  const handleEdit = (item: InventoryItem) => {
      setEditingItem(item);
      setIsModalOpen(true);
  };

  const handleDelete = (id: string) => {
      if(window.confirm('هل أنت متأكد من الحذف؟')) {
          deleteInventoryItem(id);
          addToast('تم حذف العنصر', 'error');
      }
  };

  const getStatus = (item: InventoryItem) => {
      if (item.quantity <= 0) return { label: 'نفد المخزون', color: 'bg-red-100 text-red-800' };
      if (item.quantity <= item.minThreshold) return { label: 'منخفض', color: 'bg-yellow-100 text-yellow-800' };
      return { label: 'متوفر', color: 'bg-green-100 text-green-800' };
  };

  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={() => { setEditingItem(null); 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-plus"></i>
          <span>عنصر جديد</span>
        </button>
      </div>

      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
          <table className="w-full">
              <thead className="bg-gray-50">
                  <tr>
                      <th className="px-6 py-4 text-right text-sm font-semibold text-gray-600">اسم المادة</th>
                      <th className="px-6 py-4 text-right text-sm font-semibold text-gray-600">التصنيف</th>
                      <th className="px-6 py-4 text-right text-sm font-semibold text-gray-600">الكمية</th>
                      <th className="px-6 py-4 text-right text-sm font-semibold text-gray-600">تاريخ الصلاحية</th>
                      <th className="px-6 py-4 text-right text-sm font-semibold text-gray-600">الحالة</th>
                      <th className="px-6 py-4 text-center text-sm font-semibold text-gray-600">إجراءات</th>
                  </tr>
              </thead>
              <tbody className="divide-y divide-gray-100">
                  {inventory.map(item => {
                      const status = getStatus(item);
                      return (
                          <tr key={item.id} className="hover:bg-gray-50">
                              <td className="px-6 py-4 font-medium text-gray-800">{item.name}</td>
                              <td className="px-6 py-4 text-gray-600">
                                  {item.category === 'medicine' ? 'أدوية' : item.category === 'consumable' ? 'مستهلكات' : 'معدات'}
                              </td>
                              <td className="px-6 py-4">
                                  <span className="font-bold text-gray-800">{item.quantity}</span> <span className="text-xs text-gray-500">{item.unit}</span>
                              </td>
                              <td className="px-6 py-4 text-gray-600 text-sm" dir="ltr">{item.expiryDate || '-'}</td>
                              <td className="px-6 py-4">
                                  <span className={`px-2 py-1 rounded text-xs font-medium ${status.color}`}>
                                      {status.label}
                                  </span>
                              </td>
                              <td className="px-6 py-4 text-center flex justify-center gap-2">
                                  <button onClick={() => handleEdit(item)} className="text-blue-500 hover:text-blue-700"><i className="fas fa-edit"></i></button>
                                  <button onClick={() => handleDelete(item.id)} className="text-red-500 hover:text-red-700"><i className="fas fa-trash"></i></button>
                              </td>
                          </tr>
                      );
                  })}
                  {inventory.length === 0 && (
                      <tr><td colSpan={6} className="text-center py-8 text-gray-500">المخزون فارغ</td></tr>
                  )}
              </tbody>
          </table>
      </div>

      <Modal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)} title={editingItem ? 'تعديل عنصر' : 'إضافة عنصر للمخزون'}>
          <form onSubmit={handleSave} className="space-y-4">
              <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">اسم المادة</label>
                  <input name="name" type="text" defaultValue={editingItem?.name} className="w-full px-3 py-2 border rounded-lg bg-white text-gray-900" required />
              </div>
              <div className="grid grid-cols-2 gap-4">
                  <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">الكمية</label>
                      <input name="quantity" type="number" defaultValue={editingItem?.quantity} className="w-full px-3 py-2 border rounded-lg bg-white text-gray-900" required />
                  </div>
                  <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">الوحدة</label>
                      <input name="unit" type="text" defaultValue={editingItem?.unit} placeholder="علبة، حقنة..." className="w-full px-3 py-2 border rounded-lg bg-white text-gray-900" required />
                  </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                  <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">حد التنبيه (Low Stock)</label>
                      <input name="minThreshold" type="number" defaultValue={editingItem?.minThreshold || 5} className="w-full px-3 py-2 border rounded-lg bg-white text-gray-900" />
                  </div>
                  <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">التصنيف</label>
                      <select name="category" defaultValue={editingItem?.category} className="w-full px-3 py-2 border rounded-lg bg-white text-gray-900">
                          <option value="medicine">أدوية</option>
                          <option value="consumable">مستهلكات</option>
                          <option value="equipment">معدات</option>
                      </select>
                  </div>
              </div>
              <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">تاريخ انتهاء الصلاحية</label>
                  <input name="expiryDate" type="date" defaultValue={editingItem?.expiryDate} className="w-full px-3 py-2 border rounded-lg bg-white text-gray-900" />
              </div>
              <button type="submit" className="w-full bg-primary text-white py-2 rounded-xl font-bold">حفظ</button>
          </form>
      </Modal>
    </div>
  );
};
