import { useEffect, useState } from 'react'
import { api, ApiError } from '../api/client'
import { hasProductContext } from '../lib/productContext'
import type { CreatePlacementTopicData } from '../types/brand'
import { ProductContextForm } from './ProductContextForm'
import { Button, ErrorText, Field, Input, Textarea } from './ui'

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

export function CreatePlacementTopicDialog({ open, onClose, onCreated }: CreatePlacementTopicDialogProps) {
  const [displayName, setDisplayName] = useState('')
  const [seedQuery, setSeedQuery] = useState('')
  const [brief, setBrief] = useState('')
  const [productContext, setProductContext] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    if (!open) return
    setDisplayName('')
    setSeedQuery('')
    setBrief('')
    setProductContext('')
    setError('')
  }, [open])

  if (!open) return null

  const submit = async () => {
    if (!displayName.trim() || !seedQuery.trim() || !brief.trim()) {
      setError('請填寫主題名稱、種子關鍵字與主題目標')
      return
    }
    if (!hasProductContext(productContext)) {
      setError('請填寫想置入的品牌與產品')
      return
    }
    setSubmitting(true)
    setError('')
    try {
      const data = await api.post<CreatePlacementTopicData>(
        '/api/v1/brands/placement-topics',
        {
          display_name: displayName.trim(),
          seed_query: seedQuery.trim(),
          brief: brief.trim(),
          product_context: productContext,
        },
        { auth: true },
      )
      onCreated(data)
      onClose()
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '建立失敗')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-ink/40 p-4" role="dialog" aria-modal>
      <div className="max-h-[90vh] w-full max-w-lg overflow-y-auto rounded-[var(--radius-card)] border-2 border-line bg-surface p-6 shadow-lg">
        <h2 className="text-lg font-bold text-ink">新增找 TA 主題</h2>
        <p className="mt-1 text-sm text-ink-secondary">
          填寫主題目標與置入產品後，系統會自動產生研究地圖並擴展知識圖譜。
        </p>

        <div className="mt-5 grid gap-4">
          <Field label="主題名稱">
            <Input
              value={displayName}
              onChange={(e) => setDisplayName(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={3}
              value={brief}
              onChange={(e) => setBrief(e.target.value)}
              placeholder="想服務誰、什麼情境、希望找到什麼樣的留言機會"
              data-islander-label="主題目標"
            />
          </Field>
          <div>
            <p className="mb-2 text-sm font-semibold text-ink">想置入的品牌與產品</p>
            <ProductContextForm value={productContext} onChange={setProductContext} compact />
          </div>
        </div>

        <ErrorText message={error} />
        <div className="mt-5 flex flex-wrap justify-end gap-2">
          <Button variant="ghost" onClick={onClose} disabled={submitting}>
            取消
          </Button>
          <Button onClick={() => void submit()} disabled={submitting}>
            {submitting ? '建立中…' : '建立並產生研究地圖'}
          </Button>
        </div>
      </div>
    </div>
  )
}