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

const REC_KANBAN_STAGES = [
  { key: 'pending',     label: 'محجوز',       icon: '📋', next: 'confirmed',   nextLabel: 'تأكيد الحضور',   color: 'var(--warning)' },
  { key: 'confirmed',   label: 'في الانتظار', icon: '⏳', next: 'in-progress', nextLabel: 'دخل على الطبيب', color: 'var(--info)' },
  { key: 'in-progress', label: 'مع الطبيب',   icon: '🦷', next: 'done',        nextLabel: 'إنهاء الجلسة',   color: 'var(--accent)' },
  { key: 'done',        label: 'تمت الجلسة',  icon: '✅', next: null,          nextLabel: null,              color: 'var(--success)' },
  { key: 'cancelled',   label: 'لم يحضر',     icon: '❌', next: null,          nextLabel: null,              color: 'var(--danger)' },
];

// ==================== Walk-In Modal (حضر الآن بدون موعد) ====================
function WalkInModal({ onClose, onSaved }) {
  const { toast, clinicId, patients, doctors, setAppointments, services } = useContext(AppContext);
  const allPts  = (patients && patients.length) ? patients : (window.PATIENTS || []);
  const allDocs = (doctors  && doctors.length)  ? doctors  : (window.DOCTORS  || []);
  const allSvcs = (services && services.length) ? services : (window.TREATMENT_TYPES || []);

  const [search, setSearch] = useState('');
  const [selectedPt, setSelectedPt] = useState(null);
  const [doctorId, setDoctorId] = useState(allDocs[0] ? String(allDocs[0].id) : '');
  const [type, setType] = useState(allSvcs[0]?.name || 'كشف وفحص');
  const [saving, setSaving] = useState(false);

  const todayStr = new Date().toISOString().split('T')[0];
  const nowTime  = new Date().toTimeString().slice(0, 5); // HH:MM
  const roomCount = parseInt(localStorage.getItem('senan-rooms') || '1', 10);
  const room = roomCount === 1 ? 'الغرفة' : 'غرفة 1';

  const filtered = useMemo(() => {
    if (!search.trim()) return allPts.slice(0, 8);
    const q = search.toLowerCase();
    return allPts.filter(p =>
      (p.name || '').toLowerCase().includes(q) ||
      (p.phone || '').includes(q)
    ).slice(0, 8);
  }, [search, allPts.length]);

  const selectedDoc = allDocs.find(d => String(d.id) === doctorId) || null;

  const handleConfirm = async () => {
    if (!selectedPt) { toast('اختر المريض أولاً'); return; }
    setSaving(true);
    try {
      const newAppt = await DB.addAppointment(clinicId, {
        patient_id: selectedPt.id,
        doctor_id: selectedDoc?.id || null,
        date: todayStr,
        time: nowTime + ':00',   // HH:MM:SS
        duration: 30,
        type: type || 'كشف وفحص',
        room,
        status: 'confirmed',     // مباشرة في الانتظار
        notes: 'حضر بدون موعد مسبق',
      });
      setAppointments(prev => [newAppt, ...(prev || [])]);
      toast('✅ تم تسجيل الحضور — المريض الآن في الانتظار');
      onSaved && onSaved(newAppt);
      onClose();
    } catch (e) {
      console.error(e);
      toast('خطأ: ' + (e.message || 'تعذر الحفظ'));
    } finally {
      setSaving(false);
    }
  };

  return h('div', { className: 'modal-backdrop', onClick: onClose, style: { zIndex: 210 } },
    h('div', {
      className: 'gm-box',
      onClick: e => e.stopPropagation(),
      style: { width: 460, padding: 28 },
    },
      /* Header */
      h('div', { className: 'modal-header', style: { marginBottom: 20 } },
        h('div', null,
          h('div', { className: 'modal-title' }, '🚶 حضر الآن — بدون موعد'),
          h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)', marginTop: 4 } },
            'سيُضاف مباشرة في "في الانتظار" بالكانبان · ' + nowTime,
          ),
        ),
        h('button', { className: 'icon-btn', onClick: onClose }, h(Icons.X, { size: 16 })),
      ),

      /* Patient search */
      h('div', { className: 'label mb-6' }, 'المريض'),
      h('input', {
        className: 'input mb-8',
        placeholder: 'ابحث بالاسم أو الهاتف...',
        value: search,
        autoFocus: true,
        onChange: e => { setSearch(e.target.value); setSelectedPt(null); },
      }),
      /* Patient list */
      h('div', {
        style: {
          maxHeight: 200, overflowY: 'auto', border: '1px solid var(--border)',
          borderRadius: 'var(--radius)', marginBottom: 16,
        },
      },
        filtered.length === 0
          ? h('div', { style: { padding: '14px 16px', fontSize: 13, color: 'var(--text-tertiary)', textAlign: 'center' } }, 'لا نتائج')
          : filtered.map(p => h('div', {
              key: p.id,
              style: {
                padding: '10px 14px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 10,
                background: selectedPt?.id === p.id ? 'var(--accent-soft)' : 'transparent',
                borderBottom: '1px solid var(--border)',
                transition: 'background 0.12s',
              },
              onMouseEnter: e => { if (selectedPt?.id !== p.id) e.currentTarget.style.background = 'var(--bg-hover)'; },
              onMouseLeave: e => { if (selectedPt?.id !== p.id) e.currentTarget.style.background = 'transparent'; },
              onClick: () => setSelectedPt(p),
            },
            h('div', { className: 'avatar sm', style: { fontSize: 11, flexShrink: 0 } }, (p.name || '?').charAt(0)),
            h('div', { style: { flex: 1, minWidth: 0 } },
              h('div', { style: { fontWeight: 700, fontSize: 13 } }, p.name),
              h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)', marginTop: 2 } }, p.phone || 'لا يوجد هاتف'),
            ),
            selectedPt?.id === p.id ? h('span', { style: { color: 'var(--accent)', fontSize: 16 } }, '✓') : null,
          )),
      ),

      /* Service type */
      h('div', { style: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 16 } },
        h('div', null,
          h('div', { className: 'label mb-6' }, 'نوع الزيارة'),
          h('select', {
            className: 'input',
            value: type,
            onChange: e => setType(e.target.value),
          },
            allSvcs.length > 0
              ? allSvcs.map(s => h('option', { key: s.id, value: s.name }, s.name))
              : [
                  h('option', { key: 'k', value: 'كشف وفحص' }, 'كشف وفحص'),
                  h('option', { key: 't', value: 'علاج' }, 'علاج'),
                  h('option', { key: 'f', value: 'متابعة' }, 'متابعة'),
                ],
          ),
        ),
        h('div', null,
          h('div', { className: 'label mb-6' }, 'الطبيب'),
          h('select', {
            className: 'input',
            value: doctorId,
            onChange: e => setDoctorId(e.target.value),
          },
            h('option', { value: '' }, allDocs.length ? '— اختر —' : 'لا يوجد أطباء'),
            allDocs.map(d => h('option', { key: d.id, value: String(d.id) }, d.name)),
          ),
        ),
      ),

      /* Footer */
      h('div', { className: 'modal-footer', style: { marginTop: 4, display: 'flex', gap: 8, justifyContent: 'flex-end' } },
        h('button', { className: 'btn outline', onClick: onClose }, 'إلغاء'),
        h('button', {
          className: 'btn primary',
          disabled: !selectedPt || saving,
          onClick: handleConfirm,
        }, saving ? '...' : '🚶 تسجيل الحضور'),
      ),
    ),
  );
}

