// PatientList.jsx – ADPKD Cohort View
const { useState, useMemo } = React;

const MAYO_COLORS = { '1A':'#6B9E78', '1B':'#4A8C6F', '1C':'#C77700', '1D':'#D06020', '1E':'#D32027' };
const RISK_COLORS = { 'Rapid':'#D32027', 'Intermediate':'#C77700', 'Slow':'#2E7D5B' };
const DECISION_COLORS = { 'Eligible':'#2E7D5B', 'Review':'#C77700', 'Not Eligible':'#D32027' };

function Sparkline({ data, color }) {
  const vals = data.map(d => d.v);
  const min = Math.min(...vals), max = Math.max(...vals);
  const range = max - min || 1;
  const W = 72, H = 24;
  const pts = vals.map((v, i) => {
    const x = (i / (vals.length - 1)) * W;
    const y = H - ((v - min) / range) * (H - 4) - 2;
    return `${x.toFixed(1)},${y.toFixed(1)}`;
  }).join(' ');
  const isDown = vals[vals.length - 1] < vals[0];
  const lineColor = color || (isDown ? '#D32027' : '#2E7D5B');
  return (
    <svg width={W} height={H} viewBox={`0 0 ${W} ${H}`} style={{display:'block'}}>
      <polyline points={pts} fill="none" stroke={lineColor} strokeWidth={1.5}
        strokeLinecap="round" strokeLinejoin="round"/>
      <circle cx={pts.split(' ').pop().split(',')[0]} cy={pts.split(' ').pop().split(',')[1]}
        r={2.5} fill={lineColor}/>
    </svg>
  );
}

function CompletenessBar({ value }) {
  const color = value >= 90 ? '#2E7D5B' : value >= 75 ? '#C77700' : '#D32027';
  return (
    <div style={{display:'flex', alignItems:'center', gap:6}}>
      <div style={{width:52, height:5, background:'#E5E5E7', borderRadius:3, overflow:'hidden'}}>
        <div style={{width:`${value}%`, height:'100%', background:color, borderRadius:3}}/>
      </div>
      <span style={{fontSize:11, color:'#4A4A4A', fontVariantNumeric:'tabular-nums'}}>{value}%</span>
    </div>
  );
}

function Badge({ label, color, bg }) {
  return (
    <span style={{
      display:'inline-block', padding:'2px 7px', borderRadius:3, fontSize:11,
      fontWeight:600, color: color || '#fff', background: bg || '#4A4A4A',
      letterSpacing:'0.02em', lineHeight:'16px'
    }}>{label}</span>
  );
}

function SortIcon({ col, sortCol, sortDir }) {
  const active = col === sortCol;
  return (
    <span style={{marginLeft:4, opacity: active ? 1 : 0.3, fontSize:10, color: active ? '#D32027' : '#4A4A4A'}}>
      {active && sortDir === 'asc' ? '▲' : '▼'}
    </span>
  );
}

