// DashboardScreen.jsx — AegisComply (Supabase-powered, real-time)

const dsStyles = {
  page: { padding: 24 },
  grid4: { display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 },
  grid3: { display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 16, marginBottom: 24 },
  grid2: { display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 },
  card: { background: 'white', border: '1px solid #E2E8F0', borderRadius: 8, padding: '16px 20px', boxShadow: '0 1px 3px rgba(0,0,0,0.06)' },
  cardHeader: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 },
  cardLabel: { fontSize: 10, fontWeight: 600, letterSpacing: '0.1em', textTransform: 'uppercase', color: '#94A3B8' },
  cardAction: { fontSize: 12, color: '#0D9488', fontWeight: 500, cursor: 'pointer' },
  statVal: { fontFamily: "'Helvetica', Arial, sans-serif", fontSize: 34, fontWeight: 700, color: '#0F172A', lineHeight: 1, marginBottom: 4 },
  statSub: { fontSize: 12, color: '#64748B' },
  trendUp: { color: '#16A34A', fontWeight: 600 },
  trendDn: { color: '#DC2626', fontWeight: 600 },
  badge: { display: 'inline-flex', alignItems: 'center', gap: 4, padding: '2px 8px', borderRadius: 4, fontSize: 11, fontWeight: 600, letterSpacing: '0.05em', textTransform: 'uppercase' },
  ring: { width: 80, height: 80, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center' },
  ringInner: { width: 60, height: 60, borderRadius: '50%', background: 'white', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' },
  ringNum: { fontFamily: "'Helvetica', Arial, sans-serif", fontSize: 16, fontWeight: 700, color: '#0F172A', lineHeight: 1 },
  ringLabel: { fontSize: 9, color: '#94A3B8', letterSpacing: '0.05em' },
  alertRow: { display: 'flex', alignItems: 'flex-start', gap: 10, padding: '10px 0', borderBottom: '1px solid #F1F5F9' },
  alertDot: { width: 8, height: 8, borderRadius: '50%', marginTop: 5, flexShrink: 0 },
  alertTitle: { fontSize: 13, fontWeight: 500, color: '#0F172A', lineHeight: 1.3 },
  alertMeta: { fontSize: 11, color: '#94A3B8', marginTop: 2 },
  tableHead: { display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr', gap: 8, padding: '8px 12px', background: '#F8FAFC', borderRadius: '6px 6px 0 0', borderBottom: '1px solid #E2E8F0' },
  tableHeadCell: { fontSize: 11, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: '#94A3B8' },
  tableRow: { display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr', gap: 8, padding: '9px 12px', borderBottom: '1px solid #F1F5F9' },
  tableCell: { fontSize: 13, color: '#334155' },
  deptRow: { display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 },
  deptLabel: { fontSize: 12, fontWeight: 500, color: '#334155', minWidth: 100, flexShrink: 0 },
  deptBarWrap: { flex: 1, height: 10, background: '#F1F5F9', borderRadius: 5, overflow: 'hidden' },
  deptBar: { height: '100%', borderRadius: 5 },
  deptCount: { fontSize: 12, fontWeight: 600, color: '#0F172A', minWidth: 32, textAlign: 'right' },
  deptPct: { fontSize: 11, color: '#94A3B8', minWidth: 36, textAlign: 'right' },
  empty: { padding: '20px 0', textAlign: 'center', color: '#94A3B8', fontSize: 12 },
};

const DEPT_COLORS = ['#0D9488', '#2E5A87', '#D97706', '#7AABCC', '#94A3B8', '#CBD5E1', '#9333EA', '#0EA5E9', '#65A30D'];

function dsFmtDate(d) {
  if (!d) return '—';
  try { return new Date(d).toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: 'numeric' }); }
  catch { return d; }
}

function dsRelativeTime(d) {
  if (!d) return '';
  const now = new Date();
  const then = new Date(d);
  const diffMs = now - then;
  const diffMin = Math.floor(diffMs / 60000);
  const diffHr  = Math.floor(diffMin / 60);
  const diffDay = Math.floor(diffHr / 24);
  if (diffMin < 1)  return 'just now';
  if (diffMin < 60) return `${diffMin}m ago`;
  if (diffHr < 24)  return `${diffHr}h ago`;
  if (diffDay < 7)  return `${diffDay}d ago`;
  return dsFmtDate(d);
}

function StatusBadge({ status }) {
  const map = {
    active:              { bg: '#F0FDF4', color: '#16A34A', dot: '#16A34A', label: 'Active' },
    valid:               { bg: '#F0FDF4', color: '#16A34A', dot: '#16A34A', label: 'Active' },
    expiring:            { bg: '#FFFBEB', color: '#D97706', dot: '#D97706', label: 'Expiring' },
    overdue:             { bg: '#FFF7ED', color: '#EA580C', dot: '#EA580C', label: 'Overdue' },
    expired:             { bg: '#FFF5F5', color: '#DC2626', dot: '#DC2626', label: 'Expired' },
    pending_calibration: { bg: '#F1F5F9', color: '#475569', dot: '#475569', label: 'Pending' },
  };
  const s = map[status] || map.active;
  return (
    <span style={{ ...dsStyles.badge, background: s.bg, color: s.color }}>
      <span style={{ width: 6, height: 6, borderRadius: '50%', background: s.dot, display: 'inline-block' }}/>
      {s.label}
    </span>
  );
}

function ComplianceRing({ score }) {
  const color = score >= 85 ? '#0D9488' : score >= 60 ? '#D97706' : '#DC2626';
  return (
    <div style={{ ...dsStyles.ring, background: `conic-gradient(${color} 0% ${score}%, #E2E8F0 ${score}% 100%)` }}>
      <div style={dsStyles.ringInner}>
        <span style={dsStyles.ringNum}>{score}%</span>
        <span style={dsStyles.ringLabel}>SCORE</span>
      </div>
    </div>
  );
}

// ── Main Dashboard ──────────────────────────────────────────────────────────
function DashboardScreen({ onNav, user }) {
  const [equipment, setEquipment] = React.useState([]);
  const [ppeInventory, setPPEInventory] = React.useState([]);
  const [recentIssuances, setRecentIssuances] = React.useState([]);
  const [pendingRequests, setPendingRequests] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError]     = React.useState('');

  const load = React.useCallback(async () => {
    try {
      const sb = window.supabaseClient;
      if (!sb) throw new Error('Supabase client not initialised');
      const [eq, ppe, iss, req] = await Promise.all([
        sb.from('equipment').select('id,name,category,calibration_due,status,created_at').order('created_at', { ascending: false }),
        sb.from('ppe_inventory').select('id,name,category,size,stock,issued,balance,min_stock,status,item_code'),
        sb.from('ppe_issuance').select('id,ppe_item_name,size,qty,emp_name,department,issued_at').order('issued_at', { ascending: false }).limit(50),
        sb.from('ppe_requests').select('id,emp_name,ppe_item_name,qty,submitted_at,status').eq('status', 'pending').order('submitted_at', { ascending: false }).limit(5),
      ]);
      if (eq.error)  throw eq.error;
      if (ppe.error) throw ppe.error;
      if (iss.error) throw iss.error;
      if (req.error) throw req.error;
      setEquipment(eq.data || []);
      setPPEInventory(ppe.data || []);
      setRecentIssuances(iss.data || []);
      setPendingRequests(req.data || []);
    } catch (err) {
      console.error('[Dashboard] load error:', err);
      setError(err.message || 'Failed to load dashboard.');
    } finally {
      setLoading(false);
    }
  }, []);

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

  // Realtime — refresh on any change to equipment, ppe_inventory, ppe_issuance, ppe_requests
  React.useEffect(() => {
    if (!user) return;
    const sb = window.supabaseClient;
    if (!sb) return;
    const ch = sb.channel(`dashboard-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_issuance',  filter: `user_id=eq.${user.id}` },    () => load())
      .on('postgres_changes', { event: '*', schema: 'public', table: 'ppe_requests',  filter: `account_id=eq.${user.id}` }, () => load())
      .subscribe();
    return () => { sb.removeChannel(ch); };
  }, [user, load]);

  // ── Derived metrics ──────────────────────────────────────────────────────
  const stats = React.useMemo(() => {
    const eqTotal      = equipment.length;
    const eqExpired    = equipment.filter(e => e.status === 'expired' || e.status === 'overdue').length;
    const eqExpiring   = equipment.filter(e => e.status === 'expiring').length;
    const eqPending    = equipment.filter(e => e.status === 'pending_calibration').length;
    const eqActive     = equipment.filter(e => e.status === 'active').length;
    const compliantCount = eqActive + eqPending; // active + at-lab counts as compliant
    const score        = eqTotal > 0 ? Math.round((compliantCount / eqTotal) * 100) : 100;

    const ppeLow      = ppeInventory.filter(p => p.status === 'low' || p.status === 'critical').length;
    const ppeCritical = ppeInventory.filter(p => p.status === 'critical').length;

    return { eqTotal, eqExpired, eqExpiring, eqPending, eqActive, score, ppeLow, ppeCritical };
  }, [equipment, ppeInventory]);

  // ── Department PPE consumption (aggregate from issuances) ────────────────
  const deptConsumption = React.useMemo(() => {
    const map = new Map();
    for (const iss of recentIssuances) {
      const d = iss.department || 'Unknown';
      map.set(d, (map.get(d) || 0) + (iss.qty || 0));
    }
    const arr = [...map.entries()].map(([dept, qty], i) => ({ dept, qty, color: DEPT_COLORS[i % DEPT_COLORS.length] }));
    arr.sort((a, b) => b.qty - a.qty);
    return arr.slice(0, 7);
  }, [recentIssuances]);

  // ── Top issued PPE items ─────────────────────────────────────────────────
  const topIssuedItems = React.useMemo(() => {
    const map = new Map();
    for (const iss of recentIssuances) {
      const key = iss.ppe_item_name + (iss.size ? ` [${iss.size}]` : '');
      map.set(key, (map.get(key) || 0) + (iss.qty || 0));
    }
    return [...map.entries()].map(([name, issued]) => ({ name, issued })).sort((a, b) => b.issued - a.issued).slice(0, 5);
  }, [recentIssuances]);

  // ── Recent activity feed (synthesized from real data) ────────────────────
  const recentAlerts = React.useMemo(() => {
    const alerts = [];

    // Pending PPE requests (urgent)
    for (const req of pendingRequests.slice(0, 2)) {
      alerts.push({
        color: '#0D9488',
        title: `PPE request — ${req.ppe_item_name} × ${req.qty} for ${req.emp_name}`,
        time: dsRelativeTime(req.submitted_at),
        nav: 'ppe',
      });
    }
    // Expired equipment
    for (const e of equipment.filter(e => e.status === 'expired' || e.status === 'overdue').slice(0, 2)) {
      alerts.push({
        color: '#DC2626',
        title: `Calibration ${e.status} — ${e.name}`,
        time: e.calibration_due ? `due ${dsFmtDate(e.calibration_due)}` : '',
        nav: 'equipment',
      });
    }
    // Critical PPE stock
    for (const p of ppeInventory.filter(p => p.status === 'critical').slice(0, 2)) {
      alerts.push({
        color: '#DC2626',
        title: `PPE critical — ${p.name}${p.size ? ` [${p.size}]` : ''}: ${p.balance || 0} remaining`,
        time: 'now',
        nav: 'ppe',
      });
    }
    // Expiring equipment
    for (const e of equipment.filter(e => e.status === 'expiring').slice(0, 1)) {
      alerts.push({
        color: '#D97706',
        title: `Calibration due — ${e.name}`,
        time: e.calibration_due ? dsFmtDate(e.calibration_due) : '',
        nav: 'equipment',
      });
    }
    // Recent issuance
    for (const iss of recentIssuances.slice(0, 1)) {
      alerts.push({
        color: '#64748B',
        title: `PPE issued to ${iss.emp_name} — ${iss.ppe_item_name} × ${iss.qty}`,
        time: dsRelativeTime(iss.issued_at),
        nav: 'ppe',
      });
    }

    return alerts.slice(0, 6);
  }, [equipment, ppeInventory, recentIssuances, pendingRequests]);

  // ── Recent equipment for the table ───────────────────────────────────────
  const recentEquipment = equipment.slice(0, 5);
  const deptTotal = deptConsumption.reduce((s, d) => s + d.qty, 0);
  const deptMax   = deptConsumption[0]?.qty || 1;

  if (loading) return (
    <div style={dsStyles.page}>
      <div style={{ fontSize: 14, color: '#64748B', textAlign: 'center', padding: 40 }}>Loading dashboard…</div>
    </div>
  );

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

      {/* Stat row */}
      <div style={dsStyles.grid4}>
        <div style={dsStyles.card}>
          <div style={dsStyles.cardLabel}>Compliance Score</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginTop: 12 }}>
            <ComplianceRing score={stats.score} />
            <div>
              <div style={{ fontSize: 12, color: '#64748B', marginBottom: 2 }}>{stats.eqActive + stats.eqPending} / {stats.eqTotal} compliant</div>
              <div style={dsStyles.statSub}>
                {stats.score >= 85 ? <span style={dsStyles.trendUp}>Healthy</span>
                 : stats.score >= 60 ? <span style={{ color: '#D97706', fontWeight: 600 }}>Needs attention</span>
                 : <span style={dsStyles.trendDn}>Critical</span>}
              </div>
            </div>
          </div>
        </div>
        <div style={dsStyles.card}>
          <div style={dsStyles.cardLabel}>Expired Equipment</div>
          <div style={{ ...dsStyles.statVal, color: stats.eqExpired > 0 ? '#DC2626' : '#16A34A', marginTop: 12 }}>{stats.eqExpired}</div>
          <div style={dsStyles.statSub}>{stats.eqExpired === 0 ? 'All caught up' : 'Past calibration date'}</div>
        </div>
        <div style={dsStyles.card}>
          <div style={dsStyles.cardLabel}>Calibrations Due Soon</div>
          <div style={{ ...dsStyles.statVal, color: stats.eqExpiring > 0 ? '#D97706' : '#16A34A', marginTop: 12 }}>{stats.eqExpiring}</div>
          <div style={dsStyles.statSub}>Marked as expiring</div>
        </div>
        <div style={dsStyles.card}>
          <div style={dsStyles.cardLabel}>PPE Low Stock</div>
          <div style={{ ...dsStyles.statVal, color: stats.ppeCritical > 0 ? '#DC2626' : stats.ppeLow > 0 ? '#D97706' : '#16A34A', marginTop: 12 }}>{stats.ppeLow}</div>
          <div style={dsStyles.statSub}>{stats.ppeCritical > 0 ? `${stats.ppeCritical} critical` : 'Below min threshold'}</div>
        </div>
      </div>

      {/* Equipment + alerts */}
      <div style={dsStyles.grid3}>
        <div style={dsStyles.card}>
          <div style={dsStyles.cardHeader}>
            <span style={dsStyles.cardLabel}>Recent Equipment</span>
            <span style={dsStyles.cardAction} onClick={() => onNav('equipment')}>View all →</span>
          </div>
          <div style={{ border: '1px solid #E2E8F0', borderRadius: 6, overflow: 'hidden' }}>
            <div style={dsStyles.tableHead}>
              <div style={dsStyles.tableHeadCell}>Equipment</div>
              <div style={dsStyles.tableHeadCell}>Category</div>
              <div style={dsStyles.tableHeadCell}>Cal. Due</div>
              <div style={dsStyles.tableHeadCell}>Status</div>
            </div>
            {recentEquipment.length === 0 ? (
              <div style={dsStyles.empty}>No equipment yet. Add some on the Equipment page.</div>
            ) : recentEquipment.map((r, i) => (
              <div key={r.id} style={{ ...dsStyles.tableRow, background: i % 2 === 0 ? 'white' : '#FAFCFF', cursor: 'pointer' }} onClick={() => onNav('equipment')}>
                <div style={{ ...dsStyles.tableCell, fontWeight: 500 }}>{r.name}</div>
                <div style={{ ...dsStyles.tableCell, color: '#64748B' }}>{r.category || '—'}</div>
                <div style={{ ...dsStyles.tableCell, color: '#64748B', fontSize: 12 }}>{dsFmtDate(r.calibration_due)}</div>
                <div><StatusBadge status={r.status} /></div>
              </div>
            ))}
          </div>
        </div>
        <div style={dsStyles.card}>
          <div style={dsStyles.cardHeader}>
            <span style={dsStyles.cardLabel}>Recent Alerts</span>
            <span style={dsStyles.cardAction} onClick={() => onNav('alerts')}>View all →</span>
          </div>
          {recentAlerts.length === 0 ? (
            <div style={dsStyles.empty}>No alerts — everything looks good.</div>
          ) : recentAlerts.map((a, i) => (
            <div key={i}
              style={{ ...dsStyles.alertRow, ...(i === recentAlerts.length - 1 ? { borderBottom: 'none' } : {}), cursor: 'pointer' }}
              onClick={() => a.nav && onNav(a.nav)}>
              <span style={{ ...dsStyles.alertDot, background: a.color }} />
              <div>
                <div style={dsStyles.alertTitle}>{a.title}</div>
                <div style={dsStyles.alertMeta}>{a.time}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* PPE Dept Consumption + Cal Status */}
      <div style={dsStyles.grid2}>
        <div style={dsStyles.card}>
          <div style={dsStyles.cardHeader}>
            <span style={dsStyles.cardLabel}>PPE Consumption by Department</span>
            <span style={dsStyles.cardAction} onClick={() => onNav('ppe')}>View PPE →</span>
          </div>
          {deptConsumption.length === 0 ? (
            <div style={dsStyles.empty}>No PPE issuances yet. Issue some PPE to populate this chart.</div>
          ) : (
            <>
              {deptConsumption.map((d, i) => (
                <div key={i} style={dsStyles.deptRow}>
                  <span style={dsStyles.deptLabel}>{d.dept}</span>
                  <div style={dsStyles.deptBarWrap}>
                    <div style={{ ...dsStyles.deptBar, width: `${(d.qty / deptMax) * 100}%`, background: d.color }}/>
                  </div>
                  <span style={dsStyles.deptCount}>{d.qty}</span>
                  <span style={dsStyles.deptPct}>{Math.round((d.qty / deptTotal) * 100)}%</span>
                </div>
              ))}
              {topIssuedItems.length > 0 && (
                <div style={{ marginTop: 12, paddingTop: 12, borderTop: '1px solid #F1F5F9' }}>
                  <div style={{ ...dsStyles.cardLabel, marginBottom: 8 }}>Top Issued Items</div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                    {topIssuedItems.map((item, i) => (
                      <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 6, background: '#F8FAFC', border: '1px solid #E2E8F0', borderRadius: 5, padding: '4px 8px' }}>
                        <span style={{ fontSize: 12, color: '#334155', fontWeight: 500 }}>{item.name}</span>
                        <span style={{ fontSize: 11, fontWeight: 700, color: '#0D9488', background: '#F0FDFA', padding: '1px 5px', borderRadius: 3 }}>{item.issued}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </>
          )}
        </div>

        <div style={dsStyles.card}>
          <div style={dsStyles.cardHeader}>
            <span style={dsStyles.cardLabel}>Equipment Status Overview</span>
            <span style={dsStyles.cardAction} onClick={() => onNav('equipment')}>View all →</span>
          </div>
          {stats.eqTotal === 0 ? (
            <div style={dsStyles.empty}>No equipment yet.</div>
          ) : (
            <>
              {[
                { label: 'Active',     count: stats.eqActive,                  color: '#16A34A', bg: '#F0FDF4' },
                { label: 'Expiring',   count: stats.eqExpiring,                color: '#D97706', bg: '#FFFBEB' },
                { label: 'Overdue / Expired', count: stats.eqExpired,          color: '#DC2626', bg: '#FFF5F5' },
                { label: 'At Lab',     count: stats.eqPending,                 color: '#475569', bg: '#F1F5F9' },
              ].map((s, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 14 }}>
                  <div style={{ width: 36, height: 36, borderRadius: 8, background: s.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                    <span style={{ fontFamily: "'Helvetica', Arial, sans-serif", fontSize: 14, fontWeight: 700, color: s.color }}>{s.count}</span>
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                      <span style={{ fontSize: 12, fontWeight: 500, color: '#334155' }}>{s.label}</span>
                      <span style={{ fontSize: 11, color: '#94A3B8' }}>{stats.eqTotal > 0 ? Math.round((s.count / stats.eqTotal) * 100) : 0}%</span>
                    </div>
                    <div style={{ height: 6, background: '#F1F5F9', borderRadius: 3, overflow: 'hidden' }}>
                      <div style={{ height: '100%', borderRadius: 3, background: s.color, width: `${stats.eqTotal > 0 ? (s.count / stats.eqTotal) * 100 : 0}%` }}/>
                    </div>
                  </div>
                </div>
              ))}
              <div style={{ borderTop: '1px solid #F1F5F9', paddingTop: 12, marginTop: 4, fontSize: 12, color: '#64748B' }}>
                {stats.eqTotal} equipment total &nbsp;·&nbsp; Updated live
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { DashboardScreen, StatusBadge });
