import { useEffect, useMemo, useState } from 'react'
import {
  MAX_TOP_PATROL_TAGS,
  patrolTagContextFromBrand,
  preparePatrolKeywordForSave,
  savedPatrolKeywords,
  suggestedPatrolKeywords,
  type KnowledgeGraphData,
} from '../lib/knowledgeGraph'
import type { BrandData, ResearchMapData } from '../types/brand'
import { StringListEditor } from './StringListEditor'
import { Button, Field, Input, Textarea } from './ui'

export type ResearchMapDraft = {
  audience_summary: string
  content_goal: string
  questions: string[]
  pillars: string[]
  exclusions: string[]
  patrol_keywords: string[]
}

type ResearchMapEditorProps = {
  map: ResearchMapData | null | undefined
  brand?: BrandData | null
  graph?: KnowledgeGraphData | null | undefined
  onSave: (draft: ResearchMapDraft) => Promise<void>
  onCancel?: () => void
}

function cleanLines(items: string[]) {
  const seen = new Set<string>()
  const out: string[] = []
  for (const item of items) {
    const trimmed = item.trim()
    if (!trimmed || seen.has(trimmed)) continue
    seen.add(trimmed)
    out.push(trimmed)
  }
  return out
}

function toDraft(
  map: ResearchMapData | null | undefined,
  fallbackKeywords: string[] = [],
): ResearchMapDraft {
  const patrolKeywords = savedPatrolKeywords(map)
  const resolved = patrolKeywords.length > 0 ? patrolKeywords : fallbackKeywords
  return {
    audience_summary: map?.audience_summary?.trim() ?? '',
    content_goal: map?.content_goal?.trim() ?? '',
    questions: [...(map?.questions ?? [])],
    pillars: [...(map?.pillars ?? [])],
    exclusions: [...(map?.exclusions ?? [])],
    patrol_keywords: resolved.length > 0 ? [...resolved] : [],
  }
}

