import { Fragment, useState } from 'react'
import { LayerLadderEditor } from './LayerLadderEditor'
import type { SettingItem, SettingLayer } from './SettingsTable'

const MUTATION_LABEL: Record<SettingItem['mutation'], string> = {
  'mid-run': 'Yes, now',
  'new-runs': 'New runs only',
  immutable: 'No',
}

export function SettingRow(props: {
  item: SettingItem
  onSave(key: string, layer: SettingLayer['layer'], value: string): void
}) {
  const [expanded, setExpanded] = useState(false)

  return (
    <Fragment>
      <tr className="border-b border-border">
        <th scope="row" className="px-4 py-3 text-left">
          <button
            type="button"
            aria-expanded={expanded}
            aria-label={`${expanded ? 'Collapse' : 'Expand'} ${props.item.label}`}
            onClick={() => setExpanded((current) => !current)}
            className="min-h-11 text-left text-sm font-semibold text-fg hover:text-accent"
          >
            {props.item.label}
          </button>
        </th>
        <td className="px-4 py-3 text-sm font-semibold text-fg">{props.item.value}</td>
        <td className="px-4 py-3 text-sm text-fg-muted">
          <span className="mr-2 inline-block h-2 w-2 rounded-full bg-accent" aria-hidden="true" />
          {props.item.decidedBy}
        </td>
        <td className="px-4 py-3 text-sm text-fg-muted">{MUTATION_LABEL[props.item.mutation]}</td>
      </tr>
      {expanded && (
        <tr>
          <td colSpan={4} className="p-0">
            <LayerLadderEditor item={props.item} onSave={props.onSave} />
          </td>
        </tr>
      )}
    </Fragment>
  )
}
