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

export const Services: React.FC = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingService, setEditingService] = useState<Service | null>(null);
  
  const { services, addService, updateService, deleteService } = useData();
  const { addToast } = useToast();

  const handleSaveService = (e: React.FormEvent) => {
    e.preventDefault();
    const form = e.target as HTMLFormElement;
    const name = (form.elements.namedItem('name') as HTMLInputElement).value;
    const price = (form.elements.namedItem('price') as HTMLInputElement).value;
    const description = (form.elements.namedItem('description') as HTMLTextAreaElement).value;

    if (name && price) {
        if (editingService) {
             updateService({ ...editingService, name, price: Number(price), description });
             addToast('تم تحديث الخدمة بنجاح', 'success');
        } else {
             const newService: Service = {
                id: Date.now().toString(),
                name,
                price: Number(price),
                description
            };
            addService(newService);
            addToast('تم إضافة الخدمة بنجاح', 'success');
        }
        setIsModalOpen(false);
        setEditingService(null);
    }
  };

  const handleEdit = (service: Service) => {
    setEditingService(service);
    setIsModalOpen(true);
  };

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

  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={() => { setEditingService(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="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {services.map((service) => (
            <div key={service.id} className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6 flex flex-col justify-between hover:border-primary transition-colors">
                <div>
                    <div className="flex justify-between items-start mb-2">
                        <h3 className="font-bold text-lg text-gray-800">{service.name}</h3>
                        <span className="bg-green-50 text-success font-bold px-3 py-1 rounded-lg text-sm">
                            {service.price} $
                        </span>
                    </div>
                    <p className="text-gray-500 text-sm mb-4">
                        {service.description || 'لا يوجد وصف متاح'}
                    </p>
                </div>
                <div className="flex justify-end gap-2 pt-4 border-t border-gray-50">
                    <button 
                      onClick={() => handleEdit(service)}
                      className="text-gray-400 hover:text-primary transition-colors text-sm"
                    >
                        <i className="fas fa-edit ml-1"></i> تعديل
                    </button>
                    <button 
                      onClick={() => handleDelete(service.id)}
                      className="text-gray-400 hover:text-danger transition-colors text-sm"
                    >
                        <i className="fas fa-trash ml-1"></i> حذف
                    </button>
                </div>
            </div>
        ))}
      </div>

      {/* Add/Edit Service Modal */}
      <Modal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)} title={editingService ? "تعديل الخدمة" : "إضافة خدمة طبية جديدة"}>
        <form className="space-y-4" onSubmit={handleSaveService}>
            <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">اسم الخدمة</label>
                <input 
                  name="name" 
                  type="text" 
                  defaultValue={editingService?.name}
                  placeholder="مثال: كشف أسنان" 
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary bg-white text-gray-900" 
                  required
                />
            </div>
            <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">السعر ($)</label>
                <input 
                  name="price" 
                  type="number" 
                  defaultValue={editingService?.price}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary bg-white text-gray-900" 
                  required
                />
            </div>
            <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">وصف الخدمة</label>
                <textarea 
                  name="description"
                  defaultValue={editingService?.description}
                  rows={3} 
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary bg-white text-gray-900"
                ></textarea>
            </div>
            <button type="submit" className="w-full bg-primary text-white py-2.5 rounded-xl font-bold hover:bg-primary-dark transition-colors">
                {editingService ? "حفظ التعديلات" : "حفظ الخدمة"}
            </button>
        </form>
      </Modal>
    </div>
  );
};