export function ResearchMapEditor({ map, brand, graph, onSave, onCancel }: ResearchMapEditorProps) {
  const patrolContext = useMemo(() => patrolTagContextFromBrand(brand), [brand])
  const suggestions = useMemo(
    () => suggestedPatrolKeywords(map ?? brand?.research_map, graph?.nodes ?? [], patrolContext),
    [map, brand?.research_map, graph?.nodes, patrolContext],
  )
  const saved = useMemo(
    () => toDraft(map ?? brand?.research_map, suggestions),
    [map, brand?.research_map, suggestions],
  )

  const [draft, setDraft] = useState<ResearchMapDraft>(saved)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    setDraft(saved)
  }, [saved])

  const dirty = JSON.stringify(draft) !== JSON.stringify(saved)
  const extraSuggestions = useMemo(() => {
    const current = new Set(draft.patrol_keywords.map((item) => item.trim()).filter(Boolean))
    return suggestions.filter((tag) => !current.has(tag))
  }, [draft.patrol_keywords, suggestions])

  const updatePatrolKeyword = (index: number, value: string) => {
    setDraft((prev) => ({
      ...prev,
      patrol_keywords: prev.patrol_keywords.map((item, i) => (i === index ? value : item)),
    }))
  }

  const removePatrolKeyword = (index: number) => {
    setDraft((prev) => ({
      ...prev,
      patrol_keywords: prev.patrol_keywords.filter((_, i) => i !== index),
    }))
  }

  const addPatrolKeyword = () => {
    if (draft.patrol_keywords.length >= MAX_TOP_PATROL_TAGS) return
    setDraft((prev) => ({ ...prev, patrol_keywords: [...prev.patrol_keywords, ''] }))
  }

  const addSuggestedKeyword = (tag: string) => {
    if (draft.patrol_keywords.length >= MAX_TOP_PATROL_TAGS) return
    setDraft((prev) => {
      const existing = prev.patrol_keywords.map((item) => item.trim()).filter(Boolean)
      if (existing.includes(tag)) return prev
      const blanks = prev.patrol_keywords.filter((item) => !item.trim())
      if (blanks.length > 0) {
        const next = [...prev.patrol_keywords]
        const blankIndex = next.findIndex((item) => !item.trim())
        next[blankIndex] = tag
        return { ...prev, patrol_keywords: next }
      }
      return { ...prev, patrol_keywords: [...prev.patrol_keywords, tag] }
    })
  }

  const save = async () => {
    setSaving(true)
    setError('')
    try {
      const payload: ResearchMapDraft = {
        audience_summary: draft.audience_summary.trim(),
        content_goal: draft.content_goal.trim(),
        questions: cleanLines(draft.questions),
        pillars: cleanLines(draft.pillars),
        exclusions: cleanLines(draft.exclusions),
        patrol_keywords: cleanLines(
          draft.patrol_keywords
            .map((item) => preparePatrolKeywordForSave(item))
            .filter((item) => item.length > 0),
        ).slice(0, MAX_TOP_PATROL_TAGS),
      }
      await onSave(payload)
      setDraft(payload)
      onCancel?.()
    } catch (e) {
      setError(e instanceof Error ? e.message : '儲存失敗')
    } finally {
      setSaving(false)
    }
  }

  return (
    <div className="hx-research-map-layout hx-research-map-editor">
      <div className="hx-research-reader__block hx-research-reader__block--accent hx-research-map-layout__hero">
        <Field label="受眾是誰">
          <Textarea
            value={draft.audience_summary}
            onChange={(e) => setDraft((prev) => ({ ...prev, audience_summary: e.target.value }))}
            placeholder="描述這個主題的核心受眾輪廓、情境與痛點"
            rows={4}
            className="text-[15px]"
          />
        </Field>
      </div>

      <div className="hx-research-reader__block">
        <Field label="內容目標">
          <Textarea
            value={draft.content_goal}
            onChange={(e) => setDraft((prev) => ({ ...prev, content_goal: e.target.value }))}
            placeholder="這個主題要幫受眾解決什麼、建立什麼信任"
            rows={3}
            className="text-[15px]"
          />
        </Field>
      </div>

      <div className="hx-research-map-layout__duo">
        <div className="hx-research-reader__block h-full">
          <p className="hx-research-reader__label">受眾會問什麼</p>
          <StringListEditor
            items={draft.questions}
            onChange={(questions) => setDraft((prev) => ({ ...prev, questions }))}
            placeholder="例：化療期間可以用什麼沐浴乳？"
            addLabel="新增提問"
          />
        </div>
        <div className="hx-research-reader__block h-full">
          <p className="hx-research-reader__label">內容支柱</p>
          <StringListEditor
            items={draft.pillars}
            onChange={(pillars) => setDraft((prev) => ({ ...prev, pillars }))}
            placeholder="例：敏感肌保養觀念"
            addLabel="新增支柱"
          />
        </div>
      </div>

      <div className="hx-research-reader__block hx-research-reader__block--warn">
        <p className="hx-research-reader__label">不要碰</p>
        <StringListEditor
          items={draft.exclusions}
          onChange={(exclusions) => setDraft((prev) => ({ ...prev, exclusions }))}
          placeholder="例：療效保證、誇大宣稱"
          addLabel="新增排除項"
        />
      </div>

      <div className="hx-research-reader__block hx-research-reader__block--accent">
        <div className="hx-patrol-picks__head">
          <p className="hx-research-reader__label hx-research-reader__label--brand">優先海巡關鍵字</p>
          <span className="hx-patrol-picks__meta">精選最多 {MAX_TOP_PATROL_TAGS} 組</span>
        </div>
        <p className="mb-3 text-sm text-ink-secondary">
          研究地圖產生後會依受眾提問自動整理（6～14 字搜尋短句）。可直接開始海巡，也可微調後儲存。
        </p>
        {draft.patrol_keywords.length === 0 ? (
          <p className="mb-3 text-sm text-muted">尚無海巡關鍵字，請先完成研究地圖產生。</p>
        ) : null}
        <ol className="hx-patrol-editor">
          {draft.patrol_keywords.map((item, index) => (
            <li key={`patrol-${index}`} className="hx-patrol-editor__row">
              <span className="hx-patrol-picks__rank">{index + 1}</span>
              <Input
                value={item}
                onChange={(e) => updatePatrolKeyword(index, e.target.value)}
                placeholder="例：化療 沐浴乳（6～14 字短句）"
                className="flex-1 text-[15px]"
              />
              <Button variant="ghost" type="button" onClick={() => removePatrolKeyword(index)}>
                移除
              </Button>
            </li>
          ))}
        </ol>
        <div className="hx-research-actions hx-research-actions--inline">
          <Button
            variant="ghost"
            type="button"
            onClick={addPatrolKeyword}
            disabled={draft.patrol_keywords.length >= MAX_TOP_PATROL_TAGS}
          >
            新增關鍵字
          </Button>
        </div>
        {extraSuggestions.length > 0 ? (
          <div className="mt-3 space-y-2 border-t border-line pt-3">
            <p className="text-xs font-bold text-ink-secondary">更多建議（點一下加入）</p>
            <ul className="hx-patrol-chips">
              {extraSuggestions.map((tag) => (
                <li key={tag}>
                  <button
                    type="button"
                    className="hx-patrol-chips__item hx-patrol-chips__item--action"
                    onClick={() => addSuggestedKeyword(tag)}
                    disabled={draft.patrol_keywords.length >= MAX_TOP_PATROL_TAGS}
                  >
                    <span className="hx-patrol-chips__tag">{tag}</span>
                    <span className="hx-patrol-chips__action">加入</span>
                  </button>
                </li>
              ))}
            </ul>
          </div>
        ) : null}
      </div>

      <div className="hx-research-actions">
        {onCancel ? (
          <Button variant="ghost" type="button" onClick={onCancel} disabled={saving}>
            取消編輯
          </Button>
        ) : null}
        <Button variant="soft" type="button" onClick={() => void save()} disabled={!dirty || saving}>
          {saving ? '儲存中…' : '儲存研究地圖'}
        </Button>
        <span className="text-sm text-muted">調整後記得儲存，重新產生時會保留手動修改。</span>
      </div>
      {error ? <p className="text-sm text-danger">{error}</p> : null}
    </div>
  )
}
