import { useCallback, useEffect, useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { api, ApiError } from '../api/client'
import { CreatePlacementTopicDialog } from '../components/CreatePlacementTopicDialog'
import { rememberTopicId } from '../lib/brandContext'
import { placementFlowPath } from '../lib/placementFlow'
import {
  hasResearchMap,
  sortPlacementTopics,
  topicSearchText,
  topicResearchMapPath,
  topicSettingsPath,
  topicTitle,
} from '../lib/placementTopics'
import type { BrandData, ListBrandsData } from '../types/brand'
import type { CreatePlacementTopicData, ListPlacementTopicsData, PlacementTopicData } from '../types/placementTopic'
import { Badge, Button, Card, ErrorText, Field, Input, PageTitle } from '../components/ui'
import { useIslanderPage } from '../lib/islander'

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

  const sortedTopics = useMemo(() => sortPlacementTopics(topics), [topics])

  useIslanderPage({
    title: '找 TA',
    purpose: '管理找 TA 主題，進入主題設定或找 TA 留言',
    hints: ['按「新增主題」建立任務', '點「研究地圖」查看受眾與內容方向'],
    suggestions: ['幫我新增一個主題', '哪個主題可以寫留言？'],
  })

  const load = useCallback(async () => {
    setError('')
    const [topicsRes, brandsRes] = await Promise.allSettled([
      api.get<ListPlacementTopicsData>('/api/v1/placement/topics/', { auth: true }),
      api.get<ListBrandsData>('/api/v1/brands/', { auth: true }),
    ])
    if (topicsRes.status === 'fulfilled') {
      setTopics(topicsRes.value.list ?? [])
    } else {
      const reason = topicsRes.reason
      setError(reason instanceof ApiError ? reason.message : '載入主題失敗')
      setTopics([])
    }
    if (brandsRes.status === 'fulfilled') {
      setCatalogBrands(brandsRes.value.list ?? [])
    }
  }, [])

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

  useEffect(() => {
    const refresh = () => {
      if (document.visibilityState !== 'visible') return
      load().catch(() => undefined)
    }
    window.addEventListener('focus', refresh)
    document.addEventListener('visibilitychange', refresh)
    return () => {
      window.removeEventListener('focus', refresh)
      document.removeEventListener('visibilitychange', refresh)
    }
  }, [load])

  const filtered = useMemo(() => {
    const q = search.trim().toLowerCase()
    if (!q) return sortedTopics
    return sortedTopics.filter((t) => topicSearchText(t).includes(q))
  }, [sortedTopics, search])

  const onCreated = async (data: CreatePlacementTopicData) => {
    rememberTopicId(data.topic.id)
    await load().catch(() => undefined)
    navigate(topicResearchMapPath(data.topic.id), { state: { expandJobId: data.job_id } })
  }

  return (
    <div className="space-y-8">
      <div className="flex flex-wrap items-start justify-between gap-4">
        <PageTitle
          title="找 TA"
          subtitle={
            loading
              ? '載入主題列表…'
              : `共 ${sortedTopics.length} 個主題 · 依主題設定研究方向，並產出獲客留言。`
          }
        />
        <Button onClick={() => setCreateOpen(true)}>＋ 新增主題</Button>
      </div>

      <Field label="搜尋主題" hint="可輸入主題名稱、種子關鍵字、品牌或主題目標。">
        <Input
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="例如：敏感肌、職場焦慮、保養品"
          className="max-w-md"
          data-islander-label="搜尋主題"
        />
      </Field>

      {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 mapReady = hasResearchMap(item)
            return (
              <Card key={item.id} className="flex flex-col gap-4 p-5">
                <div className="min-w-0 flex-1">
                  <h2 className="text-base font-bold text-ink">{topicTitle(item)}</h2>
                  {item.brand_display_name?.trim() ? (
                    <p className="mt-0.5 text-xs text-muted">品牌：{item.brand_display_name}</p>
                  ) : null}
                  {item.seed_query?.trim() ? (
                    <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 leading-relaxed text-ink-secondary">{item.brief}</p>
                  ) : null}
                  <div className="mt-3">
                    {mapReady ? (
                      <Badge tone="success">研究地圖已就緒</Badge>
                    ) : (
                      <Badge tone="warning">研究地圖待產生</Badge>
                    )}
                  </div>
                </div>
                <div className="flex flex-wrap gap-2 border-t border-line/60 pt-3">
                  <Button variant="soft" onClick={() => navigate(topicResearchMapPath(item.id))}>
                    研究地圖
                  </Button>
                  <Button variant="soft" onClick={() => navigate(topicSettingsPath(item.id))}>
                    主題設定
                  </Button>
                  <Button
                    onClick={() => {
                      rememberTopicId(item.id)
                      navigate(placementFlowPath('/outreach', item.id))
                    }}
                  >
                    找 TA 留言
                  </Button>
                </div>
              </Card>
            )
          })}
        </div>
      ) : (
        <Card className="p-10 text-center">
          <p className="text-sm text-ink-secondary">
            {sortedTopics.length === 0
              ? '尚無主題。按「新增主題」建立第一個找 TA 任務。'
              : '找不到符合的主題、種子關鍵字、品牌或目標'}
          </p>
          {sortedTopics.length === 0 ? (
            <Button className="mt-4" onClick={() => setCreateOpen(true)}>
              新增主題
            </Button>
          ) : null}
        </Card>
      )}

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