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

export const DentalLab: React.FC = () => {
  const { labOrders, addLabOrder, updateLabOrder } = useData();
  const { addToast } = useToast();
  const [isModalOpen, setIsModalOpen] = useState(false);

  const handleCreateOrder = (e: React.FormEvent) => {
    e.preventDefault();
    const form = e.target as HTMLFormElement;
    const patientName = (form.elements.namedItem('patientName') as HTMLInputElement).value;
    const item = (form.elements.namedItem('item') as HTMLSelectElement).value;
    const labName = (form.elements.namedItem('labName') as HTMLInputElement).value;
    const shade = (form.elements.namedItem('shade') as HTMLInputElement).value;
    const deliveryDate = (form.elements.namedItem('deliveryDate') as HTMLInputElement).value;

    if (patientName && item) {
        const newOrder: LabOrder = {
            id: `L-${Date.now().toString().slice(-4)}`,
            patientName,
            item,
            labName,
            shade,
            sentDate: new Date().toISOString().split('T')[0],
            deliveryDate,
            status: 'sent'
        };
        addLabOrder(newOrder);
        addToast('تم إرسال الطلب للمعمل', 'success');
        setIsModalOpen(false);
    }
  };

  const handleStatusChange = (order: LabOrder) => {
      let nextStatus: LabOrder['status'] = 'in_progress';
      if (order.status === 'sent') nextStatus = 'in_progress';
      else if (order.status === 'in_progress') nextStatus = 'received';
      else return;

      updateLabOrder({ ...order, status: nextStatus });
      addToast('تم تحديث حالة الطلب', 'success');
  };

  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">إدارة المعمل (Dental Lab)</h2>
          <p className="text-gray-500">متابعة طلبات التركيبات والأطقم مع المعامل الخارجية</p>
        </div>
        <button 
          onClick={() => setIsModalOpen(true)}
          className="bg-emerald-600 hover:bg-emerald-700 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">
        <div className="overflow-x-auto">
          <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">اللون (Shade)</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">
              {labOrders.map((order) => (
                <tr key={order.id} className="hover:bg-gray-50 transition-colors">
                  <td className="px-6 py-4 font-mono text-sm text-gray-500">{order.id}</td>
                  <td className="px-6 py-4 font-medium text-gray-800">{order.patientName}</td>
                  <td className="px-6 py-4 text-gray-600">{order.item}</td>
                  <td className="px-6 py-4 text-gray-600 font-bold">{order.shade}</td>
                  <td className="px-6 py-4 text-gray-600">{order.labName}</td>
                  <td className="px-6 py-4 text-gray-600">{order.deliveryDate}</td>
                  <td className="px-6 py-4">
                    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                      order.status === 'received' ? 'bg-green-100 text-green-800' :
                      order.status === 'in_progress' ? 'bg-blue-100 text-blue-800' :
                      'bg-yellow-100 text-yellow-800'
                    }`}>
                      {order.status === 'received' ? 'تم الاستلام' : order.status === 'in_progress' ? 'قيد التنفيذ' : 'تم الإرسال'}
                    </span>
                  </td>
                  <td className="px-6 py-4 text-center">
                    {order.status !== 'received' && (
                        <button 
                            onClick={() => handleStatusChange(order)}
                            className="text-xs bg-gray-100 hover:bg-emerald-600 hover:text-white text-gray-600 px-3 py-1 rounded-lg transition-colors"
                        >
                            <i className="fas fa-arrow-up mr-1"></i> تحديث الحالة
                        </button>
                    )}
                  </td>
                </tr>
              ))}
              {labOrders.length === 0 && (
                <tr>
                    <td colSpan={8} className="text-center py-8 text-gray-500">لا توجد طلبات معمل حالياً</td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      <Modal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)} title="طلب معمل جديد">
        <form className="space-y-4" onSubmit={handleCreateOrder}>
            <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">اسم المريض</label>
                <input name="patientName" type="text" className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-emerald-500 focus:border-emerald-500 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>
                    <select name="item" className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-emerald-500 focus:border-emerald-500 bg-white text-gray-900">
                        <option>Zirconia Crown</option>
                        <option>E-Max Veneer</option>
                        <option>PFM Crown</option>
                        <option>Partial Denture</option>
                        <option>Night Guard</option>
                    </select>
                </div>
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">اللون (Shade)</label>
                    <input name="shade" type="text" placeholder="e.g. A1, A2, B1" className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-emerald-500 focus:border-emerald-500 bg-white text-gray-900" required />
                </div>
            </div>
            <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">اسم المعمل</label>
                <input name="labName" type="text" className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-emerald-500 focus:border-emerald-500 bg-white text-gray-900" required />
            </div>
            <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">تاريخ التسليم المتوقع</label>
                <input name="deliveryDate" type="date" className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-emerald-500 focus:border-emerald-500 bg-white text-gray-900" required />
            </div>
            <button type="submit" className="w-full bg-emerald-600 text-white py-2.5 rounded-xl font-bold hover:bg-emerald-700 transition-colors">
                إرسال الطلب
            </button>
        </form>
      </Modal>
    </div>
  );
};
