// AlertsScreen.jsx — AegisComply (live alerts synthesized from Supabase data)

const alertScreenStyles = {
  page: { padding: 24 },
  filters: { display: 'flex', gap: 8, marginBottom: 16, flexWrap: 'wrap', alignItems: 'center' },
  filterChip: { padding: '5px 14px', borderRadius: 20, fontSize: 12, fontWeight: 500, cursor: 'pointer', border: '1px solid #E2E8F0', background: 'white', color: '#475569', fontFamily: "'DM Sans', sans-serif", transition: 'all 150ms' },
  filterChipActive: { background: '#0B1F3A', color: 'white', borderColor: '#0B1F3A' },
  countText: { marginLeft: 'auto', fontSize: 12, color: '#94A3B8', display: 'flex', alignItems: 'center', gap: 10 },
  clearLink: { fontSize: 12, color: '#0D9488', fontWeight: 500, cursor: 'pointer' },
  alertsList: { display: 'flex', flexDirection: 'column', gap: 8 },
  alertCard: { background: 'white', border: '1px solid #E2E8F0', borderRadius: 8, padding: '14px 16px', display: 'flex', alignItems: 'flex-start', gap: 14, boxShadow: '0 1px 3px rgba(0,0,0,0.05)', cursor: 'pointer', transition: 'box-shadow 150ms' },
  alertIconWrap: { width: 36, height: 36, borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginTop: 1 },
  alertContent: { flex: 1, minWidth: 0 },
  alertTitle: { fontSize: 13, fontWeight: 600, color: '#0F172A', marginBottom: 3, lineHeight: 1.3 },
  alertDesc: { fontSize: 12, color: '#64748B', lineHeight: 1.5 },
  alertMeta: { fontSize: 11, color: '#94A3B8', marginTop: 5 },
  alertActions: { display: 'flex', gap: 6, flexShrink: 0, alignItems: 'flex-start', marginTop: 2 },
  alertBtn: { height: 28, padding: '0 12px', borderRadius: 5, fontSize: 12, fontWeight: 500, cursor: 'pointer', fontFamily: "'DM Sans', sans-serif", border: '1px solid #CBD5E1', background: 'white', color: '#334155' },
  alertBtnPrimary: { background: '#0D9488', color: 'white', border: 'none', fontWeight: 600 },
  badge: { display: 'inline-flex', padding: '2px 7px', borderRadius: 4, fontSize: 10, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase' },
  empty: { background: 'white', border: '1px solid #E2E8F0', borderRadius: 8, padding: 40, textAlign: 'center', color: '#64748B' },
  emptyIcon: { width: 48, height: 48, borderRadius: 12, background: '#F0FDF4', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 12 },
};

const alertConfig = {
  critical: { bg: '#FFF5F5', iconBg: '#FEE2E2', iconColor: '#DC2626', badgeBg: '#FEE2E2', badgeColor: '#991B1B', label: 'CRITICAL' },
  warning:  { bg: '#FFFBEB', iconBg: '#FEF3C7', iconColor: '#D97706', badgeBg: '#FEF3C7', badgeColor: '#92400E', label: 'WARNING' },
  info:     { bg: 'white',   iconBg: '#F0FDFA', iconColor: '#0D9488', badgeBg: '#CCFBF1', badgeColor: '#0F766E', label: 'INFO' },
};

function AlertIcon({ type }) {
  if (type === 'critical') return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
  );
  if (type === 'warning') return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
  );
  return (
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="10"/><line x1="12" y1="12" x2="12" y2="16"/></svg>
  );
}

function alertFmtDate(d) {
  if (!d) return '—';
  try { return new Date(d).toLocaleString('en-MY', { dateStyle: 'medium', timeStyle: 'short' }); }
  catch { return d; }
}