// ==================== Reception (لوحة الاستقبال) ====================
function Reception() {
  const { appointments, setAppointments, toast, setScreen, invoices } = useContext(AppContext);
  const [showNewAppt,  setShowNewAppt]  = useState(false);
  const [showWalkIn,   setShowWalkIn]   = useState(false);
  const [loading, setLoading] = useState({});

  const todayStr = new Date().toISOString().split('T')[0];
  const [selectedDate, setSelectedDate] = useState(todayStr);

  const allAppts    = (appointments && appointments.length) ? appointments : (window.APPOINTMENTS || []);
  const allInvoices = (invoices && invoices.length) ? invoices : (window.INVOICES || []);

  const todayAppts    = allAppts.filter(a => a.date === todayStr);
  const selectedAppts = allAppts.filter(a => a.date === selectedDate);
  const isToday = selectedDate === todayStr;

  /* -------- KPIs -------- */
  const totalToday   = todayAppts.length;
  const inWaiting    = todayAppts.filter(a => a.status === 'confirmed').length;
  const inChair      = todayAppts.filter(a => a.status === 'in-progress').length;
  const doneSessions = todayAppts.filter(a => a.status === 'done').length;
  const todayRevenue = allInvoices.filter(i => i.date === todayStr).reduce((s, i) => s + (i.paid || 0), 0);

  const kpis = [
    { label: 'مواعيد اليوم', value: totalToday,   color: 'var(--accent)',  soft: 'var(--accent-soft)'  },
    { label: 'في الانتظار',  value: inWaiting,    color: 'var(--info)',    soft: 'var(--info-soft)'    },
    { label: 'مع الطبيب',    value: inChair,      color: 'var(--warning)', soft: 'var(--warning-soft)' },
    { label: 'انتهت الجلسة', value: doneSessions, color: 'var(--success)', soft: 'var(--success-soft)' },
    { label: 'تحصيل اليوم', value: window.fmtEGP(todayRevenue), color: 'var(--success)', soft: 'var(--success-soft)' },
  ];

  /* -------- Kanban actions -------- */
  async function moveCard(appt, newStatus) {
    if (loading[appt.id]) return;
    setLoading(l => ({ ...l, [appt.id]: true }));
    setAppointments(prev => (prev || []).map(a => a.id === appt.id ? { ...a, status: newStatus } : a));
    try {
      await DB.updateAppointment(appt.id, { status: newStatus });
      const labels = { done: '✅ تمت الجلسة', 'in-progress': '🦷 دخل على الطبيب', confirmed: '👋 تم تأكيد الحضور' };
      toast(labels[newStatus] || 'تم التحديث');
    } catch (e) {
      setAppointments(prev => (prev || []).map(a => a.id === appt.id ? { ...a, status: appt.status } : a));
      toast('حدث خطأ — تحقق من الاتصال');
    } finally {
      setLoading(l => ({ ...l, [appt.id]: false }));
    }
  }

  async function markNoShow(appt) {
    if (loading[appt.id]) return;
    setLoading(l => ({ ...l, [appt.id]: true }));
    try {
      await DB.updateAppointment(appt.id, { status: 'cancelled' });
      setAppointments(prev => (prev || []).map(a => a.id === appt.id ? { ...a, status: 'cancelled' } : a));
      toast('ℹ لم يحضر — تم الحفظ');
    } catch (e) { toast('حدث خطأ'); }
    finally { setLoading(l => ({ ...l, [appt.id]: false })); }
  }

  async function handleDeleteAppt(appt) {
    if (!confirm(`حذف موعد ${appt.patient}؟`)) return;
    try {
      await DB.deleteAppointment(appt.id);
      setAppointments(prev => prev.filter(a => a.id !== appt.id));
      toast('تم حذف الموعد');
    } catch (e) { toast('خطأ في الحذف'); }
  }

  /* -------- Schedule helpers -------- */
  const moveDay = (delta) => {
    const d = new Date(selectedDate);
    d.setDate(d.getDate() + delta);
    setSelectedDate(d.toISOString().split('T')[0]);
  };

  const statusMap = {
    pending:       { label: 'محجوز',       cls: 'warning' },
    confirmed:     { label: 'في الانتظار', cls: 'info'    },
    'in-progress': { label: 'مع الطبيب',   cls: 'accent'  },
    done:          { label: 'تمت',         cls: 'success' },
    cancelled:     { label: 'لم يحضر',    cls: 'danger'  },
  };

  const dateLabel = window.fmtDate(selectedDate);

  /* -------- Render -------- */
  return h('div', { className: 'fade-in' },

    /* === Modals === */
    showWalkIn  && h(WalkInModal,  { onClose: () => setShowWalkIn(false)  }),
    showNewAppt && h('div', { className: 'modal-backdrop', onClick: () => setShowNewAppt(false), style: { zIndex: 200 } },
      h('div', {
        className: 'gm-box',
        onClick: e => e.stopPropagation(),
        style: { width: 'min(860px, calc(100vw - 32px))', maxHeight: 'calc(100dvh - 40px)', overflowY: 'auto', padding: 0 },
      },
        h(Screens.NewAppointment, { onClose: () => setShowNewAppt(false) }),
      ),
    ),

    /* === Page Header === */
    h('div', { className: 'page-header' },
      h('div', null,
        h('div', { className: 'page-title' }, '🏥 الاستقبال'),
        h('div', { className: 'page-subtitle' },
          'كانبان سير المرضى · ' + new Date().toLocaleDateString('ar-EG', { weekday: 'long', day: 'numeric', month: 'long' }),
        ),
      ),
      h('div', { className: 'flex gap-8' },
        h('button', {
          className: 'btn outline',
          style: { background: 'var(--success-soft)', borderColor: 'var(--success)', color: 'var(--success)' },
          onClick: () => setShowWalkIn(true),
          title: 'مريض حضر بدون موعد مسبق',
        }, '🚶 حضر الآن'),
        h('button', { className: 'btn primary', onClick: () => setShowNewAppt(true) },
          h(Icons.Plus, { size: 16 }), 'موعد جديد',
        ),
      ),
    ),

    h('div', { className: 'page-content' },

      /* === KPI Strip === */
      h('div', { style: { display: 'flex', gap: 10, marginBottom: 16, flexWrap: 'wrap' } },
        kpis.map((k, i) => h('div', {
          key: i,
          style: {
            flex: '1 1 130px', minWidth: 110,
            background: 'var(--bg-card)', border: '1px solid var(--border)',
            borderRadius: 'var(--radius)', padding: '10px 14px',
            display: 'flex', alignItems: 'center', gap: 10,
          },
        },
          h('div', { style: { fontSize: 20, fontWeight: 900, color: k.color, minWidth: 28, textAlign: 'center' } }, k.value),
          h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)', fontWeight: 600, lineHeight: 1.3 } }, k.label),
        )),
      ),

      /* === Main Split: Kanban (60%) | Schedule (40%) === */
      h('div', { style: { display: 'grid', gridTemplateColumns: '3fr 2fr', gap: 16, alignItems: 'start' } },

        /* ===== LEFT: Kanban board ===== */
        h('div', null,
          h('div', { style: { fontWeight: 800, fontSize: 13, marginBottom: 10, color: 'var(--text-secondary)', textTransform: 'uppercase', letterSpacing: 0.5 } },
            '⚡ تتبع المرضى — كانبان اليوم',
          ),
          h('div', { className: 'kanban-board' },
            REC_KANBAN_STAGES.map(stage => {
              const cards = todayAppts.filter(a => a.status === stage.key);
              return h('div', { key: stage.key, className: 'kanban-col' },
                /* Column header */
                h('div', { className: 'kanban-col-hdr', style: { borderTop: `3px solid ${stage.color}` } },
                  h('span', null, stage.icon + ' ' + stage.label),
                  h('span', {
                    style: {
                      background: cards.length > 0 ? `color-mix(in oklab, ${stage.color} 15%, transparent)` : 'var(--bg-hover)',
                      color: cards.length > 0 ? stage.color : 'var(--text-tertiary)',
                      padding: '2px 8px', borderRadius: 999, fontSize: 12, fontWeight: 800,
                    },
                  }, cards.length),
                ),
                /* Cards */
                h('div', { style: { padding: 10, display: 'flex', flexDirection: 'column', gap: 8, minHeight: 80 } },
                  cards.length === 0
                    ? h('div', { className: 'kanban-empty' }, 'لا يوجد مرضى')
                    : cards.map(appt => h('div', {
                        key: appt.id,
                        className: 'kanban-card',
                        style: { opacity: loading[appt.id] ? 0.6 : 1 },
                      },
                      h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 } },
                        h('div', { className: 'avatar sm', style: { fontSize: 11 } }, (appt.patient || '?').charAt(0)),
                        h('div', { style: { flex: 1, minWidth: 0 } },
                          h('div', { style: { fontSize: 13, fontWeight: 700, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' } }, appt.patient),
                          h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)' } }, appt.time + ' · ' + (appt.type || '')),
                        ),
                      ),
                      h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)', marginBottom: 8 } },
                        '👨‍⚕️ ' + (appt.doctor || '—'),
                      ),
                      h('div', { style: { display: 'flex', gap: 4, flexWrap: 'wrap' } },
                        stage.next ? h('button', {
                          className: 'btn primary sm',
                          style: { fontSize: 11, flex: 1 },
                          onClick: () => moveCard(appt, stage.next),
                          disabled: !!loading[appt.id],
                        }, loading[appt.id] ? '...' : stage.nextLabel) : null,
                        stage.key !== 'done' && stage.key !== 'cancelled' ? h('button', {
                          className: 'btn ghost sm',
                          style: { fontSize: 11, padding: '4px 8px', color: 'var(--danger)' },
                          onClick: () => markNoShow(appt),
                          disabled: !!loading[appt.id],
                          title: 'لم يحضر',
                        }, '✕') : null,
                        h('button', {
                          className: 'btn ghost sm',
                          style: { fontSize: 11, padding: '4px 8px' },
                          onClick: () => setScreen('patient-file', { patientId: appt.patientId }),
                          title: 'ملف المريض',
                        }, h(Icons.User, { size: 12 })),
                      ),
                    )),
                ),
              );
            }),
          ),
        ),

        /* ===== RIGHT: Schedule panel ===== */
        h('div', { className: 'card', style: { overflow: 'hidden', position: 'sticky', top: 16 } },
          /* Date navigation header */
          h('div', {
            style: {
              padding: '10px 14px', borderBottom: '1px solid var(--border)',
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
              background: 'var(--bg-subtle)',
            },
          },
            /* Date nav left side */
            h('div', { className: 'flex ai-c gap-6' },
              h('button', { className: 'icon-btn', onClick: () => moveDay(-1) }, h(Icons.ChevronRight, { size: 16 })),
              h('div', null,
                h('div', { style: { fontWeight: 800, fontSize: 13, color: 'var(--text-primary)' } },
                  isToday ? '📅 جدول اليوم' : dateLabel,
                ),
                h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)', marginTop: 1 } },
                  (isToday ? dateLabel + ' · ' : '') + selectedAppts.length + ' موعد',
                ),
              ),
              h('button', { className: 'icon-btn', onClick: () => moveDay(1) }, h(Icons.ChevronLeft, { size: 16 })),
            ),
            /* Right side: today + calendar buttons */
            h('div', { className: 'flex gap-6' },
              !isToday
                ? h('button', { className: 'btn sm outline', onClick: () => setSelectedDate(todayStr) }, 'اليوم')
                : null,
              h('button', {
                className: 'btn sm ghost',
                onClick: () => setScreen('appointments'),
                title: 'فتح شاشة التقويم الكاملة',
              }, h(Icons.Calendar, { size: 14 }), ' التقويم'),
            ),
          ),

          /* Appointments list */
          selectedAppts.length === 0
            ? h('div', {
                style: { padding: 40, textAlign: 'center', color: 'var(--text-tertiary)', fontSize: 13 },
              },
              h('div', { style: { fontSize: 32, marginBottom: 8 } }, '📭'),
              isToday ? 'لا توجد مواعيد اليوم' : 'لا توجد مواعيد في هذا اليوم',
            )
            : h('div', { style: { maxHeight: 520, overflowY: 'auto' } },
                [...selectedAppts]
                  .sort((a, b) => (a.time || '').localeCompare(b.time || ''))
                  .map(appt => {
                    const st = statusMap[appt.status] || { label: appt.status, cls: 'warning' };
                    const doctor = (window.DOCTORS || []).find(d => d.name && appt.doctor && d.name.includes(appt.doctor.replace('د. ', '')));
                    const color = doctor?.color || 'var(--accent)';
                    return h('div', {
                      key: appt.id,
                      style: {
                        padding: '11px 16px', borderBottom: '1px solid var(--border)',
                        display: 'flex', alignItems: 'center', gap: 12,
                        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 }),
                    },
                      /* Time */
                      h('div', { style: { textAlign: 'center', minWidth: 42, flexShrink: 0 } },
                        h('div', { style: { fontSize: 14, fontWeight: 800, color: 'var(--text-primary)', fontFamily: 'monospace' } }, appt.time),
                        h('div', { style: { fontSize: 10, color: 'var(--text-tertiary)' } }, (appt.duration || 30) + 'د'),
                      ),
                      /* Color bar */
                      h('div', { style: { width: 3, height: 36, background: color, borderRadius: 3, flexShrink: 0 } }),
                      /* Info */
                      h('div', { style: { flex: 1, minWidth: 0 } },
                        h('div', { style: { fontSize: 13, fontWeight: 700, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' } }, appt.patient),
                        h('div', { style: { fontSize: 11, color: 'var(--text-tertiary)', marginTop: 2 } },
                          (appt.type || '—') + (appt.doctor ? ' · ' + appt.doctor : ''),
                        ),
                      ),
                      /* Status chip */
                      h('span', { className: 'chip ' + st.cls, style: { fontSize: 10, flexShrink: 0 } }, st.label),
                      /* Delete */
                      h('button', {
                        className: 'icon-btn',
                        style: { color: 'var(--danger)', width: 28, height: 28, flexShrink: 0 },
                        title: 'حذف الموعد',
                        onClick: e => { e.stopPropagation(); handleDeleteAppt(appt); },
                      }, h(Icons.Trash, { size: 13 })),
                    );
                  }),
              ),
        ),

      ),
    ),
  );
}

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