import { html, useState, useRef } from '../lib/preact.js';
import { getStatusMeta } from '../utils/status.js';
import { OptionButton } from './OptionButton.js';
import { renderContent } from '../lib/markdown.js';

export function QuestionBlock({ questions, sessionId, status, onRespond }) {
  const [freeformText, setFreeformText] = useState('');
  const [focused, setFocused] = useState(false);
  const [sending, setSending] = useState(false);
  const [error, setError] = useState(null);
  const [previewIndex, setPreviewIndex] = useState(0);
  const textareaRef = useRef(null);
  const meta = getStatusMeta(status);

  if (!questions || questions.length === 0) return null;

  // Only show the first question (sequential, not parallel)
  const question = questions[0];
  const remainingCount = questions.length - 1;
  const options = question.options || [];
  
  // Check if any option has markdown preview content
  const hasMarkdownPreviews = options.some(opt => opt.markdown);

  const handleOptionClick = async (optionLabel) => {
    if (sending) return;
    setSending(true);
    setError(null);
    try {
      await onRespond(sessionId, optionLabel, false, options.length);
    } catch (err) {
      setError('Failed to send response');
      console.error('QuestionBlock option error:', err);
    } finally {
      setSending(false);
    }
  };

  const handleFreeformSubmit = async (e) => {
    e.preventDefault();
    e.stopPropagation();
    if (freeformText.trim() && !sending) {
      setSending(true);
      setError(null);
      try {
        await onRespond(sessionId, freeformText.trim(), true, options.length);
        setFreeformText('');
      } catch (err) {
        setError('Failed to send response');
        console.error('QuestionBlock freeform error:', err);
      } finally {
        setSending(false);
        // Refocus the textarea after submission
        // Use setTimeout to ensure React has re-rendered with disabled=false
        setTimeout(() => {
          textareaRef.current?.focus();
        }, 0);
      }
    }
  };

  // Side-by-side layout when options have markdown previews
  if (hasMarkdownPreviews) {
    const currentMarkdown = options[previewIndex]?.markdown || '';
    
    return html`
      <div class="space-y-2.5" onClick=${(e) => e.stopPropagation()}>
        ${error && html`
          <div class="rounded-lg border border-attention/40 bg-attention/12 px-3 py-1.5 text-sm text-attention">
            ${error}
          </div>
        `}
        
        <!-- Question Header Badge -->
        ${question.header && html`
          <span class="inline-flex rounded-full border px-2 py-1 font-mono text-micro uppercase tracking-[0.15em] ${meta.badge}">
            ${question.header}
          </span>
        `}

        <!-- Question Text -->
        <p class="font-medium text-bright">${question.question || question.text}</p>

        <!-- Side-by-side: Options | Preview -->
        <div class="flex gap-3">
          <!-- Options List (left side) -->
          <div class="w-2/5 space-y-1.5 shrink-0">
            ${options.map((opt, i) => html`
              <${OptionButton}
                key=${i}
                number=${i + 1}
                label=${opt.label || opt}
                description=${opt.description}
                selected=${previewIndex === i}
                onMouseEnter=${() => setPreviewIndex(i)}
                onFocus=${() => setPreviewIndex(i)}
                onClick=${() => handleOptionClick(opt.label || opt)}
              />
            `)}
          </div>

          <!-- Preview Pane (right side) — fixed height prevents layout thrashing on hover -->
          <div class="flex-1 rounded-lg border border-selection/50 bg-bg/60 p-3 h-[400px] overflow-auto">
            ${currentMarkdown
              ? (currentMarkdown.trimStart().startsWith('```')
                  ? renderContent(currentMarkdown)
                  : html`<pre class="font-mono text-sm text-fg/90 whitespace-pre leading-relaxed">${currentMarkdown}</pre>`)
              : html`<p class="text-dim text-sm italic">No preview for this option</p>`
            }
          </div>
        </div>

        <!-- Freeform Input -->
        <form onSubmit=${handleFreeformSubmit} class="flex items-end gap-2.5">
          <textarea
            ref=${textareaRef}
            value=${freeformText}
            onInput=${(e) => {
              setFreeformText(e.target.value);
              e.target.style.height = 'auto';
              e.target.style.height = e.target.scrollHeight + 'px';
            }}
            onKeyDown=${(e) => {
              if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                handleFreeformSubmit(e);
              }
            }}
            onFocus=${() => setFocused(true)}
            onBlur=${() => setFocused(false)}
            placeholder="Type a response..."
            rows="1"
            class="flex-1 resize-none overflow-hidden rounded-xl border border-selection/75 bg-bg/70 px-3 py-2 text-sm text-fg transition-colors duration-150 placeholder:text-dim focus:outline-none"
            style=${{ minHeight: '38px', maxHeight: '150px', borderColor: focused ? meta.borderColor : undefined }}
            disabled=${sending}
          />
          <button
            type="submit"
            class="shrink-0 rounded-xl px-3 py-2 text-sm font-medium transition-[transform,filter] duration-150 hover:-translate-y-0.5 hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-50"
            style=${{ backgroundColor: meta.borderColor, color: '#0a0f18' }}
            disabled=${sending || !freeformText.trim()}
          >
            ${sending ? 'Sending...' : 'Send'}
          </button>
        </form>

        <!-- More Questions Indicator -->
        ${remainingCount > 0 && html`
          <p class="font-mono text-label text-dim">+ ${remainingCount} more question${remainingCount > 1 ? 's' : ''} after this</p>
        `}
      </div>
    `;
  }

  // Standard layout (no markdown previews)
  return html`
    <div class="space-y-2.5" onClick=${(e) => e.stopPropagation()}>
      ${error && html`
        <div class="rounded-lg border border-attention/40 bg-attention/12 px-3 py-1.5 text-sm text-attention">
          ${error}
        </div>
      `}
      <!-- Question Header Badge -->
      ${question.header && html`
        <span class="inline-flex rounded-full border px-2 py-1 font-mono text-micro uppercase tracking-[0.15em] ${meta.badge}">
          ${question.header}
        </span>
      `}

      <!-- Question Text -->
      <p class="font-medium text-bright">${question.question || question.text}</p>

      <!-- Options -->
      ${options.length > 0 && html`
        <div class="space-y-1.5">
          ${options.map((opt, i) => html`
            <${OptionButton}
              key=${i}
              number=${i + 1}
              label=${opt.label || opt}
              description=${opt.description}
              onClick=${() => handleOptionClick(opt.label || opt)}
            />
          `)}
        </div>
      `}

      <!-- Freeform Input -->
      <form onSubmit=${handleFreeformSubmit} class="flex items-end gap-2.5">
        <textarea
          ref=${textareaRef}
          value=${freeformText}
          onInput=${(e) => {
            setFreeformText(e.target.value);
            e.target.style.height = 'auto';
            e.target.style.height = e.target.scrollHeight + 'px';
          }}
          onKeyDown=${(e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
              e.preventDefault();
              handleFreeformSubmit(e);
            }
          }}
          onFocus=${() => setFocused(true)}
          onBlur=${() => setFocused(false)}
          placeholder="Type a response..."
          rows="1"
          class="flex-1 resize-none overflow-hidden rounded-xl border border-selection/75 bg-bg/70 px-3 py-2 text-sm text-fg transition-colors duration-150 placeholder:text-dim focus:outline-none"
          style=${{ minHeight: '38px', maxHeight: '150px', borderColor: focused ? meta.borderColor : undefined }}
          disabled=${sending}
        />
        <button
          type="submit"
          class="shrink-0 rounded-xl px-3 py-2 text-sm font-medium transition-[transform,filter] duration-150 hover:-translate-y-0.5 hover:brightness-110 disabled:cursor-not-allowed disabled:opacity-50"
          style=${{ backgroundColor: meta.borderColor, color: '#0a0f18' }}
          disabled=${sending || !freeformText.trim()}
        >
          ${sending ? 'Sending...' : 'Send'}
        </button>
      </form>

      <!-- More Questions Indicator -->
      ${remainingCount > 0 && html`
        <p class="font-mono text-label text-dim">+ ${remainingCount} more question${remainingCount > 1 ? 's' : ''} after this</p>
      `}
    </div>
  `;
}
