import { useCallback, useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { api, ApiError } from '../api/client'
import { PlacementFlowNav } from '../components/PlacementFlowNav'
import { useActiveTopic } from '../hooks/useActiveTopic'
import {
  Badge,
  Button,
  Card,
  ErrorText,
  Field,
  Notice,
  Select,
  Textarea,
} from '../components/ui'
import { useIslanderPage } from '../lib/islander'


export type ContentMatrixRow = {
  sort_order: number
  search_tag: string
  angle: string
  hook: string
  text: string
  reference_notes: string
  source_permalinks: string[]
  rationale: string
}

export type ContentMatrixData = {
  id?: string
  brand_id: string
  rows: ContentMatrixRow[]
  generated_at: number
  create_at?: number
  update_at?: number
}

export function PersonaMatrixPage() {
  const {
    topicId: id,
    topic,
    topics,
    brand,
    topicLabel,
    setTopicId,
    loading: topicLoading,
  } = useActiveTopic()

  const [matrix, setMatrix] = useState<ContentMatrixData | null>(null)
  const [count, setCount] = useState(5)
  const [loading, setLoading] = useState(true)
  const [generating, setGenerating] = useState(false)
  const [error, setError] = useState('')

  useIslanderPage({
    title: '原創矩陣',
    purpose: '找 TA 第三步：依獲客海巡素材產生原創發文草稿（非獲客留言、非拷貝忍者）',
    hints: [
      '素材來自 7 天內、產品匹配 ≥70 的海巡貼文',
      '每則為原創 Threads 貼文，可複製到帳號工作區發文',
      '需先完成雙軌海巡才有素材',
    ],
    suggestions: ['幫我產生 5 則原創貼文', '哪個角度適合這個主題？'],
  })

  const load = useCallback(async () => {
    if (!id) return
    setLoading(true)
    setError('')
    try {
      const matrixData = await api.get<ContentMatrixData>(
          `/api/v1/placement/topics/${encodeURIComponent(id)}/content-matrix`,
          { auth: true },
        )
      setMatrix(matrixData)
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '載入內容矩陣失敗')
    } finally {
      setLoading(false)
    }
  }, [id])

  useEffect(() => {
    load().catch(() => undefined)
  }, [load])

  const generate = async () => {
    if (!id) return
    setGenerating(true)
    setError('')
    try {
      const data = await api.post<ContentMatrixData>(
        `/api/v1/placement/topics/${encodeURIComponent(id)}/content-matrix/generate`,
        { count },
        { auth: true },
      )
      setMatrix(data)
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '產生內容矩陣失敗')
    } finally {
      setGenerating(false)
    }
  }

  const brandName = brand?.display_name?.trim() || topic?.brand_display_name?.trim() || '未命名品牌'
  const displayName = topicLabel || brandName
  const rows = matrix?.rows ?? []

  if (!topicLoading && !id) {
    return (
      <div className="ac-persona-page space-y-8">
        <PlacementFlowNav
          active="matrix"
          topicId=""
          topics={topics}
          onTopicChange={setTopicId}
          topicLoading={topicLoading}
        />
        <Card>
          <p className="text-sm text-ink-secondary">
            請先在
            <Link to="/placement/topics" className="mx-1 font-semibold text-brand hover:underline">
              找 TA
            </Link>
            建立主題，再產生內容矩陣。
          </p>
        </Card>
      </div>
    )
  }

  return (
    <div className="ac-persona-page space-y-8">
      <PlacementFlowNav
        active="matrix"
        topicId={id}
        topics={topics}
        onTopicChange={setTopicId}
        topicLoading={topicLoading}
      />

      <header className="space-y-2">
        <p className="display-en text-[10px] font-bold tracking-[0.16em] text-brand uppercase">
          Content Matrix
        </p>
        <h1 className="text-2xl font-black text-ink">原創矩陣 · {displayName}</h1>
        {topicLabel ? <p className="text-sm text-muted">品牌：{brandName}</p> : null}
        <p className="max-w-2xl text-sm leading-relaxed text-ink-secondary">
          從海巡 gold/recent 素材萃取角度，產生原創 Threads 貼文草稿。與獲客留言不同，這裡是主動發文內容。
        </p>
        <div className="flex flex-wrap gap-2">
          <Badge tone="sky">共 {rows.length} 則</Badge>
          {matrix?.generated_at ? (
            <Badge tone="neutral">
              更新 {new Date(matrix.generated_at / 1_000_000).toLocaleString('zh-TW')}
            </Badge>
          ) : null}
        </div>
      </header>

      <section className="ac-persona-panel flex flex-wrap items-end gap-4">
        <Field label="產生則數">
          <Select value={String(count)} onChange={(e) => setCount(Number(e.target.value))}>
            <option value="3">3 則</option>
            <option value="5">5 則（建議）</option>
            <option value="8">8 則</option>
            <option value="10">10 則</option>
          </Select>
        </Field>
        <Button onClick={() => void generate()} disabled={generating || loading}>
          {generating ? '產生中…' : '產生內容矩陣'}
        </Button>
      </section>

      {loading ? (
        <p className="text-sm text-ink-secondary">載入內容矩陣…</p>
      ) : rows.length === 0 ? (
        <Notice
          tone="info"
          title="尚無內容矩陣"
          message="請先完成雙軌海巡，再按「產生內容矩陣」。"
        />
      ) : (
        <div className="grid gap-4">
          {rows.map((row, index) => (
            <article
              key={`matrix-row-${row.sort_order}-${index}`}
              className="ac-island-card space-y-3 p-5"
              data-islander-label={`矩陣貼文 ${row.sort_order}`}
            >
              <div className="flex flex-wrap items-center gap-2">
                <Badge tone="brand">#{row.sort_order || index + 1}</Badge>
                {row.search_tag ? <Badge tone="sky">{row.search_tag}</Badge> : null}
                {row.angle ? <Badge tone="neutral">{row.angle}</Badge> : null}
              </div>
              {row.hook ? (
                <p className="text-sm font-semibold text-ink">{row.hook}</p>
              ) : null}
              <Field label="貼文全文" hint="可複製到 Threads 帳號工作區發文">
                <Textarea rows={6} readOnly value={row.text} />
              </Field>
              {row.rationale ? (
                <p className="text-xs text-muted">{row.rationale}</p>
              ) : null}
              {row.reference_notes ? (
                <p className="text-xs text-muted">參考：{row.reference_notes}</p>
              ) : null}
              {row.source_permalinks?.length ? (
                <div className="flex flex-wrap gap-2 text-xs">
                  {row.source_permalinks.map((link) => (
                    <a key={link} href={link} target="_blank" rel="noreferrer" className="ac-link">
                      素材連結
                    </a>
                  ))}
                </div>
              ) : null}
            </article>
          ))}
        </div>
      )}

      <ErrorText message={error} />
    </div>
  )
}