
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Modal } from '../../components/Modal';
import { useToast } from '../../context/ToastContext';
import { useData } from '../../context/DataContext';

export const PatientList: React.FC = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [showAdvancedSearch, setShowAdvancedSearch] = useState(false);
  const [advancedFilters, setAdvancedFilters] = useState({
      status: 'all',
      dateFrom: '',
      dateTo: '',
      gender: 'all'
  });

  const [isModalOpen, setIsModalOpen] = useState(false);
  const { patients, addPatient, deletePatient } = useData();
  const navigate = useNavigate();
  const { addToast } = useToast();

  const filteredPatients = patients.filter(p => {
    const basicMatch = p.name.includes(searchTerm) || p.phone.includes(searchTerm);
    
    if (!showAdvancedSearch) return basicMatch;

    const statusMatch = advancedFilters.status === 'all' || p.status === advancedFilters.status;
    const genderMatch = advancedFilters.gender === 'all' || p.gender === advancedFilters.gender;
    // Date mock logic (assuming lastVisit is relevant)
    const dateMatch = (!advancedFilters.dateFrom || p.lastVisit >= advancedFilters.dateFrom) &&
                      (!advancedFilters.dateTo || p.lastVisit <= advancedFilters.dateTo);

    return basicMatch && statusMatch && genderMatch && dateMatch;
  });

  const handleAddPatient = (e: React.FormEvent) => {
    e.preventDefault();
    const form = e.target as HTMLFormElement;
    const name = (form.elements.namedItem('name') as HTMLInputElement).value;
    const phone = (form.elements.namedItem('phone') as HTMLInputElement).value;
    const age = (form.elements.namedItem('age') as HTMLInputElement).value;

    if (name && phone) {
      const newPatient = {
        id: Date.now().toString(),
        name,
        phone,
        age: parseInt(age) || 0,
        diagnosis: 'غير محدد',
        lastVisit: new Date().toISOString().split('T')[0],
        status: 'regular' as const
      };
      
      addPatient(newPatient);
      addToast('تم إضافة المريض بنجاح', 'success');
      setIsModalOpen(false);
    }
  };

  const handleDelete = (id: string, name: string) => {
      if(window.confirm(`هل أنت متأكد من حذف ملف المريض: ${name}؟`)) {
          deletePatient(id);
          addToast('تم حذف ملف المريض', 'error');
      }
  };

  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>
        <button 
            onClick={() => setIsModalOpen(true)}
            className="bg-primary hover:bg-primary-dark text-white px-4 py-2.5 rounded-xl shadow-md transition-colors whitespace-nowrap"
          >
            <i className="fas fa-user-plus ml-2"></i>
            إضافة مريض
        </button>
      </div>

      {/* Search Bar */}
      <div className="bg-white p-4 rounded-2xl shadow-sm border border-gray-100">
          <div className="flex gap-2">
            <div className="relative flex-1">
                <input 
                type="text" 
                placeholder="بحث بالاسم أو الهاتف..." 
                className="w-full pl-4 pr-10 py-2.5 rounded-xl border border-gray-200 focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary bg-white text-gray-900"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                />
                <i className="fas fa-search absolute left-3 top-3.5 text-gray-400"></i>
            </div>
            <button 
                onClick={() => setShowAdvancedSearch(!showAdvancedSearch)}
                className={`px-4 py-2 rounded-xl border transition-colors ${showAdvancedSearch ? 'bg-blue-50 border-primary text-primary' : 'bg-gray-50 border-gray-200 text-gray-600'}`}
            >
                <i className="fas fa-filter"></i>
            </button>
          </div>

          {/* Advanced Search Panel */}
          {showAdvancedSearch && (
              <div className="mt-4 pt-4 border-t border-gray-100 grid grid-cols-1 md:grid-cols-4 gap-4 animate-fade-in">
                  <div>
                      <label className="block text-xs font-bold text-gray-600 mb-1">الحالة</label>
                      <select 
                        className="w-full p-2 border rounded-lg text-sm bg-white text-gray-900"
                        value={advancedFilters.status}
                        onChange={e => setAdvancedFilters({...advancedFilters, status: e.target.value})}
                      >
                          <option value="all">الكل</option>
                          <option value="regular">عادي</option>
                          <option value="critical">حرج</option>
                          <option value="pregnant">حامل</option>
                      </select>
                  </div>
                  <div>
                      <label className="block text-xs font-bold text-gray-600 mb-1">الجنس</label>
                      <select 
                        className="w-full p-2 border rounded-lg text-sm bg-white text-gray-900"
                        value={advancedFilters.gender}
                        onChange={e => setAdvancedFilters({...advancedFilters, gender: e.target.value})}
                      >
                          <option value="all">الكل</option>
                          <option value="male">ذكر</option>
                          <option value="female">أنثى</option>
                      </select>
                  </div>
                  <div>
                      <label className="block text-xs font-bold text-gray-600 mb-1">من تاريخ</label>
                      <input 
                        type="date" 
                        className="w-full p-2 border rounded-lg text-sm bg-white text-gray-900"
                        value={advancedFilters.dateFrom}
                        onChange={e => setAdvancedFilters({...advancedFilters, dateFrom: e.target.value})}
                      />
                  </div>
                  <div>
                      <label className="block text-xs font-bold text-gray-600 mb-1">إلى تاريخ</label>
                      <input 
                        type="date" 
                        className="w-full p-2 border rounded-lg text-sm bg-white text-gray-900"
                        value={advancedFilters.dateTo}
                        onChange={e => setAdvancedFilters({...advancedFilters, dateTo: e.target.value})}
                      />
                  </div>
              </div>
          )}
      </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-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">
              {filteredPatients.map((patient) => (
                <tr key={patient.id} className="hover:bg-gray-50 transition-colors">
                  <td className="px-6 py-4 font-medium text-gray-800">{patient.name}</td>
                  <td className="px-6 py-4 text-gray-600">{patient.age}</td>
                  <td className="px-6 py-4 text-gray-600" dir="ltr">{patient.phone}</td>
                  <td className="px-6 py-4 text-gray-600">{patient.diagnosis}</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 ${
                      patient.status === 'pregnant' ? 'bg-pink-100 text-pink-800' :
                      patient.status === 'critical' ? 'bg-red-100 text-red-800' :
                      'bg-gray-100 text-gray-800'
                    }`}>
                      {patient.status === 'pregnant' ? 'حامل' : patient.status === 'critical' ? 'حرج' : 'عادي'}
                    </span>
                  </td>
                  <td className="px-6 py-4 text-gray-600">{patient.lastVisit}</td>
                  <td className="px-6 py-4 text-center">
                    <div className="flex justify-center gap-2">
                      <button 
                        onClick={() => navigate(`/doctor/patients/${patient.id}`)}
                        className="w-8 h-8 rounded-lg bg-blue-50 text-primary hover:bg-primary hover:text-white transition-colors flex items-center justify-center" 
                        title="الملف الطبي"
                      >
                        <i className="fas fa-file-medical-alt"></i>
                      </button>
                      <button 
                        onClick={() => handleDelete(patient.id, patient.name)}
                        className="w-8 h-8 rounded-lg bg-red-50 text-danger hover:bg-danger hover:text-white transition-colors flex items-center justify-center" 
                        title="حذف الملف"
                      >
                        <i className="fas fa-trash"></i>
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
              {filteredPatients.length === 0 && (
                <tr>
                    <td colSpan={7} className="text-center py-8 text-gray-500">لا يوجد مرضى مطابقين للبحث</td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Add Patient Modal */}
      <Modal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)} title="إضافة مريض جديد">
        <form className="space-y-4" onSubmit={handleAddPatient}>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">الاسم الكامل</label>
            <input name="name" type="text" 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="age" type="number" className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary bg-white text-gray-900" />
            </div>
            <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 focus:ring-primary focus:border-primary bg-white text-gray-900">
                    <option>ذكر</option>
                    <option>أنثى</option>
                </select>
            </div>
          </div>
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">رقم الهاتف</label>
            <input name="phone" type="tel" className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary bg-white text-gray-900" dir="ltr" required />
          </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={3}></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>
  );
};
