import { useEffect, useMemo, useState } from 'react'
import { useOutletContext, useParams } from 'react-router-dom'
import { api, ApiError } from '../api/client'
import { getLastPublishPersonaId, setLastPublishPersonaId } from '../lib/publishPersona'
import { threadsAccountConnected } from '../lib/threadsAccount'
import type { ListPersonasData, PersonaData, ThreadsAccountData } from '../types/api'
import {
  AcLink,
  Badge,
  Button,
  Card,
  ErrorText,
  Field,
  Notice,
  SectionTitle,
  Select,
  SuccessText,
  Textarea,
} from '../components/ui'

const THREADS_MAX_CHARS = 500

type WorkspaceContext = {
  accountId: string
  account: ThreadsAccountData | null
  loading: boolean
  error: string
}

export function ThreadsAccountPublishPage() {
  const { id = '' } = useParams()
  const { account, loading: workspaceLoading } = useOutletContext<WorkspaceContext>()
  const [personas, setPersonas] = useState<PersonaData[]>([])
  const [personaId, setPersonaId] = useState('')
  const [topic, setTopic] = useState('')
  const [text, setText] = useState('')
  const [busy, setBusy] = useState(false)
  const [message, setMessage] = useState('')
  const [error, setError] = useState('')

  useEffect(() => {
    if (!id) return
    setPersonaId(getLastPublishPersonaId(id))
    api
      .get<ListPersonasData>('/api/v1/personas', { auth: true })
      .then((data) => setPersonas(data.list ?? []))
      .catch((e) => setError(e instanceof ApiError ? e.message : '載入人設失敗'))
  }, [id])

  const selectedPersona = useMemo(
    () => personas.find((item) => item.id === personaId) ?? null,
    [personas, personaId],
  )

  const charCount = text.length
  const overLimit = charCount > THREADS_MAX_CHARS
  const canPublish = !!personaId && text.trim().length > 0 && !overLimit

  const onPersonaChange = (nextId: string) => {
    setPersonaId(nextId)
    if (id) setLastPublishPersonaId(id, nextId)
  }

  const publish = async () => {
    if (!id || !canPublish) return
    setBusy(true)
    setError('')
    setMessage('')
    try {
      if (!threadsAccountConnected(account)) {
        setError('請先到「連線設定」完成 Threads API 連線後再發文。')
        return
      }
      setMessage(
        `已準備發文（人設：${selectedPersona?.display_name || '未命名'}）。Threads 發布 API 即將接上。`,
      )
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '發文失敗')
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="grid gap-4">
      <Card className="grid gap-4">
        <div className="flex flex-wrap items-start justify-between gap-3">
          <div className="grid gap-2">
            <SectionTitle>發文</SectionTitle>
            <p className="text-sm leading-relaxed text-ink-secondary">
              人設與帳號已解綁，每次發文自行選擇語氣策略。人設在 <AcLink to="/personas">人設庫</AcLink>{' '}
              建立與維護。
            </p>
          </div>
          {account ? (
            <Badge tone={threadsAccountConnected(account) ? 'success' : 'warning'}>
              {threadsAccountConnected(account) ? '可發文' : '尚未連線'}
            </Badge>
          ) : null}
        </div>

        {!threadsAccountConnected(account) ? (
          <Notice
            tone="warning"
            title="Threads API 尚未就緒"
            message="請到「連線設定」分頁完成 API 連線後再發文。"
          />
        ) : null}

        <Field label="套用人設（必填）">
          <Select
            value={personaId}
            onChange={(e) => onPersonaChange(e.target.value)}
            disabled={workspaceLoading}
          >
            <option value="">請選擇人設</option>
            {personas.map((item) => (
              <option key={item.id} value={item.id}>
                {item.display_name || '未命名人設'}
              </option>
            ))}
          </Select>
        </Field>

        {selectedPersona ? (
          <div className="ac-slot grid gap-2 px-4 py-3 text-sm">
            {selectedPersona.brief ? (
              <p className="text-ink-secondary">{selectedPersona.brief}</p>
            ) : null}
            {selectedPersona.persona ? (
              <p className="whitespace-pre-wrap text-ink">{selectedPersona.persona}</p>
            ) : (
              <p className="text-muted">
                此人設尚無詳細描述。{' '}
                <AcLink to={`/personas/${selectedPersona.id}`}>前往編輯</AcLink>
              </p>
            )}
          </div>
        ) : null}

        {!personas.length ? (
          <AcLink to="/personas" className="ac-btn-secondary inline-flex w-fit items-center px-4 py-2 text-sm">
            先去建立人設
          </AcLink>
        ) : null}
      </Card>

      <Card className="grid gap-4">
        <Field label="主題或方向（選填）">
          <Textarea
            rows={2}
            value={topic}
            onChange={(e) => setTopic(e.target.value)}
            placeholder="例如：分享本週產品更新、回應常見問題…"
          />
        </Field>

        <Field label="貼文內容">
          <Textarea
            rows={8}
            value={text}
            onChange={(e) => setText(e.target.value)}
            placeholder="輸入要發布的 Threads 貼文…"
          />
          <p className={`ac-hint mt-2 ${overLimit ? '!font-bold !text-danger' : ''}`}>
            {charCount} / {THREADS_MAX_CHARS} 字
          </p>
        </Field>

        <div className="flex flex-wrap gap-2">
          <Button onClick={publish} disabled={busy || workspaceLoading || !canPublish}>
            {busy ? '處理中…' : '發布到 Threads'}
          </Button>
          {personaId ? (
            <AcLink
              to={`/personas/${personaId}`}
              className="ac-btn-secondary inline-flex items-center px-4 py-2 text-sm"
            >
              編輯此人設
            </AcLink>
          ) : null}
        </div>
      </Card>

      <ErrorText message={error} />
      <SuccessText message={message} />
    </div>
  )
}