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

// ==================== Appointments (Calendar + List) ====================
function Appointments() {
  const { setScreen, appointments } = useContext(AppContext);
  const [view, setView] = useState('day'); // day | week | month
  const todayStr = new Date().toISOString().split('T')[0];
  const [selectedDate, setSelectedDate] = useState(todayStr);
  const allAppts = (appointments && appointments.length) ? appointments : (window.APPOINTMENTS || []);

  return h('div', { className: 'fade-in' },
    h('div', { className: 'page-header' },
      h('div', null,
        h('div', { className: 'page-title' }, 'المواعيد'),
        h('div', { className: 'page-subtitle' }, 'إدارة جدول العيادة والحجوزات'),
      ),
      h('div', { className: 'flex gap-8' },
        h('div', { style: { display: 'flex', gap: 2, padding: 3, background: 'var(--bg-subtle)', borderRadius: 'var(--radius)' } },
          ['day', 'week', 'month'].map((v, i) => h('button', {
            key: v,
            className: 'btn sm',
            style: {
              background: view === v ? 'var(--bg-elevated)' : 'transparent',
              boxShadow: view === v ? 'var(--shadow-sm)' : 'none',
              color: view === v ? 'var(--text-primary)' : 'var(--text-secondary)',
            },
            onClick: () => setView(v),
          }, ['يوم', 'أسبوع', 'شهر'][i])),
        ),
        h('button', { className: 'btn outline' }, h(Icons.Filter, { size: 16 }), 'تصفية'),
        h('button', { className: 'btn primary', onClick: () => setScreen('new-appointment') },
          h(Icons.Plus, { size: 16 }), 'موعد جديد',
        ),
      ),
    ),
    h('div', { className: 'page-content' },
      view === 'day'   ? h(DayView,   { allAppts, selectedDate, setSelectedDate }) :
      view === 'week'  ? h(WeekView,  { allAppts, selectedDate }) :
                         h(MonthView, { allAppts, selectedDate, setSelectedDate, setView }),
    ),
  );
}

function DayView({ allAppts, selectedDate, setSelectedDate }) {
  const hours = Array.from({ length: 10 }, (_, i) => 8 + i); // 8:00 to 17:00
  const rooms = ['غرفة 1', 'غرفة 2', 'غرفة 3'];
  const { setScreen, setAppointments, toast } = useContext(AppContext);
  const dayAppts = (allAppts || []).filter(a => a.date === selectedDate);
  const todayStr = new Date().toISOString().split('T')[0];

  const handleStatusChange = async (appt, newStatus) => {
    try {
      const updated = await DB.updateAppointment(appt.id, { status: newStatus });
      setAppointments(prev => prev.map(a => a.id === updated.id ? updated : a));
      toast('تم تحديث الحالة ✅');
    } catch(e) { console.error(e); toast('خطأ في التحديث'); }
  };

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

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

  const dateLabel = new Date(selectedDate + 'T12:00:00').toLocaleDateString('ar-EG', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });

  return h('div', { className: 'card', style: { overflow: 'hidden' } },
    h('div', { style: { padding: '16px 20px', borderBottom: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' } },
      h('div', { className: 'flex ai-c gap-12' },
        h('button', { className: 'icon-btn', onClick: () => moveDay(-1) }, h(Icons.ChevronRight, { size: 16 })),
        h('div', null,
          h('div', { style: { fontWeight: 800, fontSize: 16 } }, dateLabel),
          h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)' } }, `${dayAppts.length} موعد`),
        ),
        h('button', { className: 'icon-btn', onClick: () => moveDay(1) }, h(Icons.ChevronLeft, { size: 16 })),
      ),
      h('button', { className: 'btn sm outline', onClick: () => setSelectedDate(todayStr) }, 'اليوم'),
    ),
    h('div', { style: { overflowX: 'auto' } },
      h('div', { style: { display: 'grid', gridTemplateColumns: '80px repeat(3, 1fr)', minWidth: 700 } },
        // header row
        h('div', { style: { padding: 12, borderBottom: '1px solid var(--border)', borderInlineStart: '1px solid var(--border)', background: 'var(--bg-subtle)' } }),
        rooms.map(r => h('div', {
          key: r,
          style: { padding: 12, borderBottom: '1px solid var(--border)', borderInlineStart: '1px solid var(--border)', background: 'var(--bg-subtle)', fontWeight: 700, fontSize: 13, textAlign: 'center' },
        }, r)),

        // time rows
        hours.map(hr => h(Fragment, { key: hr },
          h('div', {
            style: {
              padding: '12px 8px', borderBottom: '1px solid var(--border)', borderInlineStart: '1px solid var(--border)',
              fontSize: 11, color: 'var(--text-tertiary)', fontWeight: 600, textAlign: 'center',
              minHeight: 80,
            },
          }, `${hr.toString().padStart(2, '0')}:00`),
          rooms.map(room => {
            const appt = dayAppts.find(a => (a.room === room || !a.room) && parseInt((a.time||'0:0').split(':')[0]) === hr);
            return h('div', {
              key: room + hr,
              style: {
                padding: 6, borderBottom: '1px solid var(--border)', borderInlineStart: '1px solid var(--border)',
                minHeight: 80, position: 'relative', cursor: 'pointer',
              },
              onMouseEnter: (e) => { if (!appt) e.currentTarget.style.background = 'var(--bg-hover)'; },
              onMouseLeave: (e) => { if (!appt) e.currentTarget.style.background = 'transparent'; },
            },
              appt ? h(AppointmentBlock, { appt, onStatusChange: handleStatusChange, onDelete: handleDeleteAppt }) : null,
            );
          }),
        )),
      ),
    ),
  );
}

