/* global React, V2Icon */
const { useState: useStateC } = React;

function V2ContextPanel({ patient, draft, ai, onUndoGeneration }) {
  const showGen = !!(draft && ai && (draft.state === 'ai_draft_ready' || draft.state === 'user_reviewed'));
  return (
    <aside style={{
      width: 320, flexShrink: 0,
      background: '#fff',
      borderLeft: '1px solid var(--sage-200)',
      display: 'flex', flexDirection: 'column',
      minHeight: 0,
    }}>
      <div style={{ flex: 1, overflowY: 'auto' }}>
        {showGen && (
          <GenerationContext draft={draft} ai={ai} onUndo={onUndoGeneration} />
        )}

        <div style={{
          padding: '10px 14px',
          borderBottom: '1px solid var(--sage-200)',
          borderTop: showGen ? '1px solid var(--sage-200)' : '0',
          background: 'var(--sage-50)',
          display: 'flex', alignItems: 'center', gap: 8,
          flexShrink: 0,
          position: 'sticky', top: 0, zIndex: 1,
        }}>
          <V2Icon name="user" size={13} stroke="var(--sage-600)" />
          <span style={{
            fontSize: 11, fontWeight: 700,
            letterSpacing: '0.06em', textTransform: 'uppercase',
            color: 'var(--sage-700)',
          }}>Patient context</span>
          <div style={{ flex: 1 }} />
          <button style={{
            background: 'transparent', border: 0, padding: 3,
            color: 'var(--sage-500)', cursor: 'pointer', display: 'flex',
          }}>
            <V2Icon name="dotMenu" size={14} />
          </button>
        </div>

        <div style={{ padding: '6px 10px 16px 10px' }}>
        <ContextSection title="PMHx" count={(patient.pmhx || []).length} defaultOpen>
          {(patient.pmhx || []).map(it => (
            <Line key={it.id} label={it.label} detail={it.detail} />
          ))}
        </ContextSection>

        <ContextSection title="Medications" count={(patient.meds || []).length} defaultOpen
          icon="pill">
          {(patient.meds || []).map(m => (
            <Line key={m.id} label={m.label}
              detail={m.detail}
              detailTone={m.detail && m.detail.includes('hold') ? 'warn' : undefined}
            />
          ))}
        </ContextSection>

        <ContextSection title="Issues" count={(patient.issues || []).length} icon="alertTriangle">
          {(patient.issues || []).map(i => (
            <Line key={i.id} label={i.label} detail={i.stale ? 'stale' : ''} detailTone={i.stale ? 'warn' : undefined} />
          ))}
        </ContextSection>

        <ContextSection title="Uploaded context" count={(patient.uploads || []).length} icon="folder">
          {(patient.uploads || []).map(u => (
            <Line key={u.id} label={u.label} detail={u.date} icon="attach" />
          ))}
          <button style={{
            display: 'flex', alignItems: 'center', gap: 5,
            padding: '6px 8px', marginTop: 4,
            background: 'transparent', border: '1px dashed var(--sage-300)',
            borderRadius: 6, color: 'var(--sage-500)',
            cursor: 'pointer', width: '100%',
            fontSize: 11.5, fontFamily: 'var(--font-sans)',
            justifyContent: 'center',
          }}>
            <V2Icon name="plus" size={11} />
            Upload file
          </button>
        </ContextSection>
        </div>
      </div>
    </aside>
  );
}

