import { useEffect, useState } from 'react'
import { threadsPostPublishBlocked } from '../lib/threadsPostLimits'
import type { CopyDraftData } from '../types/api'
import { ThreadsPostCharMeter } from './ThreadsPostCharMeter'
import { Badge, Button, Field, Textarea } from './ui'

type DraftEdit = { text: string; hook: string }

type Props = {
  draft: CopyDraftData
  editing: boolean
  edit: DraftEdit
  onEdit: () => void
  onCancelEdit: () => void
  onChange: (patch: Partial<DraftEdit>) => void
  onSave: () => void
  onMarkReady: () => void
  onCopy: () => void | Promise<boolean>
  onPublish: () => void
  saving?: boolean
  publishing?: boolean
}

function draftKindLabel(type?: string) {
  return type === 'matrix' ? '矩陣' : '深仿寫'
}

function draftKindTone(type?: string): 'brand' | 'sky' {
  return type === 'matrix' ? 'brand' : 'sky'
}

function statusBadge(draft: CopyDraftData) {
  if (draft.status === 'published') return <Badge tone="success">已發布</Badge>
  if (draft.status === 'ready') return <Badge tone="success">可發布</Badge>
  return <Badge tone="neutral">草稿</Badge>
}

export function CopyMissionDraftCard({
  draft,
  editing,
  edit,
  onEdit,
  onCancelEdit,
  onChange,
  onSave,
  onMarkReady,
  onCopy,
  onPublish,
  saving,
  publishing,
}: Props) {
  const hook = editing ? edit.hook : draft.hook
  const text = editing ? edit.text : draft.text
  const bodyText = editing ? edit.text : draft.text
  const saveBlocked = threadsPostPublishBlocked(bodyText)
  const publishBlocked = saveBlocked
  const [copied, setCopied] = useState(false)

  useEffect(() => {
    if (!copied) return
    const timer = window.setTimeout(() => setCopied(false), 2000)
    return () => window.clearTimeout(timer)
  }, [copied])

  const handleCopy = async () => {
    const ok = await onCopy()
    if (ok) setCopied(true)
  }

  return (
    <article className="hx-copy-draft-card">
      <header className="hx-copy-draft-card__head">
        <div className="flex flex-wrap items-center gap-2">
          <Badge tone={draftKindTone(draft.draft_type)}>{draftKindLabel(draft.draft_type)}</Badge>
          {draft.sort_order ? <span className="text-xs text-muted">#{draft.sort_order}</span> : null}
          {draft.angle ? <span className="text-xs font-semibold text-ink-secondary">{draft.angle}</span> : null}
          {statusBadge(draft)}
        </div>
        {!editing ? (
          <div className="flex flex-wrap gap-1.5">
            <Button variant="ghost" type="button" onClick={onEdit}>
              修改
            </Button>
            <Button variant="ghost" type="button" onClick={() => void handleCopy()} disabled={copied}>
              {copied ? '已複製' : '複製'}
            </Button>
            {draft.status !== 'published' ? (
              <Button
                type="button"
                onClick={onPublish}
                disabled={publishing || publishBlocked}
                title={publishBlocked ? '內文超過 Threads 500 字上限或為空' : undefined}
              >
                {publishing ? '發布中…' : '發布'}
              </Button>
            ) : null}
          </div>
        ) : null}
      </header>

      {hook ? (
        <p className="hx-copy-draft-card__hook">
          <span className="text-xs font-bold text-brand">Hook</span>
          {editing ? (
            <Field label="">
              <Textarea rows={1} value={edit.hook} onChange={(e) => onChange({ hook: e.target.value })} className="text-[15px]" />
            </Field>
          ) : (
            <span className="text-sm text-ink">{hook}</span>
          )}
        </p>
      ) : null}

      {editing ? (
        <Field label="內文">
          <Textarea rows={6} value={edit.text} onChange={(e) => onChange({ text: e.target.value })} className="text-[15px]" />
          <ThreadsPostCharMeter text={edit.text} />
        </Field>
      ) : (
        <>
          <p className="hx-copy-draft-card__text whitespace-pre-wrap">{text}</p>
          <ThreadsPostCharMeter text={text} />
        </>
      )}

      {draft.reference_notes?.trim() && !editing ? (
        <p className="text-xs leading-relaxed text-muted">{draft.reference_notes}</p>
      ) : null}

      {editing ? (
        <div className="flex flex-wrap gap-2 border-t border-line pt-3">
          <Button
            variant="soft"
            type="button"
            onClick={onSave}
            disabled={saving || saveBlocked}
            title={saveBlocked ? '內文不可為空，且不得超過 Threads 500 字上限' : undefined}
          >
            {saving ? '儲存中…' : '儲存'}
          </Button>
          <Button variant="ghost" type="button" onClick={onMarkReady} disabled={saving || saveBlocked}>
            標記可發布
          </Button>
          <Button variant="ghost" type="button" onClick={onCancelEdit}>
            取消
          </Button>
        </div>
      ) : null}

      {draft.published_permalink ? (
        <a href={draft.published_permalink} target="_blank" rel="noreferrer" className="text-xs font-semibold text-brand hover:underline">
          查看已發布貼文
        </a>
      ) : null}
    </article>
  )
}