import { useState } from 'react'
import type { CopyMissionData } from '../types/copyMission'
import { hasMissionResearchMap } from '../types/copyMission'
import {
  CopyMissionResearchEditor,
  MAX_COPY_SCAN_TAGS,
  type CopyMissionResearchMapDraft,
} from './CopyMissionResearchEditor'
import { Button } from './ui'

type Props = {
  mission: CopyMissionData | null
  loading?: boolean
  onSaveResearchMap?: (draft: CopyMissionResearchMapDraft) => Promise<void>
}

function CompactList({ items, emptyLabel }: { items: string[]; emptyLabel?: string }) {
  if (!items.length) {
    return emptyLabel ? <p className="hx-research-reader__empty">{emptyLabel}</p> : null
  }
  return (
    <ol className="hx-research-reader__list hx-research-reader__list--compact">
      {items.map((item, index) => (
        <li key={`${item}-${index}`}>
          <span className="hx-research-reader__list-index">{index + 1}</span>
          <span>{item}</span>
        </li>
      ))}
    </ol>
  )
}

function resolveScanTags(mission: CopyMissionData | null): string[] {
  if (!mission) return []
  if (mission.selected_tags?.length) return mission.selected_tags
  return (mission.research_map?.suggested_tags ?? []).map((item) => item.tag).filter(Boolean)
}

function MapReadView({ mission }: { mission: CopyMissionData }) {
  const map = mission.research_map
  const scanTags = resolveScanTags(mission)
  const hasContent =
    !!map?.audience_summary?.trim() ||
    !!map?.content_goal?.trim() ||
    (map?.questions?.length ?? 0) > 0 ||
    (map?.pillars?.length ?? 0) > 0 ||
    (map?.exclusions?.length ?? 0) > 0 ||
    !!map?.benchmark_notes?.trim() ||
    scanTags.length > 0

  if (!hasContent) {
    return <p className="hx-research-reader__prose text-ink-secondary">研究地圖尚未產生。</p>
  }

  return (
    <div className="hx-research-map-layout hx-research-map-layout--overview">
      <div className="hx-research-reader__block hx-research-reader__block--accent">
        <p className="hx-research-reader__label hx-research-reader__label--brand">受眾是誰</p>
        <p className="hx-research-reader__prose hx-research-reader__prose--compact">
          {map?.audience_summary?.trim() || '—'}
        </p>
      </div>
      <div className="hx-research-reader__block">
        <p className="hx-research-reader__label">內容目標</p>
        <p className="hx-research-reader__prose hx-research-reader__prose--compact">
          {map?.content_goal?.trim() || '—'}
        </p>
      </div>
      <div className="hx-research-reader__block">
        <p className="hx-research-reader__label">受眾會問什麼</p>
        <CompactList items={map?.questions ?? []} emptyLabel="尚無提問方向" />
      </div>
      <div className="hx-research-reader__block">
        <p className="hx-research-reader__label">內容支柱</p>
        <CompactList items={map?.pillars ?? []} emptyLabel="尚無內容支柱" />
      </div>
      <div className="hx-research-reader__block hx-research-reader__block--warn">
        <p className="hx-research-reader__label">不要碰</p>
        <CompactList items={map?.exclusions ?? []} emptyLabel="尚無排除項" />
      </div>
      {map?.benchmark_notes?.trim() ? (
        <div className="hx-research-reader__block">
          <p className="hx-research-reader__label">對標筆記</p>
          <p className="hx-research-reader__prose hx-research-reader__prose--compact">{map.benchmark_notes.trim()}</p>
        </div>
      ) : null}
      <div className="hx-research-reader__block hx-research-reader__block--accent">
        <div className="hx-patrol-picks__head">
          <p className="hx-research-reader__label hx-research-reader__label--brand">優先搜尋標籤</p>
          <span className="hx-patrol-picks__meta">最多 {MAX_COPY_SCAN_TAGS} 組</span>
        </div>
        <p className="mb-2 text-xs leading-relaxed text-muted">
          海巡只掃你儲存的標籤；按「編輯研究地圖」可增減並儲存。
        </p>
        {scanTags.length ? (
          <ul className="hx-patrol-chips">
            {scanTags.map((tag, index) => (
              <li key={tag} className="hx-patrol-chips__item">
                <span className="hx-patrol-chips__rank">{index + 1}</span>
                <span className="hx-patrol-chips__tag">{tag}</span>
              </li>
            ))}
          </ul>
        ) : (
          <p className="hx-research-reader__empty">研究地圖產生後會自動整理搜尋標籤。</p>
        )}
        {!mission.selected_tags?.length && scanTags.length > 0 ? (
          <p className="mt-2 text-xs leading-relaxed text-muted">
            目前顯示 AI 建議標籤；編輯並儲存後才會固定為海巡用詞。
          </p>
        ) : null}
      </div>
    </div>
  )
}

export function CopyMissionResearchOverview({ mission, loading, onSaveResearchMap }: Props) {
  const [editing, setEditing] = useState(false)
  const mapReady = hasMissionResearchMap(mission)

  if (loading) {
    return (
      <div className="hx-research-reader">
        <p className="text-sm leading-relaxed text-ink-secondary">研究地圖產生中…</p>
      </div>
    )
  }

  if (!mapReady && !onSaveResearchMap) {
    return (
      <div className="hx-research-reader">
        <p className="text-sm leading-relaxed text-ink-secondary">
          尚未產生研究地圖。請按上方「產生研究地圖」，完成後會顯示受眾方向與搜尋標籤。
        </p>
      </div>
    )
  }

  return (
    <div className="hx-research-reader">
      {onSaveResearchMap && mapReady && !editing ? (
        <div className="hx-research-map-toolbar mb-4">
          <Button variant="soft" type="button" onClick={() => setEditing(true)}>
            編輯研究地圖
          </Button>
        </div>
      ) : null}
      {editing && mission && onSaveResearchMap ? (
        <CopyMissionResearchEditor
          mission={mission}
          onSave={async (draft) => {
            await onSaveResearchMap(draft)
            setEditing(false)
          }}
          onCancel={() => setEditing(false)}
        />
      ) : mission ? (
        <MapReadView mission={mission} />
      ) : (
        <p className="text-sm leading-relaxed text-ink-secondary">尚未產生研究地圖。</p>
      )}
    </div>
  )
}