import { useCallback, useEffect, useMemo, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { api, ApiError } from '../api/client'
import { CreatePlacementTopicDialog } from '../components/CreatePlacementTopicDialog'
import { PlacementFlowPipeline } from '../components/PlacementFlowPipeline'
import { rememberBrandId } from '../lib/brandContext'
import { placementFlowPath } from '../lib/placementFlow'
import { hasProductContext, summarizeProductContext } from '../lib/productContext'
import { hasResearchMap, type BrandData, type CreatePlacementTopicData, type ListBrandsData } from '../types/brand'
import { Badge, Button, Card, ErrorText, Input, PageTitle } from '../components/ui'
import { useIslanderPage } from '../lib/islander'

export function PlacementTopicsPage() {
  const navigate = useNavigate()
  const [topics, setTopics] = useState<BrandData[]>([])
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState('')
  const [createOpen, setCreateOpen] = useState(false)
  const [error, setError] = useState('')

  useIslanderPage({
    title: '置入主題',
    purpose: '流程 B 起點：研究地圖 → 置入海巡 → 找 TA 留言',
    hints: [
      '按「新增主題」建立任務並自動產生置入研究地圖',
      '點主題進入置入研究，勾選節點後開始置入海巡',
      '海巡完成後到「找 TA 留言」處理獲客草稿',
    ],
    suggestions: ['幫我新增一個主題', '哪個主題可以開始海巡？'],
  })

  const load = useCallback(async () => {
    setError('')
    const data = await api.get<ListBrandsData>('/api/v1/brands/', { auth: true })
    setTopics(data.list ?? [])
  }, [])

  useEffect(() => {
    load()
      .catch((e) => setError(e instanceof ApiError ? e.message : '載入失敗'))
      .finally(() => setLoading(false))
  }, [load])

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase()
    if (!q) return topics
    return topics.filter(
      (t) =>
        (t.display_name ?? '').toLowerCase().includes(q) ||
        (t.seed_query ?? '').toLowerCase().includes(q) ||
        (t.brief ?? '').toLowerCase().includes(q),
    )
  }, [topics, search])

  const openTopic = (brandId: string, path: '/research' | '/outreach') => {
    rememberBrandId(brandId)
    navigate(placementFlowPath(path, brandId))
  }

  const onCreated = (data: CreatePlacementTopicData) => {
    const brand = data.brand
    setTopics((prev) => [brand, ...prev.filter((t) => t.id !== brand.id)])
    rememberBrandId(brand.id)
    navigate(placementFlowPath('/research', brand.id))
  }

  return (
    <div className="space-y-8">
      <header className="space-y-3">
        <p className="display-en text-[10px] font-bold tracking-[0.16em] text-brand uppercase">Flow B · Find Your TA</p>
        <div className="flex flex-wrap items-start justify-between gap-4">
          <PageTitle
            title="找 TA"
            subtitle="管理置入主題：依研究地圖找到有需求訊號的 Threads 貼文，再產出獲客留言。"
          />
          <Button onClick={() => setCreateOpen(true)}>＋ 新增主題</Button>
        </div>
        <PlacementFlowPipeline />
      </header>

      <Input
        value={search}
        onChange={(e) => setSearch(e.target.value)}
        placeholder="搜尋主題名稱或種子關鍵字…"
        className="max-w-md"
      />

      {loading ? (
        <Card className="p-6 text-sm text-muted">載入中…</Card>
      ) : filtered.length ? (
        <div className="grid gap-4 sm:grid-cols-2">
          {filtered.map((item) => {
            const productSummary = summarizeProductContext(item.product_context) || item.product_brief
            const mapReady = hasResearchMap(item)
            const hasProduct = hasProductContext(item.product_context) || !!item.product_brief?.trim()
            return (
              <Card key={item.id} className="flex flex-col gap-3 p-5">
                <div>
                  <h2 className="text-base font-bold text-ink">{item.display_name || '未命名主題'}</h2>
                  {item.seed_query ? (
                    <p className="mt-1 text-xs text-muted">種子：{item.seed_query}</p>
                  ) : null}
                  {item.brief?.trim() ? (
                    <p className="mt-2 line-clamp-2 text-sm text-ink-secondary">{item.brief}</p>
                  ) : null}
                  {productSummary ? (
                    <p className="mt-2 line-clamp-1 text-xs text-ink-secondary">置入：{productSummary}</p>
                  ) : null}
                  <div className="mt-2 flex flex-wrap gap-2">
                    {mapReady ? <Badge tone="success">研究地圖已就緒</Badge> : <Badge tone="warning">地圖產生中</Badge>}
                    {hasProduct ? <Badge tone="sky">產品已填</Badge> : <Badge tone="neutral">待填產品</Badge>}
                  </div>
                </div>
                <div className="mt-auto flex flex-wrap gap-2 border-t border-line/60 pt-3">
                  <Button variant="soft" onClick={() => openTopic(item.id, '/research')}>
                    ① 置入研究
                  </Button>
                  <Button variant="soft" onClick={() => openTopic(item.id, '/outreach')}>
                    ② 找 TA 留言
                  </Button>
                  <Link
                    to={`/brands/${item.id}`}
                    className="self-center text-xs font-semibold text-brand hover:underline"
                  >
                    編輯設定
                  </Link>
                </div>
              </Card>
            )
          })}
        </div>
      ) : (
        <Card className="p-10 text-center">
          <p className="text-sm text-ink-secondary">
            {topics.length === 0 ? '尚無主題。按「新增主題」建立第一個找 TA 任務。' : '找不到符合的主題'}
          </p>
          {topics.length === 0 ? (
            <Button className="mt-4" onClick={() => setCreateOpen(true)}>
              新增主題
            </Button>
          ) : null}
        </Card>
      )}

      <CreatePlacementTopicDialog open={createOpen} onClose={() => setCreateOpen(false)} onCreated={onCreated} />
      <ErrorText message={error} />
    </div>
  )
}