function PatientList({ patients, selectedId, onSelect, onNavigate }) {
  const [sortCol, setSortCol] = useState('riskTier');
  const [sortDir, setSortDir] = useState('asc');
  const [filter, setFilter] = useState('');

  function handleSort(col) {
    if (col === sortCol) setSortDir(d => d === 'asc' ? 'desc' : 'asc');
    else { setSortCol(col); setSortDir('asc'); }
  }

  const riskOrder = { 'Rapid': 0, 'Intermediate': 1, 'Slow': 2 };
  const decisionOrder = { 'Eligible': 0, 'Review': 1, 'Not Eligible': 2 };

  const sorted = useMemo(() => {
    let data = patients.filter(p =>
      !filter || p.alias.toLowerCase().includes(filter.toLowerCase()) ||
      p.id.toLowerCase().includes(filter.toLowerCase()) ||
      p.pkdVariant.toLowerCase().includes(filter.toLowerCase())
    );
    data = [...data].sort((a, b) => {
      let av = a[sortCol], bv = b[sortCol];
      if (sortCol === 'riskTier') { av = riskOrder[a.riskTier]; bv = riskOrder[b.riskTier]; }
      if (sortCol === 'decision') { av = decisionOrder[a.decision]; bv = decisionOrder[b.decision]; }
      if (typeof av === 'string') return sortDir === 'asc' ? av.localeCompare(bv) : bv.localeCompare(av);
      return sortDir === 'asc' ? av - bv : bv - av;
    });
    return data;
  }, [patients, sortCol, sortDir, filter]);

  const cols = [
    { key:'id', label:'Patient ID', w:90 },
    { key:'age', label:'Age', w:52 },
    { key:'sex', label:'Sex', w:44 },
    { key:'egfr', label:'eGFR trend', w:120 },
    { key:'htTKV', label:'htTKV (ml/m)', w:100 },
    { key:'mayoClass', label:'Mayo', w:62 },
    { key:'pkdVariant', label:'PKD variant', w:148 },
    { key:'riskTier', label:'Risk tier', w:110 },
    { key:'decision', label:'Decision', w:100 },
    { key:'lastUpdate', label:'Last update', w:100 },
    { key:'completeness', label:'Completeness', w:110 },
  ];

  const thStyle = (key) => ({
    padding:'8px 10px', textAlign:'left', fontSize:11, fontWeight:600,
    color:'#4A4A4A', textTransform:'uppercase', letterSpacing:'0.06em',
    whiteSpace:'nowrap', cursor:'pointer', userSelect:'none',
    borderBottom:'2px solid #E5E5E7', background:'#F7F7F8',
    position:'sticky', top:0, zIndex:1
  });

  return (
    <div style={{display:'flex', flexDirection:'column', height:'100%'}}>
      {/* Header */}
      <div style={{padding:'20px 24px 16px', borderBottom:'1px solid #E5E5E7', background:'#fff'}}>
        <div style={{display:'flex', alignItems:'center', justifyContent:'space-between'}}>
          <div>
            <h1 style={{fontSize:18, fontWeight:700, color:'#1A1A1A', marginBottom:2}}>ADPKD Patient Cohort</h1>
            <p style={{fontSize:13, color:'#4A4A4A'}}>
              {sorted.length} of {patients.length} patients · Tolvaptan eligibility pipeline
            </p>
          </div>
          <div style={{display:'flex', gap:8, alignItems:'center'}}>
            <input
              value={filter} onChange={e => setFilter(e.target.value)}
              placeholder="Filter patients…"
              style={{
                padding:'6px 10px', border:'1px solid #E5E5E7', borderRadius:4,
                fontSize:13, color:'#1A1A1A', outline:'none', width:200,
                background:'#F7F7F8'
              }}
            />
            <div style={{display:'flex', gap:6}}>
              {['Rapid','Intermediate','Slow'].map(tier => (
                <span key={tier} style={{
                  fontSize:11, fontWeight:600, padding:'3px 8px', borderRadius:3,
                  background: tier === 'Rapid' ? '#FEF2F2' : tier === 'Intermediate' ? '#FFFBEB' : '#F0FDF4',
                  color: RISK_COLORS[tier], border:`1px solid ${RISK_COLORS[tier]}33`
                }}>
                  {patients.filter(p=>p.riskTier===tier).length} {tier}
                </span>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* Table */}
      <div style={{flex:1, overflowY:'auto', overflowX:'auto'}}>
        <table style={{width:'100%', borderCollapse:'collapse', fontSize:13}}>
          <thead>
            <tr>
              {cols.map(c => (
                <th key={c.key} style={{...thStyle(c.key), minWidth:c.w}}
                  onClick={() => handleSort(c.key)}>
                  {c.label}<SortIcon col={c.key} sortCol={sortCol} sortDir={sortDir}/>
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {sorted.map((p, idx) => {
              const isSelected = p.id === selectedId;
              return (
                <tr key={p.id}
                  onClick={() => { onSelect(p.id); onNavigate('dashboard'); }}
                  style={{
                    background: isSelected ? '#FEF8F8' : idx % 2 === 0 ? '#fff' : '#FAFAFA',
                    borderLeft: isSelected ? '3px solid #D32027' : '3px solid transparent',
                    cursor:'pointer', transition:'background 0.1s'
                  }}
                  onMouseEnter={e => { if(!isSelected) e.currentTarget.style.background='#F7F7F8'; }}
                  onMouseLeave={e => { if(!isSelected) e.currentTarget.style.background = idx%2===0?'#fff':'#FAFAFA'; }}
                >
                  <td style={{padding:'10px 10px', borderBottom:'1px solid #E5E5E7'}}>
                    <span style={{fontWeight:600, color:'#1A1A1A', fontFamily:'monospace', fontSize:12}}>{p.id}</span>
                    <div style={{fontSize:11, color:'#4A4A4A', marginTop:1}}>{p.alias}</div>
                  </td>
                  <td style={{padding:'10px 10px', borderBottom:'1px solid #E5E5E7', color:'#1A1A1A'}}>{p.age}</td>
                  <td style={{padding:'10px 10px', borderBottom:'1px solid #E5E5E7', color:'#4A4A4A'}}>{p.sex}</td>
                  <td style={{padding:'8px 10px', borderBottom:'1px solid #E5E5E7'}}>
                    <div style={{display:'flex', alignItems:'center', gap:8}}>
                      <Sparkline data={p.egfrTrend}/>
                      <span style={{fontSize:12, fontWeight:600, color:'#1A1A1A', fontVariantNumeric:'tabular-nums'}}>{p.egfr}</span>
                    </div>
                  </td>
                  <td style={{padding:'10px 10px', borderBottom:'1px solid #E5E5E7', fontVariantNumeric:'tabular-nums', color:'#1A1A1A', fontWeight:500}}>{p.htTKV}</td>
                  <td style={{padding:'10px 10px', borderBottom:'1px solid #E5E5E7'}}>
                    <Badge label={p.mayoClass} color='#fff' bg={MAYO_COLORS[p.mayoClass]}/>
                  </td>
                  <td style={{padding:'10px 10px', borderBottom:'1px solid #E5E5E7', fontSize:12, color:'#4A4A4A'}}>{p.pkdVariant}</td>
                  <td style={{padding:'10px 10px', borderBottom:'1px solid #E5E5E7'}}>
                    <span style={{
                      fontSize:11, fontWeight:600, padding:'2px 8px', borderRadius:3,
                      background: p.riskTier==='Rapid'?'#FEF2F2':p.riskTier==='Intermediate'?'#FFFBEB':'#F0FDF4',
                      color: RISK_COLORS[p.riskTier]
                    }}>{p.riskTier}</span>
                  </td>
                  <td style={{padding:'10px 10px', borderBottom:'1px solid #E5E5E7'}}>
                    <span style={{
                      fontSize:11, fontWeight:600, padding:'2px 8px', borderRadius:3,
                      background: p.decision==='Eligible'?'#F0FDF4':p.decision==='Review'?'#FFFBEB':'#FEF2F2',
                      color: DECISION_COLORS[p.decision]
                    }}>{p.decision}</span>
                  </td>
                  <td style={{padding:'10px 10px', borderBottom:'1px solid #E5E5E7', fontSize:12, color:'#4A4A4A', whiteSpace:'nowrap'}}>{p.lastUpdate}</td>
                  <td style={{padding:'10px 10px', borderBottom:'1px solid #E5E5E7'}}>
                    <CompletenessBar value={p.completeness}/>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {/* Footer */}
      <div style={{padding:'10px 24px', borderTop:'1px solid #E5E5E7', background:'#F7F7F8', fontSize:11, color:'#4A4A4A', display:'flex', gap:24}}>
        <span>Source: MeDIC FHIR R4 · UKK · Last sync: 2026-04-18 06:12</span>
        <span style={{marginLeft:'auto'}}>Click any row to open Patient Dashboard</span>
      </div>
    </div>
  );
}

Object.assign(window, { PatientList });
