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

export const BirthLog: React.FC = () => {
  const { birthRecords, addBirthRecord } = useData();
  const { addToast } = useToast();
  const [isModalOpen, setIsModalOpen] = useState(false);

  // Stats
  const totalBirths = birthRecords.length;
  const boys = birthRecords.filter(r => r.gender === 'male').length;
  const girls = birthRecords.filter(r => r.gender === 'female').length;
  const cSections = birthRecords.filter(r => r.deliveryType === 'c-section').length;

  const handleAddBirth = (e: React.FormEvent) => {
    e.preventDefault();
    const form = e.target as HTMLFormElement;
    const motherName = (form.elements.namedItem('motherName') as HTMLInputElement).value;
    const babyName = (form.elements.namedItem('babyName') as HTMLInputElement).value;
    const gender = (form.elements.namedItem('gender') as HTMLSelectElement).value as 'male' | 'female';
    const weight = (form.elements.namedItem('weight') as HTMLInputElement).value;
    const deliveryType = (form.elements.namedItem('deliveryType') as HTMLSelectElement).value as 'natural' | 'c-section';
    const date = (form.elements.namedItem('date') as HTMLInputElement).value;
    const time = (form.elements.namedItem('time') as HTMLInputElement).value;
    const notes = (form.elements.namedItem('notes') as HTMLTextAreaElement).value;

    if (motherName) {
        const newRecord: BirthRecord = {
            id: `B-${Date.now().toString().slice(-4)}`,
            motherName,
            babyName,
            gender,
            weight: Number(weight),
            deliveryType,
            date,
            time,
            notes
        };
        addBirthRecord(newRecord);
        addToast('تم تسجيل حالة الولادة بنجاح', 'success');
        setIsModalOpen(false);
    }
  };

  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={() => setIsModalOpen(true)}
          className="bg-rose-500 hover:bg-rose-600 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>

      {/* Stats */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <StatCard title="إجمالي الولادات" value={totalBirths} icon="fa-baby-carriage" color="primary" />
          <div className="bg-white p-5 rounded-2xl shadow-sm border border-gray-100 flex justify-between items-center">
             <div>
                 <p className="text-gray-500 text-sm font-medium mb-1">ذكور</p>
                 <h3 className="text-2xl font-bold text-blue-600">{boys}</h3>
             </div>
             <i className="fas fa-mars text-blue-200 text-3xl"></i>
          </div>
          <div className="bg-white p-5 rounded-2xl shadow-sm border border-gray-100 flex justify-between items-center">
             <div>
                 <p className="text-gray-500 text-sm font-medium mb-1">إناث</p>
                 <h3 className="text-2xl font-bold text-pink-600">{girls}</h3>
             </div>
             <i className="fas fa-venus text-pink-200 text-3xl"></i>
          </div>
           <div className="bg-white p-5 rounded-2xl shadow-sm border border-gray-100 flex justify-between items-center">
             <div>
                 <p className="text-gray-500 text-sm font-medium mb-1">قيصريات</p>
                 <h3 className="text-2xl font-bold text-purple-600">{cSections}</h3>
             </div>
             <i className="fas fa-procedures text-purple-200 text-3xl"></i>
          </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-right text-sm font-semibold text-gray-600">ملاحظات</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {birthRecords.map((record) => (
                <tr key={record.id} className="hover:bg-gray-50 transition-colors">
                  <td className="px-6 py-4 text-gray-600 text-sm">
                      <div className="font-bold">{record.date}</div>
                      <div className="text-xs">{record.time}</div>
                  </td>
                  <td className="px-6 py-4 font-medium text-gray-800">{record.motherName}</td>
                  <td className="px-6 py-4 text-gray-800">{record.babyName}</td>
                  <td className="px-6 py-4">
                      {record.gender === 'male' ? 
                        <span className="text-blue-600 bg-blue-50 px-2 py-1 rounded-lg text-xs font-bold"><i className="fas fa-mars mr-1"></i> ذكر</span> : 
                        <span className="text-pink-600 bg-pink-50 px-2 py-1 rounded-lg text-xs font-bold"><i className="fas fa-venus mr-1"></i> أنثى</span>
                      }
                  </td>
                  <td className="px-6 py-4 text-gray-600">{record.weight} kg</td>
                  <td className="px-6 py-4">
                      <span className={`px-2 py-1 rounded text-xs font-medium ${record.deliveryType === 'natural' ? 'bg-green-100 text-green-800' : 'bg-purple-100 text-purple-800'}`}>
                          {record.deliveryType === 'natural' ? 'طبيعي' : 'قيصرية'}
                      </span>
                  </td>
                  <td className="px-6 py-4 text-gray-500 text-sm italic">{record.notes || '-'}</td>
                </tr>
              ))}
              {birthRecords.length === 0 && (
                <tr>
                    <td colSpan={7} 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={handleAddBirth}>
            <div className="grid grid-cols-2 gap-4">
                 <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">اسم الأم</label>
                    <input name="motherName" type="text" className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-rose-500 focus:border-rose-500 bg-white text-gray-900" required />
                </div>
                 <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">اسم المولود</label>
                    <input name="babyName" type="text" className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-rose-500 focus:border-rose-500 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">الجنس</label>
                    <select name="gender" className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-rose-500 focus:border-rose-500 bg-white text-gray-900">
                        <option value="male">ذكر</option>
                        <option value="female">أنثى</option>
                    </select>
                </div>
                <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">الوزن (kg)</label>
                    <input name="weight" type="number" step="0.1" className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-rose-500 focus:border-rose-500 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">تاريخ الولادة</label>
                    <input name="date" type="date" defaultValue={new Date().toISOString().split('T')[0]} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-rose-500 focus:border-rose-500 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-rose-500 focus:border-rose-500 bg-white text-gray-900" required />
                </div>
            </div>

            <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">نوع الولادة</label>
                <select name="deliveryType" className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-rose-500 focus:border-rose-500 bg-white text-gray-900">
                    <option value="natural">طبيعي (Natural)</option>
                    <option value="c-section">قيصرية (C-Section)</option>
                </select>
            </div>
             <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">ملاحظات</label>
                <textarea name="notes" rows={2} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-rose-500 focus:border-rose-500 bg-white text-gray-900"></textarea>
            </div>
            
            <button type="submit" className="w-full bg-rose-500 text-white py-2.5 rounded-xl font-bold hover:bg-rose-600 transition-colors">
                حفظ السجل
            </button>
        </form>
      </Modal>
    </div>
  );
};
