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

function V2Editor({
  draft, ai, onChangeBody, onSubmit, onDiscard, onCollapse, canCollapse,
}) {
  const [showSource, setShowSource] = useStateE(false);
  const isReady = draft.state === 'ai_draft_ready' || draft.state === 'user_reviewed';
  const polished = ai?.polished;
  const body = draft.body || polished;

  return (
    <div style={{ flex: 1, overflowY: 'auto', minHeight: 0, padding: '20px 28px 32px 28px' }}>
      <div style={{ maxWidth: 760, margin: '0 auto' }}>

        {/* Status banner — AI-attributed */}
        {isReady && (
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10,
            padding: '10px 14px', marginBottom: 16,
            background: 'var(--ai-surface)',
            border: '1px solid var(--ai-border)',
            borderRadius: 8,
          }}>
            <V2Icon name="sparkle" size={14} stroke="var(--ai)" fill="var(--ai)" />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ai-text)' }}>
                AI draft ready · review and edit before submitting
              </div>
              <div style={{ fontSize: 11, color: 'var(--ai-text)', opacity: 0.75 }}>
                Generated from your source text + 6 patient context items
              </div>
            </div>
            <button
              onClick={() => setShowSource(s => !s)}
              style={{
                display: 'flex', alignItems: 'center', gap: 5,
                padding: '5px 10px', borderRadius: 6,
                border: '1px solid var(--ai-border)',
                background: '#fff', color: 'var(--ai-text)',
                cursor: 'pointer', fontSize: 11, fontWeight: 500,
                fontFamily: 'var(--font-sans)',
              }}
            >
              <V2Icon name="eye" size={11} />
              {showSource ? 'Hide' : 'Show'} my notes
            </button>
            <button
              onClick={onDiscard}
              title="Discard draft"
              style={{
                display: 'grid', placeItems: 'center',
                width: 28, height: 28, borderRadius: 6,
                border: '1px solid var(--ai-border)', background: '#fff',
                color: 'var(--reject-text)', cursor: 'pointer',
              }}
            >
              <V2Icon name="trash" size={12} />
            </button>
          </div>
        )}

        {showSource && (
          <div style={{
            padding: '12px 16px', marginBottom: 16,
            background: 'var(--sage-50)',
            border: '1px dashed var(--sage-300)',
            borderRadius: 8,
          }}>
            <div style={{
              display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6,
            }}>
              <V2Icon name="pencilOutline" size={11} stroke="var(--sage-500)" />
              <span style={{
                fontSize: 10, fontWeight: 600,
                letterSpacing: '0.06em', textTransform: 'uppercase',
                color: 'var(--sage-500)',
              }}>Your source text</span>
              <span style={{ fontSize: 10, color: 'var(--sage-400)' }}>· kept verbatim</span>
            </div>
            <div style={{
              fontFamily: 'var(--font-serif)', fontStyle: 'italic',
              fontSize: 13, color: 'var(--sage-700)', lineHeight: 1.55,
              whiteSpace: 'pre-wrap',
            }}>
              {draft.sourceText || '(empty)'}
            </div>
          </div>
        )}

        {/* Document */}
        <div style={{
          background: '#fff',
          border: '1px solid var(--sage-200)',
          borderRadius: 12,
          boxShadow: 'var(--shadow-sm)',
          overflow: 'hidden',
        }}>
          {/* Doc header */}
          <div style={{
            padding: '14px 22px',
            borderBottom: '1px solid var(--sage-200)',
            display: 'flex', alignItems: 'center', gap: 12,
            background: 'var(--sage-50)',
          }}>
            <div>
              <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--sage-800)' }}>
                {draft.type} note · Day {draft.day || 3}
              </div>
              <div style={{ fontSize: 11, color: 'var(--sage-500)', fontFamily: 'var(--font-mono)', marginTop: 2 }}>
                Started {draft.startedAt} · {draft.author || 'Dr. R. Patel'}
              </div>
            </div>
            <div style={{ flex: 1 }} />
            <span style={{
              fontSize: 10, fontWeight: 700,
              padding: '3px 9px', borderRadius: 9999,
              background: isReady ? 'var(--ai-surface)' : 'var(--sage-100)',
              color: isReady ? 'var(--ai-text)' : 'var(--sage-600)',
              border: `1px solid ${isReady ? 'var(--ai-border)' : 'var(--sage-200)'}`,
              letterSpacing: '0.06em', textTransform: 'uppercase',
            }}>{isReady ? 'AI Draft · Editable' : 'Draft'}</span>
          </div>

          <div style={{ padding: '22px 26px 26px 26px' }}>
            {body ? (
              <>
                <EditableSection title="Subjective" value={body.subjective} field="subjective" onChange={onChangeBody} editable />
                <EditableSection title="Objective" value={body.objective} field="objective" onChange={onChangeBody} editable />
                <EditableSection title="Assessment" value={body.assessment} field="assessment" onChange={onChangeBody} editable />
                <EditableList title="Plan" items={body.plan || []} onChange={items => onChangeBody({ plan: items })} />
              </>
            ) : (
              <BlankBody onChange={onChangeBody} />
            )}
          </div>
        </div>

        {/* Footer actions */}
        <div style={{
          marginTop: 16,
          padding: '10px 14px',
          background: '#fff',
          border: '1px solid var(--sage-200)',
          borderRadius: 8,
          display: 'flex', alignItems: 'center', gap: 8,
        }}>
          <button onClick={onDiscard} style={ghostE('var(--reject-text)')}>
            <V2Icon name="trash" size={12} />
            Discard
          </button>
          {canCollapse && (
            <button onClick={onCollapse} style={ghostE('var(--sage-600)')}>
              <V2Icon name="collapseArrows" size={12} />
              Collapse to composer
            </button>
          )}
          <div style={{ flex: 1 }} />
          <span style={{ fontSize: 11, color: 'var(--sage-500)', display: 'flex', alignItems: 'center', gap: 5 }}>
            <V2Icon name="check" size={11} stroke="var(--primary-light)" />
            Autosaved
          </span>
          <button
            onClick={onSubmit}
            disabled={!isReady && !body}
            style={{
              display: 'flex', alignItems: 'center', gap: 6,
              padding: '8px 16px', borderRadius: 6,
              border: 0,
              background: 'var(--primary)',
              color: '#fff', cursor: 'pointer',
              fontSize: 12.5, fontWeight: 600,
              fontFamily: 'var(--font-sans)',
            }}
          >
            <V2Icon name="check" size={13} stroke="#fff" />
            Submit & file
          </button>
        </div>
      </div>
    </div>
  );
}

