import { useEffect, useMemo, useState } from 'react'
import { Link } from 'react-router-dom'
import { api, ApiError } from '../api/client'
import { getActiveBrandId } from '../lib/brandContext'
import type { ExpandKnowledgeGraphData } from '../lib/knowledgeGraph'
import { brandHasCatalogProducts } from '../lib/productCatalog'
import { isCatalogBrand } from '../lib/productCatalog'
import type { BrandData } from '../types/brand'
import type { CreatePlacementTopicData, PlacementTopicData } from '../types/placementTopic'
import { BrandProductPicker } from './BrandProductPicker'
import { Button, ErrorText, Field, Input, Textarea } from './ui'

type CreatePlacementTopicDialogProps = {
  open: boolean
  brands: BrandData[]
  onClose: () => void
  onCreated: (data: CreatePlacementTopicData) => void
}

export function CreatePlacementTopicDialog({
  open,
  brands,
  onClose,
  onCreated,
}: CreatePlacementTopicDialogProps) {
  const [brandId, setBrandId] = useState('')
  const [productId, setProductId] = useState<string | null>(null)
  const [topicName, setTopicName] = useState('')
  const [seedQuery, setSeedQuery] = useState('')
  const [brief, setBrief] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState('')

  const catalogBrands = useMemo(() => brands.filter(isCatalogBrand), [brands])

  const selectedBrand = useMemo(
    () => catalogBrands.find((item) => item.id === brandId) ?? null,
    [brandId, catalogBrands],
  )

  useEffect(() => {
    if (!open) return
    const preferred =
      catalogBrands.find((item) => item.id === getActiveBrandId())?.id ||
      catalogBrands.find((item) => brandHasCatalogProducts(item))?.id ||
      catalogBrands[0]?.id ||
      ''
    setBrandId(preferred)
    setProductId(null)
    setTopicName('')
    setSeedQuery('')
    setBrief('')
    setError('')
  }, [open, catalogBrands])

  useEffect(() => {
    if (!open) return
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose()
    }
    document.addEventListener('keydown', onKey)
    document.body.style.overflow = 'hidden'
    return () => {
      document.removeEventListener('keydown', onKey)
      document.body.style.overflow = ''
    }
  }, [open, onClose])

  if (!open) return null

  const submit = async () => {
    if (!brandId) {
      setError('請選擇要置入的品牌')
      return
    }
    if (!brandHasCatalogProducts(selectedBrand)) {
      setError('請先到品牌庫為此品牌新增至少一個產品')
      return
    }
    if (!topicName.trim()) {
      setError('請填寫主題名稱')
      return
    }
    if (!seedQuery.trim() || !brief.trim()) {
      setError('請填寫種子關鍵字與主題目標')
      return
    }
    if (!selectedBrand) {
      setError('請選擇要置入的品牌')
      return
    }
    setSubmitting(true)
    setError('')
    try {
      const topic = await api.post<PlacementTopicData>(
        '/api/v1/placement/topics/',
        {
          brand_id: brandId,
          topic_name: topicName.trim(),
          seed_query: seedQuery.trim(),
          brief: brief.trim(),
          product_id: productId ?? '',
        },
        { auth: true },
      )

      const job = await api.post<ExpandKnowledgeGraphData>(
        `/api/v1/placement/topics/${encodeURIComponent(topic.id)}/knowledge-graph/expand`,
        { seed_query: seedQuery.trim(), regenerate_map: true },
        { auth: true },
      )
      onCreated({
        topic,
        job_id: job.job_id,
        status: job.status,
        message: job.message,
      })
      onClose()
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '建立失敗')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div
      className="fixed inset-0 z-50 flex items-end justify-center bg-ink/40 p-3 sm:items-center sm:p-4"
      role="dialog"
      aria-modal
      aria-labelledby="create-placement-topic-title"
      onClick={onClose}
    >
      <div
        className="auth-ticket ac-dialog-texture w-full max-w-md shadow-soft"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-start justify-between gap-3 border-b border-line/70 px-5 py-4">
          <div className="min-w-0">
            <h2 id="create-placement-topic-title" className="text-lg font-bold text-ink">
              新增找 TA 主題
            </h2>
            <p className="mt-0.5 text-sm text-ink-secondary">
              選擇品牌後建立獨立主題，同一品牌可有多個主題。填種子詞後自動產生研究地圖。
            </p>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="ac-btn-secondary shrink-0 rounded-[var(--radius-pill)] px-3 py-1 text-xs"
            aria-label="關閉"
          >
            關閉
          </button>
        </div>

        <div className="space-y-4 px-5 py-4">
          {!catalogBrands.length ? (
            <p className="text-sm text-ink-secondary">
              尚未建立品牌。
              <Link to="/brands" className="ml-1 font-semibold text-brand hover:underline">
                前往品牌庫建立
              </Link>
            </p>
          ) : (
            <>
              <BrandProductPicker
                brands={catalogBrands}
                brandId={brandId}
                productId={productId}
                onBrandChange={setBrandId}
                onProductChange={setProductId}
              />

              <Field label="主題名稱">
                <Input
                  value={topicName}
                  onChange={(e) => setTopicName(e.target.value)}
                  placeholder="例：敏感肌換季保養"
                  data-islander-label="主題名稱"
                />
              </Field>
              <Field label="種子關鍵字">
                <Input
                  value={seedQuery}
                  onChange={(e) => setSeedQuery(e.target.value)}
                  placeholder="例：敏感肌、換季泛紅"
                  data-islander-label="種子關鍵字"
                />
              </Field>
              <Field label="主題目標">
                <Textarea
                  rows={2}
                  value={brief}
                  onChange={(e) => setBrief(e.target.value)}
                  placeholder="想服務誰、什麼情境、希望找到什麼留言機會"
                  data-islander-label="主題目標"
                />
              </Field>
            </>
          )}
        </div>

        <div className="px-5">
          <ErrorText message={error} />
        </div>
        <div className="flex flex-wrap justify-end gap-2 border-t border-line/70 px-5 py-4">
          <Button variant="ghost" onClick={onClose} disabled={submitting}>
            取消
          </Button>
          <Button
            onClick={() => void submit()}
            disabled={submitting || !catalogBrands.length || !brandHasCatalogProducts(selectedBrand)}
          >
            {submitting ? '建立中…' : '建立並產生研究地圖'}
          </Button>
        </div>
      </div>
    </div>
  )
}