import { useId } from 'react'
import { TextField } from './TextField'

export interface DecisionContextKv {
  label: string
  value: string
}

export interface DecisionRowOption {
  label: string
  recommended?: boolean
  choice: string
}

export type DecisionRowAnswerState = 'idle' | 'submitting' | 'answered' | 'error'

export interface DecisionRowProps {
  itemId: string
  projectName?: string
  projectColor?: string
  title: string
  meta: string
  waitingAgeLabel: string
  isOld?: boolean
  expanded?: boolean
  onToggleExpand?: () => void
  question?: string
  dataBlock?: string
  contextKvs?: DecisionContextKv[]
  journalRef?: string
  options: DecisionRowOption[]
  allowFreeText?: boolean
  freeTextValue?: string
  onFreeTextChange?: (value: string) => void
  answerState?: DecisionRowAnswerState
  errorMessage?: string
  answeredSummary?: string
  onSelectOption?: (option: DecisionRowOption) => void
  onSubmitFreeText?: () => void
}

/** `.dec` — one human-in-the-loop decision row per mockup v3. */
export function DecisionRow({
  itemId,
  projectName,
  projectColor,
  title,
  meta,
  waitingAgeLabel,
  isOld,
  expanded = false,
  onToggleExpand,
  question,
  dataBlock,
  contextKvs,
  journalRef,
  options,
  allowFreeText = true,
  freeTextValue = '',
  onFreeTextChange,
  answerState = 'idle',
  errorMessage,
  answeredSummary,
  onSelectOption,
  onSubmitFreeText,
}: DecisionRowProps) {
  const freeTextId = useId()
  const busy = answerState === 'submitting'
  const answered = answerState === 'answered'
  const errored = answerState === 'error'
  const controlsDisabled = busy || answered

  return (
    <article
      className={`overflow-hidden rounded-xl border bg-surface ${expanded ? 'border-border-strong' : 'border-border'}`}
      data-decision-row-id={itemId}
      data-decision-expanded={expanded ? 'true' : 'false'}
      data-decision-answer-state={answerState}
    >
      <button
        type="button"
        className="flex w-full cursor-pointer items-center gap-3 px-4 py-3 text-left"
        onClick={onToggleExpand}
        aria-expanded={expanded}
      >
        {projectColor ? (
          <span className="w-1 flex-shrink-0 self-stretch rounded-full" style={{ backgroundColor: projectColor }} aria-hidden />
        ) : null}
        {projectName ? (
          <span
            className="inline-flex flex-shrink-0 items-center gap-1.5 rounded-[11px] px-2 py-0.5 text-[11px] font-semibold"
            style={{
              color: projectColor,
              backgroundColor: projectColor ? `${projectColor}22` : undefined,
            }}
            data-project-tag={projectName}
            data-project-color={projectColor}
          >
            {projectColor ? (
              <span className="h-[7px] w-[7px] rounded-full" style={{ backgroundColor: projectColor }} aria-hidden />
            ) : null}
            {projectName}
          </span>
        ) : null}
        <span className="min-w-0 flex-1">
          <span className="block text-[13px] font-semibold text-fg">{title}</span>
          <span className="mt-0.5 block text-[11.5px] text-fg-subtle">{meta}</span>
        </span>
        <span className={`flex-shrink-0 text-[11.5px] ${isOld ? 'text-danger' : 'text-warning'}`}>{waitingAgeLabel}</span>
        <span className="flex-shrink-0 text-[11px] text-fg-subtle">{expanded ? '▲ collapse' : '▼ expand'}</span>
      </button>

      {expanded ? (
        <div className="border-t border-[#20242c] px-4 py-3.5 pl-8">
          {question ? (
            <>
              <h5 className="text-[11px] font-semibold uppercase tracking-[0.1em] text-fg-subtle">Full question from agent</h5>
              <p className="mt-1.5 max-w-[760px] text-[12.5px] leading-[1.65] text-[#b9c1d0]">{question}</p>
            </>
          ) : null}
          {dataBlock ? (
            <>
              <h5 className="mt-3 text-[11px] font-semibold uppercase tracking-[0.1em] text-fg-subtle">Data</h5>
              <pre className="mt-1 overflow-x-auto rounded-lg border border-[#20242c] bg-[#101318] p-3 font-mono text-[11.5px] leading-[1.6] text-[#9db4d0]">
                {dataBlock}
              </pre>
            </>
          ) : null}
          {contextKvs && contextKvs.length > 0 ? (
            <>
              <h5 className="mt-3 text-[11px] font-semibold uppercase tracking-[0.1em] text-fg-subtle">Context</h5>
              <div className="mt-1.5 flex flex-wrap gap-x-6 gap-y-1 text-[12px] text-fg-muted">
                {contextKvs.map((kv) => (
                  <span key={kv.label}>
                    {kv.label} <b className="font-medium text-fg">{kv.value}</b>
                  </span>
                ))}
              </div>
            </>
          ) : null}
          {journalRef ? (
            <>
              <h5 className="mt-3 text-[11px] font-semibold uppercase tracking-[0.1em] text-fg-subtle">Journal ref</h5>
              <p className="mt-1 font-mono text-[12px] text-fg-muted">{journalRef}</p>
            </>
          ) : null}
          <h5 className="mt-3 text-[11px] font-semibold uppercase tracking-[0.1em] text-fg-subtle">Answer</h5>
        </div>
      ) : null}

      <div className="flex flex-wrap gap-2 px-4 pb-3 pl-8">
        {answered && answeredSummary ? (
          <p className="text-[12px] text-success" data-decision-answered>
            Answered: {answeredSummary}
          </p>
        ) : null}
        {errored && errorMessage ? (
          <p className="w-full text-[12px] text-danger" data-decision-error>
            {errorMessage}
          </p>
        ) : null}
        {options.map((option) => (
          <button
            key={option.choice}
            type="button"
            disabled={controlsDisabled}
            onClick={() => onSelectOption?.(option)}
            className={
              option.recommended
                ? 'cursor-pointer rounded-lg border border-[#3a5a3d] bg-[#1a2a1c] px-3.5 py-1.5 text-[12px] text-[#b8e6a0] disabled:cursor-not-allowed disabled:opacity-50'
                : 'cursor-pointer rounded-lg border border-[#2e3440] bg-surface-raised px-3.5 py-1.5 text-[12px] text-[#c7cede] disabled:cursor-not-allowed disabled:opacity-50'
            }
          >
            {option.label}
            {option.recommended ? <span className="text-[10.5px] text-[#6d9960]"> · recommended</span> : null}
          </button>
        ))}
        {allowFreeText ? (
          <div className="flex min-w-[200px] flex-1 gap-1.5">
            <TextField
              id={freeTextId}
              label="Answer in plain text"
              labelMode="hidden"
              value={freeTextValue}
              disabled={controlsDisabled}
              placeholder="Or answer in plain text…"
              onValueChange={(value) => onFreeTextChange?.(value)}
              onKeyDown={(event) => {
                if (event.key === 'Enter') onSubmitFreeText?.()
              }}
              data-decision-free-text
            />
            <button
              type="button"
              disabled={controlsDisabled || freeTextValue.trim().length === 0}
              onClick={onSubmitFreeText}
              className="cursor-pointer rounded-lg bg-[#dbe4ff] px-3.5 py-1.5 text-[12px] font-semibold text-[#10131a] disabled:cursor-not-allowed disabled:opacity-50"
            >
              Send
            </button>
          </div>
        ) : null}
      </div>
    </article>
  )
}
