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

export const Appointments: React.FC = () => {
  const [viewMode, setViewMode] = useState<'list' | 'calendar'>('list');
  const [filter, setFilter] = useState('all');
  const [isModalOpen, setIsModalOpen] = useState(false);
  
  const { appointments, addAppointment, updateAppointmentStatus } = useData();
  const { addToast } = useToast();

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'confirmed': return 'bg-green-100 text-green-800';
      case 'pending': return 'bg-yellow-100 text-yellow-800';
      case 'cancelled': return 'bg-red-100 text-red-800';
      case 'completed': return 'bg-blue-100 text-blue-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'confirmed': return 'مؤكد';
      case 'pending': return 'قيد الانتظار';
      case 'cancelled': return 'ملغي';
      case 'completed': return 'مكتمل';
      default: return status;
    }
  };

  const handleAddAppointment = (e: React.FormEvent) => {
    e.preventDefault();
    const form = e.target as HTMLFormElement;
    const name = (form.elements.namedItem('patientName') as HTMLInputElement).value;
    const date = (form.elements.namedItem('date') as HTMLInputElement).value;
    const time = (form.elements.namedItem('time') as HTMLInputElement).value;
    const type = (form.elements.namedItem('type') as HTMLSelectElement).value;

    if (name && date && time) {
        const newAppointment: Appointment = {
            id: Date.now().toString(),
            patientName: name,
            date,
            time,
            type,
            status: 'pending'
        };
        addAppointment(newAppointment);
        addToast('تم حجز الموعد بنجاح', 'success');
        setIsModalOpen(false);
    }
  };

  const handleStatusUpdate = (id: string, newStatus: 'confirmed' | 'cancelled') => {
    updateAppointmentStatus(id, newStatus);
    addToast(newStatus === 'confirmed' ? 'تم تأكيد الموعد' : 'تم إلغاء الموعد', newStatus === 'confirmed' ? 'success' : 'error');
  };

  const filteredAppointments = filter === 'all' 
    ? appointments 
    : appointments.filter(a => a.status === filter);

  // Calendar Logic
  const renderCalendar = () => {
    const today = new Date();
    const currentMonth = today.getMonth();
    const currentYear = today.getFullYear();
    const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
    const firstDay = new Date(currentYear, currentMonth, 1).getDay(); // 0 = Sunday
    
    // Adjust for RTL/Monday start if needed, simplified here for Sunday start
    
    const days = [];
    // Padding
    for (let i = 0; i < firstDay; i++) {
        days.push(<div key={`empty-${i}`} className="h-32 bg-gray-50/50 border border-gray-100"></div>);
    }
    
    // Days
    for (let d = 1; d <= daysInMonth; d++) {
        const dateStr = `${currentYear}-${String(currentMonth + 1).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
        const dayApps = appointments.filter(a => a.date === dateStr);
        
        days.push(
            <div key={d} className="h-32 bg-white border border-gray-100 p-2 overflow-hidden hover:bg-gray-50 transition-colors relative">
                <span className={`text-sm font-bold ${d === today.getDate() ? 'bg-primary text-white w-6 h-6 rounded-full flex items-center justify-center' : 'text-gray-700'}`}>{d}</span>
                <div className="mt-1 space-y-1 overflow-y-auto max-h-[80%]">
                    {dayApps.map(app => (
                        <div key={app.id} className={`text-[10px] px-1 py-0.5 rounded truncate ${getStatusColor(app.status)}`}>
                           {app.time} - {app.patientName}
                        </div>
                    ))}
                </div>
            </div>
        );
    }

    return (
        <div className="grid grid-cols-7 gap-px bg-gray-200 rounded-2xl overflow-hidden border border-gray-200">
            {['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'].map(day => (
                <div key={day} className="bg-gray-100 p-2 text-center text-xs font-bold text-gray-500">{day}</div>
            ))}
            {days}
        </div>
    );
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col md:flex-row justify-between items-center gap-4">
        <div>
          <h2 className="text-2xl font-bold text-gray-800">المواعيد</h2>
          <p className="text-gray-500">جدول مواعيد المرضى والزيارات</p>
        </div>
        <div className="flex gap-2">
           <div className="flex bg-gray-100 p-1 rounded-lg">
                <button 
                    onClick={() => setViewMode('list')}
                    className={`px-3 py-1.5 rounded-md text-sm transition-all ${viewMode === 'list' ? 'bg-white shadow text-gray-800' : 'text-gray-500 hover:text-gray-700'}`}
                >
                    <i className="fas fa-list"></i> قائمة
                </button>
                <button 
                     onClick={() => setViewMode('calendar')}
                     className={`px-3 py-1.5 rounded-md text-sm transition-all ${viewMode === 'calendar' ? 'bg-white shadow text-gray-800' : 'text-gray-500 hover:text-gray-700'}`}
                >
                    <i className="fas fa-calendar-alt"></i> تقويم
                </button>
           </div>
          <button 
            onClick={() => setIsModalOpen(true)}
            className="bg-primary hover:bg-primary-dark text-white px-4 py-2 rounded-lg shadow-md transition-colors"
          >
            <i className="fas fa-plus ml-2"></i> موعد جديد
          </button>
        </div>
      </div>

      {viewMode === 'list' && (
        <>
            <div className="flex gap-2 overflow-x-auto pb-2">
                {['all', 'confirmed', 'pending', 'completed'].map(status => (
                <button 
                    key={status}
                    onClick={() => setFilter(status)}
                    className={`px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition-colors ${
                    filter === status 
                    ? 'bg-primary text-white' 
                    : 'bg-white text-gray-600 hover:bg-gray-50 border border-gray-200'
                    }`}
                >
                    {status === 'all' ? 'الكل' : getStatusText(status)}
                </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">النوع</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">
                    {filteredAppointments.map((app) => (
                        <tr key={app.id} className="hover:bg-gray-50 transition-colors">
                        <td className="px-6 py-4 font-medium text-gray-800">{app.patientName}</td>
                        <td className="px-6 py-4 text-gray-600">{app.date}</td>
                        <td className="px-6 py-4 text-gray-600 font-semibold">{app.time}</td>
                        <td className="px-6 py-4 text-gray-600">{app.type}</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 ${getStatusColor(app.status)}`}>
                            {getStatusText(app.status)}
                            </span>
                        </td>
                        <td className="px-6 py-4 text-center">
                            <div className="flex justify-center gap-2">
                            <button 
                                onClick={() => handleStatusUpdate(app.id, 'confirmed')}
                                disabled={app.status !== 'pending'}
                                className={`w-8 h-8 rounded-lg flex items-center justify-center transition-colors ${app.status === 'pending' ? 'bg-green-50 text-success hover:bg-success hover:text-white' : 'bg-gray-100 text-gray-400 cursor-not-allowed'}`} 
                                title="تأكيد"
                            >
                                <i className="fas fa-check"></i>
                            </button>
                            <button 
                                onClick={() => handleStatusUpdate(app.id, 'cancelled')}
                                disabled={app.status === 'cancelled'}
                                className={`w-8 h-8 rounded-lg flex items-center justify-center transition-colors ${app.status !== 'cancelled' ? 'bg-red-50 text-danger hover:bg-danger hover:text-white' : 'bg-gray-100 text-gray-400 cursor-not-allowed'}`} 
                                title="إلغاء"
                            >
                                <i className="fas fa-times"></i>
                            </button>
                            </div>
                        </td>
                        </tr>
                    ))}
                    {filteredAppointments.length === 0 && (
                        <tr>
                            <td colSpan={6} className="text-center py-8 text-gray-500">لا توجد مواعيد في هذه القائمة</td>
                        </tr>
                    )}
                    </tbody>
                </table>
                </div>
            </div>
        </>
      )}

      {viewMode === 'calendar' && (
          <div className="animate-fade-in">
              {renderCalendar()}
              <div className="mt-4 flex gap-4 justify-center text-xs text-gray-500">
                  <span className="flex items-center gap-1"><div className="w-3 h-3 bg-green-100 rounded"></div> مؤكد</span>
                  <span className="flex items-center gap-1"><div className="w-3 h-3 bg-yellow-100 rounded"></div> انتظار</span>
                  <span className="flex items-center gap-1"><div className="w-3 h-3 bg-blue-100 rounded"></div> مكتمل</span>
              </div>
          </div>
      )}

      {/* New Appointment Modal */}
      <Modal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)} title="حجز موعد جديد">
        <form className="space-y-4" onSubmit={handleAddAppointment}>
            <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">اسم المريض</label>
                <input name="patientName" type="text" 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 className="grid grid-cols-2 gap-4">
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">التاريخ</label>
                    <input name="date" type="date" 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="time" type="time" 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>
            <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 border-gray-300 rounded-lg focus:ring-primary focus:border-primary bg-white text-gray-900">
                    <option value="كشف دوري">كشف دوري</option>
                    <option value="استشارة">استشارة</option>
                    <option value="متابعة">متابعة</option>
                    <option value="جراحة">جراحة</option>
                </select>
            </div>
            <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">ملاحظات</label>
                <textarea className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary bg-white text-gray-900" rows={2}></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">
                تأكيد الحجز
            </button>
        </form>
      </Modal>
    </div>
  );
};
