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

export const DoctorDashboard: React.FC = () => {
  const navigate = useNavigate();
  const { patients, appointments, invoices, clinicType, inventory } = useData();
  const { addToast } = useToast();

  // Calculations
  const totalPatients = patients.length;
  const criticalPatients = patients.filter(p => p.status === 'critical').length;
  const todaysIncome = invoices
    .filter(inv => inv.date === new Date().toISOString().split('T')[0] && inv.status === 'paid')
    .reduce((sum, inv) => sum + inv.amount, 0);
  
  const todayAppointments = appointments.filter(app => app.date === new Date().toISOString().split('T')[0]);

  // Inventory Alerts
  const lowStockItems = inventory.filter(item => item.quantity <= item.minThreshold);

  // Dynamic Content based on ClinicType
  let clinicIcon = 'fa-user-md';
  let clinicTitle = 'عيادة الطب العام';
  if (clinicType === 'dental') {
    clinicIcon = 'fa-tooth';
    clinicTitle = 'عيادة الأسنان';
  } else if (clinicType === 'obgyn') {
    clinicIcon = 'fa-baby';
    clinicTitle = 'عيادة النسائية والتوليد';
  } else if (clinicType === 'vet') {
    clinicIcon = 'fa-paw';
    clinicTitle = 'العيادة البيطرية';
  }

  const handleStartCheckup = (patientName: string) => {
      const patient = patients.find(p => p.name === patientName);
      if (patient) {
          navigate(`/doctor/patients/${patient.id}`);
      } else {
          addToast('لم يتم العثور على ملف المريض، يرجى إنشاؤه أولاً', 'error');
          navigate('/doctor/patients');
      }
  };

  return (
    <div className="space-y-6">
      <header className="mb-6 flex justify-between items-center">
        <div>
          <h2 className="text-2xl font-bold text-gray-800">لوحة التحكم</h2>
          <p className="text-gray-500">أهلاً بك د. أحمد في {clinicTitle}</p>
        </div>
        <div className="bg-white px-4 py-2 rounded-xl shadow-sm border border-gray-100 flex items-center gap-2 text-primary font-bold">
            <i className={`fas ${clinicIcon}`}></i>
            <span className="uppercase text-sm">{clinicType} Mode</span>
        </div>
      </header>

      {/* Dynamic Inventory Alerts */}
      {lowStockItems.length > 0 && (
        <div className="bg-red-50 border border-red-200 rounded-xl p-4 flex items-start gap-3 animate-pulse">
            <i className="fas fa-exclamation-triangle text-red-500 mt-1"></i>
            <div className="flex-1">
                <h4 className="font-bold text-red-800">تنبيه مخزون منخفض</h4>
                <p className="text-sm text-red-700 mb-2">
                    لديك {lowStockItems.length} مواد وصلت للحد الأدنى: 
                    {lowStockItems.slice(0, 3).map(i => <span key={i.id} className="font-bold mx-1">{i.name}</span>)}
                    {lowStockItems.length > 3 && '...'}
                </p>
                <button onClick={() => navigate('/doctor/inventory')} className="text-xs bg-red-100 hover:bg-red-200 text-red-800 px-3 py-1 rounded-lg font-bold transition-colors">
                    إدارة المخزون
                </button>
            </div>
        </div>
      )}

      {/* Specialty Specific Alerts */}
      {clinicType === 'obgyn' && (
        <div className="bg-pink-50 border border-pink-200 rounded-xl p-4 flex items-start gap-3">
            <i className="fas fa-heartbeat text-pink-500 mt-1"></i>
            <div>
            <h4 className="font-bold text-pink-800">حالات ولادة قريبة</h4>
            <p className="text-sm text-pink-700">لديك 2 مرضى تجاوزوا الأسبوع 38 من الحمل. يرجى المتابعة.</p>
            </div>
        </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <StatCard title="مرضى اليوم" value={todayAppointments.length} icon="fa-calendar-day" color="primary" />
        <StatCard 
            title={clinicType === 'dental' ? 'عمليات جراحية' : clinicType === 'obgyn' ? 'حالات حمل نشطة' : 'حالات حرجة'} 
            value={clinicType === 'obgyn' ? 12 : criticalPatients} 
            icon={clinicType === 'dental' ? 'fa-syringe' : clinicType === 'obgyn' ? 'fa-baby-carriage' : 'fa-procedures'} 
            color="danger" 
        />
        <StatCard title="إجمالي المرضى" value={totalPatients} icon="fa-users" color="info" />
        <StatCard title="دخل اليوم" value={`${todaysIncome.toLocaleString()} $`} icon="fa-money-bill" color="success" />
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Appointments List */}
        <div className="lg:col-span-2 bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
          <div className="flex justify-between items-center mb-6">
            <h3 className="text-lg font-bold text-gray-800">مواعيد اليوم</h3>
            <button className="text-primary text-sm font-medium" onClick={() => navigate('/doctor/appointments')}>عرض الجدول</button>
          </div>
          <div className="space-y-4">
            {todayAppointments.map((app) => (
              <div key={app.id} className="flex items-center justify-between p-4 bg-gray-50 rounded-xl border border-gray-100">
                <div className="flex items-center gap-4">
                  <div className="w-12 h-12 rounded-full bg-white border-2 border-primary flex items-center justify-center font-bold text-gray-700 shadow-sm">
                    {app.time}
                  </div>
                  <div>
                    <h4 className="font-bold text-gray-800">{app.patientName}</h4>
                    <p className="text-sm text-gray-500">{app.type}</p>
                  </div>
                </div>
                <button 
                  onClick={() => handleStartCheckup(app.patientName)} 
                  className="px-4 py-2 text-sm bg-white border border-gray-200 text-gray-700 rounded-lg hover:bg-primary hover:text-white transition-colors"
                >
                  بدء الكشف
                </button>
              </div>
            ))}
            {todayAppointments.length === 0 && (
                <p className="text-gray-500 text-center py-4">لا توجد مواعيد مسجلة لهذا اليوم</p>
            )}
          </div>
        </div>

        {/* Quick Actions */}
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
          <h3 className="text-lg font-bold text-gray-800 mb-6">إجراءات سريعة</h3>
          <div className="grid grid-cols-2 gap-4">
            <button 
              onClick={() => navigate('/doctor/patients')}
              className="p-4 rounded-xl bg-blue-50 text-primary hover:bg-primary hover:text-white transition-all flex flex-col items-center gap-2"
            >
              <i className="fas fa-user-plus text-2xl"></i>
              <span className="text-sm font-semibold">مريض جديد</span>
            </button>
            <button 
              onClick={() => navigate('/doctor/finance')}
              className="p-4 rounded-xl bg-purple-50 text-purple-600 hover:bg-purple-600 hover:text-white transition-all flex flex-col items-center gap-2"
            >
              <i className="fas fa-file-invoice text-2xl"></i>
              <span className="text-sm font-semibold">إصدار فاتورة</span>
            </button>
            
            {/* Specialty specific buttons */}
            {clinicType === 'dental' ? (
                 <button 
                    onClick={() => navigate('/doctor/dental-lab')} 
                    className="p-4 rounded-xl bg-yellow-50 text-yellow-600 hover:bg-yellow-600 hover:text-white transition-all flex flex-col items-center gap-2"
                 >
                    <i className="fas fa-teeth text-2xl"></i>
                    <span className="text-sm font-semibold">المعمل</span>
                 </button>
            ) : clinicType === 'obgyn' ? (
                <button 
                    onClick={() => navigate('/doctor/birth-log')}
                    className="p-4 rounded-xl bg-pink-50 text-pink-600 hover:bg-pink-600 hover:text-white transition-all flex flex-col items-center gap-2"
                >
                    <i className="fas fa-baby-carriage text-2xl"></i>
                    <span className="text-sm font-semibold">سجل الولادات</span>
                 </button>
            ) : (
                <button 
                    onClick={() => navigate('/doctor/reports')}
                    className="p-4 rounded-xl bg-green-50 text-success hover:bg-success hover:text-white transition-all flex flex-col items-center gap-2"
                >
                    <i className="fas fa-file-medical text-2xl"></i>
                    <span className="text-sm font-semibold">تقرير طبي</span>
                </button>
            )}
            
            <button 
               onClick={() => window.print()}
               className="p-4 rounded-xl bg-gray-50 text-gray-600 hover:bg-gray-600 hover:text-white transition-all flex flex-col items-center gap-2"
            >
              <i className="fas fa-print text-2xl"></i>
              <span className="text-sm font-semibold">طباعة</span>
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};
