import { useEffect, useMemo, useState } from 'react'
import {
  MAX_TOP_PATROL_TAGS,
  patrolTagContextFromPlacementTopic,
  resolvePatrolKeywords,
  savedPatrolKeywords,
  type KnowledgeGraphData,
} from '../lib/knowledgeGraph'
import type { BrandData, ResearchMapData } from '../types/brand'
import type { PlacementTopicData } from '../types/placementTopic'
import { KnowledgeOverviewPanel } from './KnowledgeOverviewPanel'
import { ResearchMapEditor, type ResearchMapDraft } from './ResearchMapEditor'
import { Button } from './ui'

type ResearchMapOverviewProps = {
  map: ResearchMapData | null | undefined
  graph: KnowledgeGraphData | null | undefined
  brand?: BrandData | PlacementTopicData | null
  catalogBrand?: BrandData | null
  patrolKeywords?: string[]
  loading?: boolean
  onSaveResearchMap?: (draft: ResearchMapDraft) => Promise<void>
}

type TabId = 'map' | 'knowledge'

type SourceItem = {
  title?: string
  url?: string
  snippet?: string
  query?: string
}

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 mergeSources(
  mapItems: ResearchMapData['research_items'],
  graphSources: KnowledgeGraphData['brave_sources'],
) {
  const seen = new Set<string>()
  const merged: SourceItem[] = []
  for (const src of [...(graphSources ?? []), ...(mapItems ?? [])]) {
    const key = src.url?.trim() || `${src.query}-${src.snippet}`
    if (!key || seen.has(key)) continue
    seen.add(key)
    merged.push(src)
  }
  return merged
}

function PatrolKeywordsRead({
  map,
  keywords: resolvedKeywords,
}: {
  map: ResearchMapData | null | undefined
  keywords: string[]
}) {
  const savedCount = useMemo(() => savedPatrolKeywords(map).length, [map])
  const keywords = resolvedKeywords
  if (!keywords.length) {
    return (
      <p className="hx-research-reader__empty">
        研究地圖產生後會自動整理。若為空，請先完成「產生研究地圖」。
      </p>
    )
  }

  return (
    <div className="space-y-2">
      <ul className="hx-patrol-chips">
        {keywords.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>
      {savedCount === 0 ? (
        <p className="text-xs leading-relaxed text-muted">
          這是依研究地圖與延伸知識自動整理的搜尋短句，可直接開始海巡；按「編輯研究地圖」可增減並儲存。
        </p>
      ) : null}
    </div>
  )
}

function MapReadView({
  map,
  patrolKeywords,
}: {
  map: ResearchMapData | null | undefined
  patrolKeywords: string[]
}) {
  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

  if (!hasContent) {
    const itemCount = map?.research_items?.length ?? 0
    if (itemCount > 0) {
      return (
        <p className="hx-research-reader__prose text-ink-secondary">
          受眾摘要與支柱尚未寫入（資料庫僅保留 {itemCount} 筆參考連結）。
          請按上方「重新產生研究地圖」補齊文字地圖，或先切到「延伸知識」查看節點。
        </p>
      )
    }
    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>
      <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_TOP_PATROL_TAGS} 組</span>
        </div>
        <p className="mb-2 text-xs leading-relaxed text-muted">
          像真人會在 Threads 搜尋框輸入的短句；開始海巡時會使用這些關鍵字。
        </p>
        <PatrolKeywordsRead map={map} keywords={patrolKeywords} />
      </div>
    </div>
  )
}