function AppointmentBlock({ appt, onStatusChange, onDelete }) {
  const { setScreen } = useContext(AppContext);
  const [menuOpen, setMenuOpen] = useState(false);
  const doctor = (window.DOCTORS||[]).find(d => d.name && appt.doctor && d.name.includes(appt.doctor.replace('د. ', '')));
  const color = doctor?.color || 'var(--accent)';
  const statusMap = { pending: 'معلق', confirmed: 'مؤكد', 'in-progress': 'جاري', done: 'مكتمل', cancelled: 'ملغي' };

  return h('div', {
    style: {
      background: `color-mix(in oklab, ${color} 15%, var(--bg-elevated))`,
      borderInlineStart: `3px solid ${color}`,
      borderRadius: 8, padding: 8, height: '100%',
      cursor: 'pointer', transition: 'all 0.15s', position: 'relative',
    },
    onMouseEnter: (e) => e.currentTarget.style.transform = 'scale(1.02)',
    onMouseLeave: (e) => { e.currentTarget.style.transform = 'scale(1)'; setMenuOpen(false); },
  },
    h('div', { onClick: () => setScreen('patient-file', { patientId: appt.patientId }) },
      h('div', { style: { fontSize: 13, fontWeight: 800, color: 'var(--text-primary)', marginBottom: 2 } }, appt.patient),
      h('div', { style: { fontSize: 11, color: 'var(--text-secondary)' } }, `${appt.time} · ${appt.duration}د`),
      h('div', { style: { fontSize: 11, color, fontWeight: 600, marginTop: 4 } }, appt.type),
      h('div', { style: { fontSize: 10, marginTop: 2, opacity: 0.8 } }, statusMap[appt.status] || appt.status),
    ),
    h('button', {
      className: 'icon-btn',
      style: { position: 'absolute', top: 4, insetInlineStart: 4, width: 20, height: 20, fontSize: 12 },
      onClick: (e) => { e.stopPropagation(); setMenuOpen(!menuOpen); },
    }, '⋮'),
    menuOpen ? h('div', {
      style: {
        position: 'absolute', top: 28, insetInlineStart: 0, background: 'var(--bg-elevated)',
        border: '1px solid var(--border)', borderRadius: 8, boxShadow: 'var(--shadow-lg)',
        zIndex: 100, minWidth: 130, overflow: 'hidden',
      },
      onClick: e => e.stopPropagation(),
    },
      [
        { status: 'confirmed', label: '✅ تأكيد', color: 'var(--success)' },
        { status: 'in-progress', label: '🔵 جاري الآن', color: 'var(--info)' },
        { status: 'done', label: '🏁 مكتمل', color: 'var(--text-primary)' },
        { status: 'cancelled', label: '❌ إلغاء', color: 'var(--danger)' },
      ].map(({ status, label, color: c }) => h('button', {
        key: status,
        style: { display: 'block', width: '100%', padding: '8px 12px', border: 'none', background: 'transparent', cursor: 'pointer', textAlign: 'right', fontSize: 12, color: c },
        onMouseEnter: e => e.currentTarget.style.background = 'var(--bg-hover)',
        onMouseLeave: e => e.currentTarget.style.background = 'transparent',
        onClick: () => { onStatusChange && onStatusChange(appt, status); setMenuOpen(false); },
      }, label)),
      h('div', { style: { borderTop: '1px solid var(--border)', margin: '4px 0' } }),
      h('button', {
        style: { display: 'block', width: '100%', padding: '8px 12px', border: 'none', background: 'transparent', cursor: 'pointer', textAlign: 'right', fontSize: 12, color: 'var(--danger)' },
        onMouseEnter: e => e.currentTarget.style.background = 'var(--bg-hover)',
        onMouseLeave: e => e.currentTarget.style.background = 'transparent',
        onClick: () => { onDelete && onDelete(appt); setMenuOpen(false); },
      }, '🗑 حذف الموعد'),
    ) : null,
  );
}