// ── localStorage-backed dismissals (per user) ──────────────────────────────
function loadDismissed(userId) {
  if (!userId) return new Set();
  try {
    const raw = localStorage.getItem(`aegis-dismissed-${userId}`);
    return new Set(raw ? JSON.parse(raw) : []);
  } catch { return new Set(); }
}
function saveDismissed(userId, set) {
  if (!userId) return;
  try { localStorage.setItem(`aegis-dismissed-${userId}`, JSON.stringify([...set])); } catch {}
}

// ── Main AlertsScreen ──────────────────────────────────────────────────────
function AlertsScreen({ user, onNav }) {
  const [equipment, setEquipment]         = React.useState([]);
  const [ppeInventory, setPPEInventory]   = React.useState([]);
  const [ppeRequests, setPPERequests]     = React.useState([]);
  const [borrowRequests, setBorrowReqs]   = React.useState([]);
  const [calIssues, setCalIssues]         = React.useState([]);
  const [excessiveIssuance, setExcessive] = React.useState([]);
  const [calFailures, setCalFailures]     = React.useState([]);
  const [loading, setLoading]             = React.useState(true);
  const [error, setError]                 = React.useState('');
  const [activeFilter, setActiveFilter]   = React.useState('All');
  const [dismissed, setDismissed]         = React.useState(() => loadDismissed(user?.id));

  const load = React.useCallback(async () => {
    try {
      const sb = window.supabaseClient;
      const [eq, ppe, ppeReq, brwReq, cal, exc, fail] = await Promise.all([
        sb.from('equipment').select('*'),
        sb.from('ppe_inventory').select('*'),
        sb.from('ppe_requests').select('*').eq('status', 'pending'),
        sb.from('borrow_requests').select('*').eq('status', 'pending'),
        sb.from('calibration_records').select('*').eq('has_issue', true).order('created_at', { ascending: false }).limit(20),
        sb.from('anomaly_excessive_issuance').select('*').order('issuance_count', { ascending: false }),
        sb.from('anomaly_calibration_failures').select('*').order('fail_count', { ascending: false }),
      ]);
      if (eq.error)     throw eq.error;
      if (ppe.error)    throw ppe.error;
      if (ppeReq.error) throw ppeReq.error;
      if (brwReq.error) throw brwReq.error;
      if (cal.error)    throw cal.error;
      // Anomaly views might not exist yet (silently fall back to empty)
      setEquipment(eq.data || []);
      setPPEInventory(ppe.data || []);
      setPPERequests(ppeReq.data || []);
      setBorrowReqs(brwReq.data || []);
      setCalIssues(cal.data || []);
      setExcessive(exc.data || []);
      setCalFailures(fail.data || []);
    } catch (err) {
      console.error('[Alerts] load error:', err);
      setError(err.message || 'Failed to load alerts.');
    } finally {
      setLoading(false);
    }
  }, []);

  React.useEffect(() => { load(); }, [load]);

  // Realtime — refresh on any change to source tables
  React.useEffect(() => {
    if (!user) return;
    const sb = window.supabaseClient;
    if (!sb) return;
    const ch = sb.channel(`alerts-watcher-${user.id}`)
      .on('postgres_changes', { event: '*', schema: 'public', table: 'equipment',            filter: `user_id=eq.${user.id}` },    () => load())
      .on('postgres_changes', { event: '*', schema: 'public', table: 'ppe_inventory',        filter: `user_id=eq.${user.id}` },    () => load())
      .on('postgres_changes', { event: '*', schema: 'public', table: 'ppe_requests',         filter: `account_id=eq.${user.id}` }, () => load())
      .on('postgres_changes', { event: '*', schema: 'public', table: 'borrow_requests',      filter: `account_id=eq.${user.id}` }, () => load())
      .on('postgres_changes', { event: '*', schema: 'public', table: 'calibration_records',  filter: `user_id=eq.${user.id}` },    () => load())
      .subscribe();
    return () => { sb.removeChannel(ch); };
  }, [user, load]);

  const handleDismiss = (key) => {
    setDismissed(prev => {
      const next = new Set(prev);
      next.add(key);
      saveDismissed(user?.id, next);
      return next;
    });
  };

  const handleClearAllDismissed = () => {
    setDismissed(new Set());
    saveDismissed(user?.id, new Set());
  };

  // ── Synthesize alerts from data ──────────────────────────────────────────
  const allAlerts = React.useMemo(() => {
    const list = [];

    // Critical: expired / overdue equipment
    for (const e of equipment) {
      if (e.status === 'expired' || e.status === 'overdue') {
        list.push({
          key:      `eq-${e.status}:${e.id}`,
          type:     'critical',
          category: 'Calibration',
          module:   'Equipment',
          title:    `Calibration ${e.status} — ${e.name}`,
          desc:     `Serial ${e.serial_number}. Due date: ${e.calibration_due ? new Date(e.calibration_due).toLocaleDateString('en-GB') : 'unknown'}. ${e.status === 'expired' ? 'Operating without a valid certificate. Recalibrate immediately.' : 'Past calibration due date — schedule recalibration.'}`,
          time:     e.calibration_due || e.updated_at,
          nav:      'calibration',
        });
      }
    }

    // Warning: expiring equipment
    for (const e of equipment) {
      if (e.status === 'expiring') {
        list.push({
          key:      `eq-expiring:${e.id}`,
          type:     'warning',
          category: 'Calibration',
          module:   'Equipment',
          title:    `Calibration due soon — ${e.name}`,
          desc:     `Serial ${e.serial_number}. Due date: ${e.calibration_due ? new Date(e.calibration_due).toLocaleDateString('en-GB') : 'unknown'}. Schedule recalibration before due date.`,
          time:     e.calibration_due || e.updated_at,
          nav:      'calibration',
        });
      }
    }

    // Critical: PPE critical stock
    for (const p of ppeInventory) {
      if (p.status === 'critical') {
        list.push({
          key:      `ppe-critical:${p.id}`,
          type:     'critical',
          category: 'PPE',
          module:   'PPE',
          title:    `PPE critical stock — ${p.name}${p.size ? ` [${p.size}]` : ''}`,
          desc:     `Current balance: ${p.balance ?? 0} ${p.unit || 'pcs'}. Min threshold: ${p.min_stock}. Immediate procurement required.`,
          time:     p.updated_at,
          nav:      'ppe',
        });
      }
    }

    // Warning: PPE low stock
    for (const p of ppeInventory) {
      if (p.status === 'low') {
        list.push({
          key:      `ppe-low:${p.id}`,
          type:     'warning',
          category: 'PPE',
          module:   'PPE',
          title:    `PPE low stock — ${p.name}${p.size ? ` [${p.size}]` : ''}`,
          desc:     `Current balance: ${p.balance ?? 0} ${p.unit || 'pcs'}. Min threshold: ${p.min_stock}. Reorder recommended.`,
          time:     p.updated_at,
          nav:      'ppe',
        });
      }
    }

    // Warning: pending PPE requests
    for (const r of ppeRequests) {
      list.push({
        key:      `ppe-req:${r.id}`,
        type:     'warning',
        category: 'Requests',
        module:   'PPE',
        title:    `Pending PPE request — ${r.ppe_item_name}`,
        desc:     `${r.emp_name} (${r.emp_id}) from ${r.department} requesting ${r.qty} unit(s). Contact: ${r.contact || '—'}`,
        time:     r.submitted_at,
        nav:      'ppe',
      });
    }

    // Warning: pending borrow requests
    for (const r of borrowRequests) {
      list.push({
        key:      `borrow-req:${r.id}`,
        type:     'warning',
        category: 'Requests',
        module:   'Calibration',
        title:    `Pending borrow request — ${r.device_name}`,
        desc:     `${r.requester_name} from ${r.department} requesting to borrow for ${r.duration}. Contact: ${r.contact || '—'}${r.reason ? ` · ${r.reason}` : ''}`,
        time:     r.submitted_at,
        nav:      'calibration',
      });
    }

    // Info: calibration records with issues
    for (const c of calIssues) {
      const eq = equipment.find(e => e.id === c.equipment_id);
      list.push({
        key:      `cal-issue:${c.id}`,
        type:     'info',
        category: 'Calibration',
        module:   'Calibration',
        title:    `Calibration issue logged — ${eq?.name || 'Unknown equipment'}`,
        desc:     c.issue_note || `Result: ${c.result}. Lab: ${c.lab_provider || '—'}.`,
        time:     c.created_at || c.cal_date,
        nav:      'calibration',
      });
    }

    // Anomaly: excessive PPE issuance per employee (≥5 issuances in 30 days)
    for (const a of excessiveIssuance) {
      list.push({
        key:      `anom-excess:${a.emp_id}`,
        type:     a.issuance_count >= 10 ? 'critical' : 'warning',
        category: 'Anomaly',
        module:   'PPE',
        title:    `Unusual issuance pattern — ${a.emp_name}`,
        desc:     `${a.emp_name} (${a.emp_id}, ${a.department}) received ${a.issuance_count} PPE issuances totalling ${a.total_qty} units in the last 30 days. Possible misuse, role change, or operational pattern worth reviewing. Items: ${a.items_issued || '—'}`,
        time:     a.last_issued,
        nav:      'ppe',
      });
    }

    // Anomaly: repeated calibration failures on same device
    for (const a of calFailures) {
      list.push({
        key:      `anom-fail:${a.equipment_id}`,
        type:     'critical',
        category: 'Anomaly',
        module:   'Calibration',
        title:    `Repeated calibration failures — ${a.equipment_name}`,
        desc:     `Serial ${a.serial_number} has failed ${a.fail_count} of ${a.total_cals} calibrations in the last 180 days. Last failure: ${a.last_fail_date ? new Date(a.last_fail_date).toLocaleDateString('en-GB') : 'unknown'}. ${a.issue_notes ? 'Notes: ' + a.issue_notes : 'Consider replacement or full inspection.'}`,
        time:     a.last_fail_date,
        nav:      'calibration',
      });
    }

    // Sort: type priority (critical > warning > info), then time desc
    const order = { critical: 0, warning: 1, info: 2 };
    list.sort((a, b) => {
      const ord = order[a.type] - order[b.type];
      if (ord !== 0) return ord;
      return new Date(b.time || 0) - new Date(a.time || 0);
    });
    return list;
  }, [equipment, ppeInventory, ppeRequests, borrowRequests, calIssues, excessiveIssuance, calFailures]);

  // Apply dismissal filter + category filter
  const visibleAlerts = allAlerts.filter(a => {
    if (dismissed.has(a.key)) return false;
    if (activeFilter === 'All') return true;
    if (activeFilter === 'Critical')   return a.type === 'critical';
    if (activeFilter === 'Warning')    return a.type === 'warning';
    if (activeFilter === 'Info')       return a.type === 'info';
    if (activeFilter === 'Calibration') return a.category === 'Calibration';
    if (activeFilter === 'PPE')        return a.category === 'PPE';
    if (activeFilter === 'Requests')   return a.category === 'Requests';
    if (activeFilter === 'Anomaly')    return a.category === 'Anomaly';
    return true;
  });

  const totalUnread = allAlerts.filter(a => !dismissed.has(a.key)).length;
  const dismissedCount = allAlerts.filter(a => dismissed.has(a.key)).length;

  const filters = ['All', 'Critical', 'Warning', 'Info', 'Anomaly', 'Calibration', 'PPE', 'Requests'];

  if (loading) return (
    <div style={alertScreenStyles.page}>
      <div style={alertScreenStyles.empty}>Loading alerts…</div>
    </div>
  );

  return (
    <div style={alertScreenStyles.page}>
      {error && (
        <div style={{ background: '#FFF5F5', border: '1px solid #FECACA', color: '#DC2626', padding: '10px 14px', borderRadius: 6, fontSize: 12, marginBottom: 16 }}>{error}</div>
      )}

      <div style={alertScreenStyles.filters}>
        {filters.map(f => {
          let count = 0;
          if (f === 'All')              count = totalUnread;
          else if (f === 'Critical')    count = allAlerts.filter(a => !dismissed.has(a.key) && a.type === 'critical').length;
          else if (f === 'Warning')     count = allAlerts.filter(a => !dismissed.has(a.key) && a.type === 'warning').length;
          else if (f === 'Info')        count = allAlerts.filter(a => !dismissed.has(a.key) && a.type === 'info').length;
          else                          count = allAlerts.filter(a => !dismissed.has(a.key) && a.category === f).length;
          return (
            <button
              key={f}
              style={{ ...alertScreenStyles.filterChip, ...(activeFilter === f ? alertScreenStyles.filterChipActive : {}) }}
              onClick={() => setActiveFilter(f)}
            >
              {f} {count > 0 && <span style={{ marginLeft: 4, opacity: 0.7 }}>({count})</span>}
            </button>
          );
        })}
        <div style={alertScreenStyles.countText}>
          <span>{totalUnread} active</span>
          {dismissedCount > 0 && (
            <span style={alertScreenStyles.clearLink} onClick={handleClearAllDismissed}>
              Show {dismissedCount} dismissed
            </span>
          )}
        </div>
      </div>

      <div style={alertScreenStyles.alertsList}>
        {visibleAlerts.length === 0 ? (
          <div style={alertScreenStyles.empty}>
            <div style={alertScreenStyles.emptyIcon}>
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#16A34A" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
            </div>
            <div style={{ fontSize: 14, fontWeight: 600, color: '#334155', marginBottom: 4 }}>
              {allAlerts.length === 0 ? 'All clear!' : 'No alerts match this filter.'}
            </div>
            <div style={{ fontSize: 12, color: '#94A3B8' }}>
              {allAlerts.length === 0
                ? 'No expired equipment, no low stock, no pending requests.'
                : 'Try selecting a different filter above.'}
            </div>
          </div>
        ) : visibleAlerts.map((a) => {
          const cfg = alertConfig[a.type];
          return (
            <div
              key={a.key}
              style={{ ...alertScreenStyles.alertCard, background: cfg.bg, borderLeft: `3px solid ${cfg.iconColor}` }}
              onClick={() => onNav?.(a.nav)}
            >
              <div style={{ ...alertScreenStyles.alertIconWrap, background: cfg.iconBg, color: cfg.iconColor }}>
                <AlertIcon type={a.type} />
              </div>
              <div style={alertScreenStyles.alertContent}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                  <span style={{ ...alertScreenStyles.badge, background: cfg.badgeBg, color: cfg.badgeColor }}>{cfg.label}</span>
                  <span style={{ fontSize: 11, color: '#94A3B8' }}>{a.module}</span>
                </div>
                <div style={alertScreenStyles.alertTitle}>{a.title}</div>
                <div style={alertScreenStyles.alertDesc}>{a.desc}</div>
                <div style={alertScreenStyles.alertMeta}>{alertFmtDate(a.time)}</div>
              </div>
              <div style={alertScreenStyles.alertActions} onClick={e => e.stopPropagation()}>
                <button style={alertScreenStyles.alertBtn} onClick={() => handleDismiss(a.key)}>Dismiss</button>
                <button
                  style={{ ...alertScreenStyles.alertBtn, ...alertScreenStyles.alertBtnPrimary }}
                  onClick={() => onNav?.(a.nav)}
                >
                  {a.type === 'info' ? 'View' : 'Resolve'}
                </button>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { AlertsScreen });