function EditableSection({ title, value, field, onChange }) {
  return (
    <div style={{ marginBottom: 18 }}>
      <h4 style={{
        margin: 0, marginBottom: 6,
        fontSize: 11, fontWeight: 700,
        color: 'var(--sage-500)',
        letterSpacing: '0.08em', textTransform: 'uppercase',
      }}>{title}</h4>
      <textarea
        value={value || ''}
        onChange={e => onChange({ [field]: e.target.value })}
        rows={Math.max(2, Math.ceil(((value || '').length) / 70))}
        style={{
          width: '100%', resize: 'vertical',
          border: '1px solid transparent',
          background: 'transparent',
          padding: '4px 6px', borderRadius: 6,
          fontSize: 13, lineHeight: 1.55,
          color: 'var(--sage-800)',
          fontFamily: 'var(--font-sans)',
          outline: 0,
          minHeight: 28,
        }}
        onFocus={e => { e.target.style.background = 'var(--sage-50)'; e.target.style.borderColor = 'var(--sage-200)'; }}
        onBlur={e => { e.target.style.background = 'transparent'; e.target.style.borderColor = 'transparent'; }}
      />
    </div>
  );
}

function EditableList({ title, items, onChange }) {
  function update(i, val) {
    const next = items.slice();
    next[i] = val;
    onChange(next);
  }
  function remove(i) {
    onChange(items.filter((_, idx) => idx !== i));
  }
  function add() {
    onChange([...items, '']);
  }
  return (
    <div style={{ marginBottom: 8 }}>
      <h4 style={{
        margin: 0, marginBottom: 6,
        fontSize: 11, fontWeight: 700,
        color: 'var(--sage-500)',
        letterSpacing: '0.08em', textTransform: 'uppercase',
      }}>{title}</h4>
      <ol style={{ margin: 0, paddingLeft: 0, listStyle: 'none' }}>
        {items.map((it, i) => (
          <li key={i} style={{
            display: 'flex', alignItems: 'flex-start', gap: 8,
            marginBottom: 4,
          }}>
            <span style={{
              flexShrink: 0,
              fontFamily: 'var(--font-mono)', fontSize: 11,
              color: 'var(--sage-400)',
              padding: '4px 0',
              minWidth: 18,
            }}>{i + 1}.</span>
            <input
              value={it}
              onChange={e => update(i, e.target.value)}
              style={{
                flex: 1, border: '1px solid transparent',
                padding: '4px 6px', borderRadius: 6,
                background: 'transparent',
                fontSize: 13, color: 'var(--sage-800)',
                fontFamily: 'var(--font-sans)',
                outline: 0,
              }}
              onFocus={e => { e.target.style.background = 'var(--sage-50)'; e.target.style.borderColor = 'var(--sage-200)'; }}
              onBlur={e => { e.target.style.background = 'transparent'; e.target.style.borderColor = 'transparent'; }}
            />
            <button
              onClick={() => remove(i)}
              aria-label="Remove plan item"
              style={{
                background: 'transparent', border: 0,
                padding: 4, color: 'var(--sage-400)',
                cursor: 'pointer', display: 'flex',
                opacity: 0.6,
              }}
            >
              <V2Icon name="x" size={11} />
            </button>
          </li>
        ))}
      </ol>
      <button
        onClick={add}
        style={{
          display: 'flex', alignItems: 'center', gap: 5,
          padding: '4px 8px', marginLeft: 26, marginTop: 2,
          border: 0, background: 'transparent',
          color: 'var(--sage-500)', cursor: 'pointer',
          fontSize: 11.5, fontFamily: 'var(--font-sans)',
        }}
      >
        <V2Icon name="plus" size={11} /> Add plan item
      </button>
    </div>
  );
}

function BlankBody({ onChange }) {
  return (
    <div style={{
      padding: 24, textAlign: 'center',
      background: 'var(--sage-50)', borderRadius: 8,
      border: '1px dashed var(--sage-300)',
      color: 'var(--sage-500)', fontSize: 13,
    }}>
      Empty draft. Type below or click <em>Analyse</em> in the composer to generate a structured note.
    </div>
  );
}

function ghostE(color) {
  return {
    display: 'flex', alignItems: 'center', gap: 5,
    padding: '6px 10px', borderRadius: 6,
    border: '1px solid var(--sage-200)',
    background: '#fff', color, cursor: 'pointer',
    fontSize: 11.5, fontWeight: 500,
    fontFamily: 'var(--font-sans)',
  };
}

window.V2Editor = V2Editor;