function WeekView({ allAppts, selectedDate }) {
  const { setScreen } = useContext(AppContext);
  const dayNames = ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'];
  const todayStr = new Date().toISOString().split('T')[0];
  const getWeekDays = (dateStr) => {
    const d = new Date((dateStr || todayStr) + 'T12:00:00');
    const day = d.getDay();
    const startOffset = day === 6 ? 0 : -(day + 1);
    return Array.from({ length: 7 }, (_, i) => {
      const dd = new Date(d); dd.setDate(d.getDate() + startOffset + i);
      return dd.toISOString().split('T')[0];
    });
  };
  const weekDays = getWeekDays(selectedDate);
  const weekAppts = (allAppts || []).filter(a => weekDays.includes(a.date));
  return h('div', { className: 'card', style: { overflow: 'hidden' } },
    h('div', { style: { padding: '14px 20px', borderBottom: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' } },
      h('div', { style: { fontWeight: 800, fontSize: 15 } }, 'عرض الأسبوع'),
      h('div', { style: { fontSize: 12, color: 'var(--text-tertiary)' } }, `${weekAppts.length} موعد هذا الأسبوع`),
    ),
    h('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)' } },
      weekDays.map((dateStr, i) => {
        const d = new Date(dateStr + 'T12:00:00');
        const isToday = dateStr === todayStr;
        const dayAppts = weekAppts.filter(a => a.date === dateStr);
        return h('div', { key: dateStr },
          h('div', {
            style: { padding: '10px 8px', textAlign: 'center', borderBottom: '1px solid var(--border)', borderInlineStart: i > 0 ? '1px solid var(--border)' : 'none', background: 'var(--bg-subtle)' },
          },
            h('div', { style: { fontSize: 10, color: 'var(--text-tertiary)', fontWeight: 600 } }, dayNames[d.getDay()]),
            h('div', { style: { fontSize: 16, fontWeight: 800, marginTop: 4, color: isToday ? '#fff' : 'var(--text-primary)', background: isToday ? 'var(--accent)' : 'transparent', width: 30, height: 30, borderRadius: '50%', display: 'grid', placeItems: 'center', margin: '4px auto 0' } }, d.getDate()),
          ),
          h('div', { style: { padding: 6, minHeight: 280, borderInlineStart: i > 0 ? '1px solid var(--border)' : 'none' } },
            dayAppts.slice(0, 5).map((a, j) => {
              const doc = (window.DOCTORS||[]).find(doc => doc.name && a.doctor && doc.name.includes(a.doctor.replace('د. ', '')));
              const color = doc?.color || 'var(--accent)';
              return h('div', {
                key: j,
                onClick: () => setScreen('patient-file', { patientId: a.patientId }),
                style: { padding: '4px 6px', marginBottom: 4, borderRadius: 5, background: `color-mix(in oklab, ${color} 15%, var(--bg-elevated))`, borderInlineStart: `2px solid ${color}`, fontSize: 10, cursor: 'pointer' },
              },
                h('div', { style: { fontWeight: 700 } }, a.time),
                h('div', { style: { color: 'var(--text-secondary)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, (a.patient || '').split(' ')[0]),
              );
            }),
            dayAppts.length > 5 ? h('div', { style: { fontSize: 10, color: 'var(--text-tertiary)', textAlign: 'center', padding: '4px 0' } }, `+${dayAppts.length-5} آخرون`) : null,
          ),
        );
      }),
    ),
  );
}

function MonthView({ allAppts, selectedDate, setSelectedDate, setView }) {
  const { setScreen } = useContext(AppContext);
  const todayStr = new Date().toISOString().split('T')[0];
  const [cursorDate, setCursorDate] = useState(() => (selectedDate || todayStr).substring(0, 7) + '-01');

  const year = parseInt(cursorDate.substring(0, 4));
  const month = parseInt(cursorDate.substring(5, 7)) - 1;
  const firstDayOfMonth = new Date(year, month, 1).getDay();
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const monthLabel = new Date(year, month, 1).toLocaleDateString('ar-EG', { month: 'long', year: 'numeric' });

  const moveMonth = (delta) => {
    const d = new Date(year, month + delta, 1);
    setCursorDate(d.toISOString().split('T')[0].substring(0, 8) + '01');
  };

  const cells = [];
  for (let i = 0; i < firstDayOfMonth; i++) cells.push(null);
  for (let i = 1; i <= daysInMonth; i++) {
    const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(i).padStart(2, '0')}`;
    cells.push({ day: i, dateStr, isToday: dateStr === todayStr });
  }

  const dayLabels = ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'];

  return h('div', null,
    h('div', { className: 'flex jc-sb ai-c', style: { marginBottom: 12 } },
      h('div', { style: { fontWeight: 800, fontSize: 18 } }, monthLabel),
      h('div', { className: 'flex gap-8' },
        h('button', { className: 'icon-btn', onClick: () => moveMonth(-1) }, h(Icons.ChevronRight, { size: 16 })),
        h('button', { className: 'btn sm outline', onClick: () => { setCursorDate(todayStr.substring(0, 8) + '01'); } }, 'اليوم'),
        h('button', { className: 'icon-btn', onClick: () => moveMonth(1) }, h(Icons.ChevronLeft, { size: 16 })),
      ),
    ),
    h('div', { className: 'calendar-grid' },
      dayLabels.map((d, i) => h('div', { key: i, className: 'calendar-day-header' }, d)),
      cells.map((c, i) => {
        if (!c) return h('div', { key: 'empty-' + i, className: 'calendar-day other-month' });
        const dayAppts = (allAppts || []).filter(a => a.date === c.dateStr);
        return h('div', {
          key: c.dateStr,
          className: 'calendar-day' + (c.isToday ? ' today' : ''),
          onClick: () => { setSelectedDate(c.dateStr); setView('day'); },
          style: { cursor: 'pointer' },
        },
          h('div', { className: 'day-num' }, c.day),
          dayAppts.slice(0, 3).map((a, j) => {
            const statusColor = a.status === 'confirmed' ? 'success' : a.status === 'done' ? '' : 'warning';
            return h('div', {
              key: j,
              className: 'event-pill ' + statusColor,
              onClick: (e) => { e.stopPropagation(); setScreen('patient-file', { patientId: a.patientId }); },
            }, (a.patient || '').split(' ')[0] + ' · ' + a.time);
          }),
          dayAppts.length > 3 ? h('div', { className: 'event-pill', style: { background: 'var(--bg-subtle)', color: 'var(--text-tertiary)' } }, `+${dayAppts.length - 3}`) : null,
        );
      }),
    ),
  );
}

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