function GenerationContext({ draft, ai, onUndo }) {
  const [showInput, setShowInput] = useStateC(false);
  const sources = ai?.sources || [];
  return (
    <div style={{ background: 'var(--ai-surface)', borderBottom: '1px solid var(--ai-border)' }}>
      <div style={{
        padding: '10px 14px',
        display: 'flex', alignItems: 'center', gap: 8,
      }}>
        <V2Icon name="sparkle" size={13} stroke="var(--ai)" fill="var(--ai)" />
        <span style={{
          fontSize: 11, fontWeight: 700,
          letterSpacing: '0.06em', textTransform: 'uppercase',
          color: 'var(--ai-text)',
        }}>Generation context</span>
        <div style={{ flex: 1 }} />
        <span style={{
          fontSize: 10, color: 'var(--ai-text)', opacity: 0.7,
          fontFamily: 'var(--font-mono)',
        }}>Generated Today · {draft.startedAt?.replace('Today · ', '') || ''}</span>
      </div>

      <div style={{ padding: '0 12px 12px 12px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {/* Original input */}
        <div style={{
          background: '#fff',
          border: '1px solid var(--ai-border)',
          borderRadius: 6,
          overflow: 'hidden',
        }}>
          <button
            onClick={() => setShowInput(s => !s)}
            style={{
              width: '100%', display: 'flex', alignItems: 'center', gap: 6,
              padding: '7px 10px', border: 0, background: 'transparent',
              cursor: 'pointer', fontFamily: 'var(--font-sans)',
            }}
          >
            <V2Icon name="pencilOutline" size={11} stroke="var(--sage-500)" />
            <span style={{
              fontSize: 10.5, fontWeight: 700,
              letterSpacing: '0.06em', textTransform: 'uppercase',
              color: 'var(--sage-700)',
            }}>Original input</span>
            <div style={{ flex: 1 }} />
            <V2Icon name={showInput ? 'chevronUp' : 'chevronDown'} size={12} stroke="var(--sage-500)" />
          </button>
          {showInput && (
            <div style={{
              padding: '0 12px 10px 12px',
              fontFamily: 'var(--font-serif)', fontStyle: 'italic',
              fontSize: 12, lineHeight: 1.5,
              color: 'var(--sage-700)', whiteSpace: 'pre-wrap',
              borderTop: '1px dashed var(--sage-200)',
              paddingTop: 8,
            }}>
              {draft.sourceText || '(empty)'}
            </div>
          )}
        </div>

        {/* AI sources */}
        <div style={{
          background: '#fff',
          border: '1px solid var(--ai-border)',
          borderRadius: 6,
          padding: '8px 10px',
        }}>
          <div style={{
            fontSize: 10.5, fontWeight: 700,
            letterSpacing: '0.06em', textTransform: 'uppercase',
            color: 'var(--ai-text)', marginBottom: 6,
          }}>Sources used</div>
          <ul style={{ listStyle: 'none', margin: 0, padding: 0, display: 'flex', flexDirection: 'column', gap: 3 }}>
            {sources.map((s, i) => (
              <li key={i} style={{
                display: 'flex', alignItems: 'center', gap: 6,
                fontSize: 11.5, color: 'var(--sage-700)',
              }}>
                <V2Icon name="check" size={11} stroke="var(--ai)" />
                <span style={{
                  whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
                  flex: 1, minWidth: 0,
                }}>{s.label}</span>
              </li>
            ))}
          </ul>
        </div>

        {/* Undo generation */}
        <button
          onClick={onUndo}
          style={{
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
            padding: '7px 10px', borderRadius: 6,
            border: '1px solid var(--ai-border)',
            background: '#fff', color: 'var(--ai-text)',
            cursor: 'pointer', fontSize: 11.5, fontWeight: 500,
            fontFamily: 'var(--font-sans)',
          }}
          onMouseEnter={e => { e.currentTarget.style.background = 'var(--ai-surface)'; }}
          onMouseLeave={e => { e.currentTarget.style.background = '#fff'; }}
        >
          <V2Icon name="collapseArrows" size={11} stroke="var(--ai-text)" />
          Undo generation
        </button>
      </div>
    </div>
  );
}

function ContextSection({ title, count, defaultOpen, icon, children }) {
  const [open, setOpen] = useStateC(!!defaultOpen);
  return (
    <div style={{ marginBottom: 4, padding: '4px 4px 8px 4px' }}>
      <button
        onClick={() => setOpen(o => !o)}
        style={{
          width: '100%', display: 'flex', alignItems: 'center', gap: 6,
          padding: '6px 6px',
          border: 0, background: 'transparent',
          cursor: 'pointer', fontFamily: 'var(--font-sans)',
        }}
      >
        {icon && (
          <V2Icon name={icon} size={11} stroke="var(--sage-500)" />
        )}
        <span style={{
          fontSize: 11, fontWeight: 700,
          letterSpacing: '0.06em', textTransform: 'uppercase',
          color: 'var(--sage-700)',
        }}>{title}</span>
        <span style={{
          fontSize: 10, color: 'var(--sage-500)',
          fontFamily: 'var(--font-mono)',
          padding: '0 6px', borderRadius: 9999,
          background: 'var(--sage-100)',
        }}>{count}</span>
        <div style={{ flex: 1 }} />
        <V2Icon name={open ? 'chevronUp' : 'chevronDown'} size={12} stroke="var(--sage-500)" />
      </button>
      {open && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 1, marginTop: 2 }}>
          {children}
        </div>
      )}
    </div>
  );
}

function Line({ label, detail, detailTone, icon }) {
  const detailColor = detailTone === 'warn' ? 'var(--flag-text)' : 'var(--sage-500)';
  return (
    <div style={{
      padding: '5px 8px', borderRadius: 5,
      display: 'flex', alignItems: 'flex-start', gap: 7,
    }}>
      <span style={{
        width: 4, height: 4, borderRadius: '50%',
        background: 'var(--sage-400)',
        marginTop: 7, flexShrink: 0,
      }} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 12, color: 'var(--sage-800)', lineHeight: 1.4 }}>
          {label}
        </div>
        {detail && (
          <div style={{
            fontSize: 10.5, color: detailColor,
            fontFamily: detailTone === 'warn' ? 'var(--font-sans)' : 'var(--font-mono)',
            marginTop: 1,
            display: 'flex', alignItems: 'center', gap: 4,
          }}>
            {icon && <V2Icon name={icon} size={9} stroke={detailColor} />}
            {detail}
          </div>
        )}
      </div>
    </div>
  );
}

window.V2ContextPanel = V2ContextPanel;
