import { useState } from 'react'
import {
  STYLE_8D_KEYS,
  STYLE_8D_LABELS,
  type StoredStyle8DProfile,
  type Style8DKey,
  type Style8DSamplePost,
} from '../lib/styleProfile'
import { EvidenceList } from './EvidenceList'
import { Button, Textarea } from './ui'

const STYLE_8D_TONE: Record<Style8DKey, 'coral' | 'sky' | 'palm' | 'bell'> = {
  d1Tone: 'coral',
  d2Structure: 'sky',
  d3Interaction: 'palm',
  d4Topics: 'bell',
  d5Rhythm: 'coral',
  d6Visual: 'sky',
  d7Conversion: 'palm',
  d8Risk: 'bell',
}

const STYLE_8D_SHORT: Record<Style8DKey, string> = {
  d1Tone: 'D1',
  d2Structure: 'D2',
  d3Interaction: 'D3',
  d4Topics: 'D4',
  d5Rhythm: 'D5',
  d6Visual: 'D6',
  d7Conversion: 'D7',
  d8Risk: 'D8',
}

const STYLE_8D_TAB: Record<Style8DKey, string> = {
  d1Tone: '語氣',
  d2Structure: '結構',
  d3Interaction: '互動',
  d4Topics: '主題',
  d5Rhythm: '節奏',
  d6Visual: '視覺',
  d7Conversion: '轉換',
  d8Risk: '紅線',
}

type Props = {
  analysis: StoredStyle8DProfile['analysis']
  samplePosts?: Style8DSamplePost[]
  loading?: boolean
  onUpdate: (key: Style8DKey, summary: string) => void
}

export function Style8DDimensionEditor({ analysis, samplePosts = [], loading, onUpdate }: Props) {
  const [activeKey, setActiveKey] = useState<Style8DKey>('d1Tone')
  const active = analysis[activeKey]
  const activeIndex = STYLE_8D_KEYS.indexOf(activeKey)
  const filledCount = STYLE_8D_KEYS.filter((key) => analysis[key]?.summary?.trim()).length

  const goPrev = () => {
    if (activeIndex > 0) setActiveKey(STYLE_8D_KEYS[activeIndex - 1])
  }

  const goNext = () => {
    if (activeIndex < STYLE_8D_KEYS.length - 1) setActiveKey(STYLE_8D_KEYS[activeIndex + 1])
  }

  return (
    <div className="ac-persona-8d">
      <div className="mb-3 flex flex-wrap items-center justify-between gap-2">
        <p className="text-sm font-bold text-ink-secondary">
          點選維度切換 · 已填寫 {filledCount} / 8
        </p>
        <div className="flex gap-2">
          <Button variant="ghost" className="min-h-9 px-3 py-1 text-xs" onClick={goPrev} disabled={activeIndex === 0}>
            ← 上一項
          </Button>
          <Button
            variant="ghost"
            className="min-h-9 px-3 py-1 text-xs"
            onClick={goNext}
            disabled={activeIndex === STYLE_8D_KEYS.length - 1}
          >
            下一項 →
          </Button>
        </div>
      </div>

      <div className="ac-persona-8d-strip" role="tablist" aria-label="8D 風格維度">
        {STYLE_8D_KEYS.map((key) => {
          const hasContent = !!analysis[key]?.summary?.trim()
          const isActive = activeKey === key
          return (
            <button
              key={key}
              type="button"
              role="tab"
              aria-selected={isActive}
              className={`ac-persona-8d-tab ac-persona-8d-tab--${STYLE_8D_TONE[key]} ${isActive ? 'ac-persona-8d-tab--active' : ''}`}
              onClick={() => setActiveKey(key)}
            >
              <span className="ac-persona-8d-tab__code">{STYLE_8D_SHORT[key]}</span>
              <span className="ac-persona-8d-tab__name">{STYLE_8D_TAB[key]}</span>
              <span
                className={`ac-persona-8d-tab__status ${hasContent ? 'ac-persona-8d-tab__status--done' : ''}`}
                aria-hidden
              />
            </button>
          )
        })}
      </div>

      <div className="ac-persona-8d-sheet" role="tabpanel">
        <div className="ac-persona-8d-sheet__head">
          <div>
            <div className={`ac-persona-stamp ac-persona-stamp--${STYLE_8D_TONE[activeKey]} !inline-block !border-0 !bg-transparent !p-0 !shadow-none`}>
              <span className="ac-persona-stamp__badge">{STYLE_8D_SHORT[activeKey]}</span>
            </div>
            <h3 className="mt-2 text-lg font-black text-ink">{STYLE_8D_LABELS[activeKey]}</h3>
            <p className="mt-1 text-sm text-muted">
              {activeIndex + 1} / {STYLE_8D_KEYS.length} · 在這裡完整編輯這個維度的策略描述
            </p>
          </div>
        </div>

        <Textarea
          rows={12}
          className="ac-persona-8d-sheet__input !min-h-[14rem] !py-4 !text-[15px] !leading-relaxed"
          value={active?.summary ?? ''}
          onChange={(e) => onUpdate(activeKey, e.target.value)}
          placeholder={`描述${STYLE_8D_LABELS[activeKey]}的策略方向、語氣或禁忌…`}
          disabled={loading}
        />

        {active?.evidence?.length ? (
          <EvidenceList evidence={active.evidence} samplePosts={samplePosts} />
        ) : (
          <p className="text-sm text-muted">AI 分析完成後，相關貼文證據會顯示在這裡。</p>
        )}
      </div>
    </div>
  )
}