function MapTab({
  map,
  brand,
  catalogBrand,
  graph,
  patrolKeywords,
  editing,
  onSaveResearchMap,
  onCancelEdit,
}: {
  map: ResearchMapData | null | undefined
  brand?: BrandData | PlacementTopicData | null
  catalogBrand?: BrandData | null
  graph: KnowledgeGraphData | null | undefined
  patrolKeywords: string[]
  editing: boolean
  onSaveResearchMap?: (draft: ResearchMapDraft) => Promise<void>
  onCancelEdit?: () => void
}) {
  if (editing && onSaveResearchMap) {
    return (
      <ResearchMapEditor
        map={map}
        brand={catalogBrand ?? (brand as BrandData | null | undefined)}
        graph={graph}
        onSave={onSaveResearchMap}
        onCancel={onCancelEdit}
      />
    )
  }

  return <MapReadView map={map ?? brand?.research_map} patrolKeywords={patrolKeywords} />
}

export function ResearchMapOverview({
  map,
  graph,
  brand,
  catalogBrand,
  patrolKeywords,
  loading,
  onSaveResearchMap,
}: ResearchMapOverviewProps) {
  const nodeCount = graph?.nodes?.length ?? 0
  const mapReady =
    !!map?.audience_summary?.trim() ||
    !!map?.content_goal?.trim() ||
    !!(map?.questions?.length) ||
    !!(map?.pillars?.length) ||
    !!(map?.research_items?.length)
  const [tab, setTab] = useState<TabId>(mapReady ? 'map' : nodeCount > 0 ? 'knowledge' : 'map')
  const [mapEditMode, setMapEditMode] = useState(false)
  const sources = useMemo(() => mergeSources(map?.research_items, graph?.brave_sources), [map, graph])
  const resolvedPatrolKeywords = useMemo(() => {
    if (patrolKeywords) return patrolKeywords
    const topicLike = brand && 'brand_id' in brand ? brand : null
    const context = topicLike
      ? patrolTagContextFromPlacementTopic(topicLike, catalogBrand)
      : undefined
    return resolvePatrolKeywords(map ?? brand?.research_map, graph?.nodes ?? [], context)
  }, [patrolKeywords, map, brand, catalogBrand, graph?.nodes])

  const tabs: { id: TabId; label: string; count?: number }[] = [
    { id: 'map', label: '研究地圖' },
    { id: 'knowledge', label: '延伸知識', count: nodeCount || undefined },
  ]

  useEffect(() => {
    if (tab !== 'map') {
      setMapEditMode(false)
    }
  }, [tab])

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

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

  return (
    <div className="hx-research-reader hx-research-tabs">
      <div className="hx-research-tabs__head">
        <nav className="hx-research-tabs__nav" aria-label="研究地圖分頁">
          {tabs.map((item) => {
            const active = tab === item.id
            return (
              <button
                key={item.id}
                type="button"
                className={`hx-research-tabs__btn ${active ? 'hx-research-tabs__btn--active' : ''}`}
                onClick={() => setTab(item.id)}
              >
                <span>{item.label}</span>
                {item.count !== undefined && item.count > 0 ? (
                  <span className="hx-research-tabs__count">{item.count}</span>
                ) : null}
                {item.id === 'knowledge' && sources.length > 0 ? (
                  <span className="hx-research-tabs__sources-hint">· {sources.length} 連結</span>
                ) : null}
              </button>
            )
          })}
        </nav>
        {tab === 'map' && onSaveResearchMap && !mapEditMode ? (
          <div className="hx-research-map-toolbar">
            <Button variant="soft" type="button" onClick={() => setMapEditMode(true)}>
              編輯研究地圖
            </Button>
          </div>
        ) : null}
      </div>
      <div className="hx-research-tabs__panel">
        {tab === 'map' ? (
          <MapTab
            map={map}
            brand={brand}
            catalogBrand={catalogBrand}
            graph={graph}
            patrolKeywords={resolvedPatrolKeywords}
            editing={mapEditMode}
            onSaveResearchMap={onSaveResearchMap}
            onCancelEdit={() => setMapEditMode(false)}
          />
        ) : null}
        {tab === 'knowledge' ? <KnowledgeOverviewPanel graph={graph} sources={sources} /> : null}
      </div>
    </div>
  )
}
