import { useEffect, useState } from 'react'
import { Outlet, useNavigate, useParams } from 'react-router-dom'
import { api, ApiError } from '../api/client'
import { useThreadsAccount } from '../threads/ThreadsAccountContext'
import { threadsAccountConnected, threadsAccountLabel, threadsAccountStatusLabel } from '../lib/threadsAccount'
import type { ThreadsAccountData } from '../types/api'
import { Badge, Button, Card, ErrorText, PageTitle, TabLink } from './ui'

const tabs = [
  { to: 'publish', label: '發文' },
  { to: 'connections', label: '連線設定' },
] as const

export function ThreadsAccountWorkspace() {
  const { id = '' } = useParams()
  const navigate = useNavigate()
  const { switchAccount, refresh } = useThreadsAccount()
  const [account, setAccount] = useState<ThreadsAccountData | null>(null)
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (!id) return
    let cancelled = false
    setLoading(true)
    setError('')
    ;(async () => {
      try {
        await switchAccount(id)
        const data = await api.get<ThreadsAccountData>(`/api/v1/threads-accounts/${encodeURIComponent(id)}`, {
          auth: true,
        })
        if (!cancelled) setAccount(data)
      } catch (e) {
        if (!cancelled) {
          setError(e instanceof ApiError ? e.message : '載入帳號失敗')
          setAccount(null)
        }
      } finally {
        if (!cancelled) setLoading(false)
      }
    })()
    return () => {
      cancelled = true
    }
  }, [id, switchAccount])

  useEffect(() => {
    refresh().catch(() => undefined)
  }, [id, refresh])

  if (!id) {
    return (
      <div>
        <PageTitle title="Threads 帳號" subtitle="請從頂部選擇或新增經營帳號" />
        <Card>
          <p className="text-sm text-ink-secondary">尚未指定帳號。</p>
        </Card>
      </div>
    )
  }

  return (
    <div>
      <PageTitle
        title={loading ? '載入帳號…' : threadsAccountLabel(account)}
        subtitle="管理 Threads API 連線與發文。人設在發文時選擇，不綁定帳號。開發工具在連線頁底部，正式上線後會移除。"
      />

      {account ? (
        <Card className="mb-4 flex flex-wrap items-center gap-2">
          <Badge tone={threadsAccountConnected(account) ? 'success' : 'neutral'}>
            {threadsAccountStatusLabel(account)}
          </Badge>
          {account.username ? (
            <span className="text-sm text-muted">@{account.username.replace(/^@/, '')}</span>
          ) : null}
        </Card>
      ) : null}

      <div className="mb-6 flex flex-wrap gap-2">
        {tabs.map((tab) => (
          <TabLink key={tab.to} to={`/threads/${id}/${tab.to}`}>
            {tab.label}
          </TabLink>
        ))}
        <Button type="button" variant="ghost" onClick={() => navigate('/')}>
          返回總覽
        </Button>
      </div>

      <ErrorText message={error} />
      <Outlet context={{ accountId: id, account, loading, error }} />
    </div>
  )
}