/* global React, Icons, AppContext */
const { useState, useContext, useMemo, createElement: h, Fragment } = React;

// ==================== Dashboard ====================
function Dashboard() {
  const { toast, setScreen, appointments, patients, invoices, inventory, doctors, clinicName } = useContext(AppContext);

  // Use real data with fallback to window globals
  const allAppts   = (appointments && appointments.length) ? appointments : (window.APPOINTMENTS || []);
  const allPatients= (patients && patients.length)         ? patients     : (window.PATIENTS || []);
  const allInvoices= (invoices && invoices.length)         ? invoices     : (window.INVOICES || []);
  const allInventory=(inventory && inventory.length)       ? inventory    : (window.INVENTORY || []);
  const allDoctors = (doctors && doctors.length)           ? doctors      : (window.DOCTORS || []);

  // Today's date string YYYY-MM-DD
  const todayStr = new Date().toISOString().split('T')[0];
  const todayAppts = allAppts.filter(a => a.date === todayStr);
  const completed  = todayAppts.filter(a => a.status === 'confirmed' || a.status === 'in-progress' || a.status === 'done').length;
  const pending    = allAppts.filter(a => a.status === 'pending').length;

  // Revenue today from paid invoices
  const todayRevenue = allInvoices
    .filter(i => i.date === todayStr)
    .reduce((s, i) => s + (i.paid || 0), 0);

  // New patients this month
  const thisMonth = todayStr.substring(0, 7);
  const newPatientsMonth = allPatients.filter(p => (p.created_at || '').startsWith(thisMonth)).length;

  // Greeting
  const hour = new Date().getHours();
  const greeting = hour < 12 ? 'صباح الخير' : hour < 18 ? 'مساء الخير' : 'مساء النور';
  const dateLabel = new Date().toLocaleDateString('ar-EG', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });

  const kpis = [
    { label: 'مواعيد اليوم',      value: todayAppts.length, trend: `${completed} مكتمل`, trendUp: true,  icon: Icons.Calendar,   color: 'var(--accent)',   soft: 'var(--accent-soft)' },
    { label: 'إيرادات اليوم',     value: todayRevenue.toLocaleString('ar-EG'), suffix: 'ج.م', trend: 'محصّل اليوم', trendUp: true, icon: Icons.DollarSign, color: 'var(--success)', soft: 'var(--success-soft)' },
    { label: 'مرضى جدد (الشهر)', value: newPatientsMonth, trend: `إجمالي: ${allPatients.length} مريض`, trendUp: newPatientsMonth > 0, icon: Icons.UserPlus, color: 'var(--info)', soft: 'var(--info-soft)' },
    { label: 'مواعيد معلقة',     value: pending, trend: 'في انتظار التأكيد', trendUp: false, icon: Icons.Clock, color: 'var(--warning)', soft: 'var(--warning-soft)' },
  ];

  return h('div', { className: 'fade-in' },
    h('div', { className: 'page-header' },
      h('div', null,
        h('div', { className: 'page-title' }, greeting + '، ' + (clinicName || 'مدير العيادة') + ' 👋'),
        h('div', { className: 'page-subtitle' }, dateLabel + ' · ' + (todayAppts.length ? `${todayAppts.length} مواعيد اليوم` : 'لا توجد مواعيد اليوم')),
      ),
      h('div', { className: 'flex gap-8' },
        h('button', { className: 'btn outline', onClick: () => setScreen('reports') },
          h(Icons.Download, { size: 16 }), 'تصدير التقرير',
        ),
        h('button', { className: 'btn primary', onClick: () => setScreen('new-appointment') },
          h(Icons.Plus, { size: 16 }), 'موعد جديد',
        ),
      ),
    ),
    h('div', { className: 'page-content' },
      // KPIs
      h('div', { className: 'grid cols-4', style: { marginBottom: 20 } },
        kpis.map((k, i) => h('div', { key: i, className: 'card kpi' },
          h('div', { className: 'flex jc-sb ai-c' },
            h('div', null,
              h('div', { className: 'label' }, k.label),
              h('div', { className: 'value' },
                k.value,
                k.suffix ? h('span', { style: { fontSize: 14, fontWeight: 600, color: 'var(--text-tertiary)', marginInlineStart: 4 } }, k.suffix) : null,
              ),
              h('div', { className: 'trend ' + (k.trendUp ? 'up' : 'down') },
                h(k.trendUp ? Icons.TrendingUp : Icons.TrendingDown, { size: 14 }),
                k.trend,
              ),
            ),
            h('div', { className: 'kpi-icon', style: { background: k.soft, color: k.color } },
              h(k.icon, { size: 20 }),
            ),
          ),
        )),
      ),

      h('div', { style: { display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 20 } },
        // Today's schedule
        h('div', { className: 'card' },
          h('div', { style: { padding: '16px 20px', borderBottom: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' } },
            h('div', null,
              h('div', { style: { fontWeight: 800, fontSize: 15 } }, 'جدول اليوم'),
              h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)', marginTop: 2 } }, `${completed} من ${todayAppts.length} مواعيد مؤكدة`),
            ),
            h('button', { className: 'btn ghost sm', onClick: () => setScreen('appointments') }, 'عرض التقويم'),
          ),
          h('div', { style: { maxHeight: 420, overflowY: 'auto' } },
            todayAppts.length ? todayAppts.slice(0,6).map(a => h(AppointmentRow, { key: a.id, appt: a })) : h("div", { style: { padding: 32, textAlign: "center", color: "var(--text-tertiary)" } }, "لا توجد مواعيد اليوم"),
          ),
        ),

        h('div', { style: { display: 'flex', flexDirection: 'column', gap: 20 } },
          // Revenue chart
          h('div', { className: 'card p-20' },
            h('div', { className: 'flex jc-sb ai-c mb-16' },
              h('div', null,
                h('div', { style: { fontWeight: 800, fontSize: 15 } }, 'الإيرادات الأسبوعية'),
                h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)', marginTop: 2 } }, 'آخر 7 أيام'),
              ),
              h('span', { className: 'chip success' }, '+18.4%'),
            ),
            h(MiniBarChart, {
              data: [12400, 18200, 14800, 22100, 19500, 28600, 24850],
              labels: ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'اليوم'],
            }),
          ),
          // Doctors status
          h('div', { className: 'card' },
            h('div', { style: { padding: '14px 20px', borderBottom: '1px solid var(--border)', fontWeight: 800, fontSize: 14 } }, 'الأطباء اليوم'),
            h('div', { style: { padding: 10 } },
              allDoctors.map(d => h('div', {
                key: d.id,
                style: { display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px', borderRadius: 'var(--radius)', cursor: 'pointer' },
                onMouseEnter: (e) => e.currentTarget.style.background = 'var(--bg-hover)',
                onMouseLeave: (e) => e.currentTarget.style.background = 'transparent',
              },
                h('div', { className: 'avatar sm', style: { background: d.color } }, d.avatar),
                h('div', { style: { flex: 1, minWidth: 0 } },
                  h('div', { style: { fontSize: 13, fontWeight: 700, color: 'var(--text-primary)' } }, d.name),
                  h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)' } }, d.specialty),
                ),
                h('span', {
                  className: 'chip ' + (d.status === 'متاحة' ? 'success' : d.status === 'مع مريض' ? 'warning' : ''),
                  style: { fontSize: 10 },
                }, d.status),
              )),
            ),
          ),
        ),
      ),

      // Lower row
      h('div', { className: 'grid cols-3', style: { marginTop: 20 } },
        // Low stock alert
        h('div', { className: 'card p-20' },
          h('div', { className: 'flex jc-sb ai-c mb-16' },
            h('div', { style: { fontWeight: 800, fontSize: 14 } }, '⚠ تنبيه المخزون'),
            h('button', { className: 'btn ghost sm', onClick: () => setScreen('inventory') }, 'عرض الكل'),
          ),
          allInventory.filter(i => i.stock < i.minStock).slice(0, 3).map(item => h('div', {
            key: item.id,
            style: { padding: '10px 0', borderBottom: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' },
          },
            h('div', null,
              h('div', { style: { fontSize: 13, fontWeight: 600 } }, item.name),
              h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)', marginTop: 2 } }, `متبقي: ${item.stock} ${item.unit}`),
            ),
            h('div', { style: { flex: '0 0 auto', width: 60 } },
              h('div', { className: 'progress' },
                h('div', {
                  className: 'progress-bar',
                  style: {
                    width: Math.max(5, (item.stock / item.minStock) * 100) + '%',
                    background: item.stock < item.minStock / 2 ? 'var(--danger)' : 'var(--warning)',
                  },
                }),
              ),
            ),
          )),
        ),

        // Recent patients
        h('div', { className: 'card p-20' },
          h('div', { className: 'flex jc-sb ai-c mb-16' },
            h('div', { style: { fontWeight: 800, fontSize: 14 } }, 'مرضى جدد'),
            h('button', { className: 'btn ghost sm', onClick: () => setScreen('patients') }, 'الكل'),
          ),
          allPatients.slice(0, 4).map(p => h('div', {
            key: p.id,
            style: { display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0', borderBottom: '1px solid var(--border)' },
          },
            h('div', { className: 'avatar sm' }, p.avatar),
            h('div', { style: { flex: 1, minWidth: 0 } },
              h('div', { style: { fontSize: 13, fontWeight: 600 } }, p.name),
              h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)' } }, `${p.age} سنة · ${p.gender}`),
            ),
            h('button', { className: 'btn ghost sm' }, h(Icons.ChevronLeft, { size: 16 })),
          )),
        ),

        // Outstanding payments
        h('div', { className: 'card p-20' },
          h('div', { className: 'flex jc-sb ai-c mb-16' },
            h('div', { style: { fontWeight: 800, fontSize: 14 } }, 'مدفوعات معلقة'),
            h('button', { className: 'btn ghost sm', onClick: () => setScreen('billing') }, 'الكل'),
          ),
          allInvoices.filter(i => i.status !== 'paid').slice(0, 3).map(inv => h('div', {
            key: inv.id,
            style: { padding: '10px 0', borderBottom: '1px solid var(--border)' },
          },
            h('div', { className: 'flex jc-sb ai-c' },
              h('div', { style: { fontSize: 13, fontWeight: 600 } }, inv.patient),
              h('div', { style: { fontSize: 13, fontWeight: 800, color: 'var(--danger)' } }, window.fmtEGP(inv.total - inv.paid)),
            ),
            h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)', marginTop: 2 } }, `${inv.id} · ${inv.date}`),
          )),
        ),
      ),
    ),
  );
}

