import { useEffect, useMemo, useState } from 'react'
import type { CopyMissionData } from '../types/copyMission'
import { StringListEditor } from './StringListEditor'
import { Button, Field, Input, Textarea } from './ui'

export const MAX_COPY_SCAN_TAGS = 6

export type CopyMissionResearchMapDraft = {
  audience_summary: string
  content_goal: string
  questions: string[]
  pillars: string[]
  exclusions: string[]
  benchmark_notes: string
  selected_tags: string[]
}

type Props = {
  mission: CopyMissionData
  onSave: (draft: CopyMissionResearchMapDraft) => 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(mission: CopyMissionData): CopyMissionResearchMapDraft {
  const map = mission.research_map
  const selected = mission.selected_tags?.length
    ? [...mission.selected_tags]
    : (map?.suggested_tags ?? []).slice(0, MAX_COPY_SCAN_TAGS).map((item) => item.tag)
  return {
    audience_summary: map?.audience_summary?.trim() ?? '',
    content_goal: map?.content_goal?.trim() ?? '',
    questions: [...(map?.questions ?? [])],
    pillars: [...(map?.pillars ?? [])],
    exclusions: [...(map?.exclusions ?? [])],
    benchmark_notes: map?.benchmark_notes?.trim() ?? '',
    selected_tags: selected.length > 0 ? selected : [],
  }
}

export function CopyMissionResearchEditor({ mission, onSave, onCancel }: Props) {
  const saved = useMemo(() => toDraft(mission), [mission])
  const [draft, setDraft] = useState<CopyMissionResearchMapDraft>(saved)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')

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

  const dirty = JSON.stringify(draft) !== JSON.stringify(saved)
  const suggestions = useMemo(() => {
    const current = new Set(draft.selected_tags.map((item) => item.trim()).filter(Boolean))
    return (mission.research_map?.suggested_tags ?? [])
      .map((item) => item.tag.trim())
      .filter((tag) => tag && !current.has(tag))
  }, [draft.selected_tags, mission.research_map?.suggested_tags])

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

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

  const addTag = () => {
    if (draft.selected_tags.length >= MAX_COPY_SCAN_TAGS) return
    setDraft((prev) => ({ ...prev, selected_tags: [...prev.selected_tags, ''] }))
  }

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

  const save = async () => {
    setSaving(true)
    setError('')
    try {
      const payload: CopyMissionResearchMapDraft = {
        audience_summary: draft.audience_summary.trim(),
        content_goal: draft.content_goal.trim(),
        questions: cleanLines(draft.questions),
        pillars: cleanLines(draft.pillars),
        exclusions: cleanLines(draft.exclusions),
        benchmark_notes: draft.benchmark_notes.trim(),
        selected_tags: cleanLines(draft.selected_tags).slice(0, MAX_COPY_SCAN_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">
        <Field label="對標筆記">
          <Textarea
            value={draft.benchmark_notes}
            onChange={(e) => setDraft((prev) => ({ ...prev, benchmark_notes: e.target.value }))}
            placeholder="可記錄想模仿的語氣、結構或禁忌"
            rows={3}
            className="text-[15px]"
          />
        </Field>
      </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_COPY_SCAN_TAGS} 組</span>
        </div>
        <p className="mb-3 text-sm text-ink-secondary">
          像真人會在 Threads 搜尋框輸入的詞；海巡只掃你儲存的標籤，節省 API 配額。
        </p>
        {draft.selected_tags.length === 0 ? (
          <p className="mb-3 text-sm text-muted">尚無搜尋標籤，請先完成研究地圖產生或手動新增。</p>
        ) : null}
        <ol className="hx-patrol-editor">
          {draft.selected_tags.map((item, index) => (
            <li key={`copy-tag-${index}`} className="hx-patrol-editor__row">
              <span className="hx-patrol-picks__rank">{index + 1}</span>
              <Input
                value={item}
                onChange={(e) => updateTag(index, e.target.value)}
                placeholder="例：平價底妝 推薦"
                className="flex-1 text-[15px]"
              />
              <Button variant="ghost" type="button" onClick={() => removeTag(index)}>
                移除
              </Button>
            </li>
          ))}
        </ol>
        <div className="hx-research-actions hx-research-actions--inline">
          <Button
            variant="ghost"
            type="button"
            onClick={addTag}
            disabled={draft.selected_tags.length >= MAX_COPY_SCAN_TAGS}
          >
            新增標籤
          </Button>
        </div>
        {suggestions.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">
              {suggestions.map((tag) => (
                <li key={tag}>
                  <button
                    type="button"
                    className="hx-patrol-chips__item hx-patrol-chips__item--action"
                    onClick={() => addSuggestedTag(tag)}
                    disabled={draft.selected_tags.length >= MAX_COPY_SCAN_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>
  )
}