function AppointmentRow({ appt }) {
  const { setScreen } = useContext(AppContext);
  const statusMap = {
    confirmed: { chip: 'success', label: 'مؤكد' },
    'in-progress': { chip: 'info', label: 'جاري' },
    pending: { chip: 'warning', label: 'معلق' },
    done: { chip: '', label: 'مكتمل' },
  };
  const s = statusMap[appt.status] || statusMap.pending;
  const doctor = (window.DOCTORS || []).find(d => d.name.includes(appt.doctor.replace('د. ', '')));

  return h('div', {
    style: {
      padding: '14px 20px', borderBottom: '1px solid var(--border)', display: 'flex',
      alignItems: 'center', gap: 14, cursor: 'pointer', transition: 'background 0.15s',
    },
    onMouseEnter: (e) => e.currentTarget.style.background = 'var(--bg-hover)',
    onMouseLeave: (e) => e.currentTarget.style.background = 'transparent',
    onClick: () => setScreen('patient-file', { patientId: appt.patientId }),
  },
    h('div', { style: { textAlign: 'center', minWidth: 54 } },
      h('div', { style: { fontSize: 16, fontWeight: 800, color: 'var(--text-primary)' } }, appt.time),
      h('div', { style: { fontSize: 10, color: 'var(--text-tertiary)' } }, appt.duration + ' د'),
    ),
    h('div', { style: { width: 3, height: 40, background: doctor?.color || 'var(--accent)', borderRadius: 3 } }),
    h('div', { style: { flex: 1, minWidth: 0 } },
      h('div', { style: { fontSize: 14, fontWeight: 700, color: 'var(--text-primary)' } }, appt.patient),
      h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)', marginTop: 2 } },
        `${appt.type} · ${appt.doctor} · ${appt.room}`,
      ),
    ),
    h('span', { className: 'chip ' + s.chip }, s.label),
    h('button', { className: 'icon-btn', onClick: (e) => e.stopPropagation() }, h(Icons.MoreHorizontal, { size: 16 })),
  );
}

function MiniBarChart({ data, labels }) {
  const max = Math.max(...data);
  return h('div', null,
    h('div', { style: { display: 'flex', alignItems: 'flex-end', gap: 6, height: 120, marginBottom: 8 } },
      data.map((v, i) => h('div', {
        key: i,
        style: {
          flex: 1,
          height: `${(v / max) * 100}%`,
          background: i === data.length - 1 ? 'var(--accent)' : 'var(--accent-soft)',
          borderRadius: '6px 6px 2px 2px',
          position: 'relative',
          minHeight: 8,
          transition: 'all 0.3s',
        },
        title: window.fmtEGP(v),
      })),
    ),
    h('div', { style: { display: 'flex', gap: 6 } },
      labels.map((l, i) => h('div', {
        key: i,
        style: { flex: 1, textAlign: 'center', fontSize: 10, color: 'var(--text-tertiary)', fontWeight: 600 },
      }, l.slice(0, 3))),
    ),
  );
}

window.Screens = window.Screens || {};
window.Screens.Dashboard = Dashboard;
