import { useEffect, useState } from 'react'
import { ApiError } from '../api/client'
import { useThreadsAccount } from '../threads/ThreadsAccountContext'
import type { ThreadsAccountData } from '../types/api'
import { Button, ErrorText, Field, Input, SectionTitle, SuccessText } from './ui'

export function AccountDisplayNameSettings({
  accountId,
  account,
  loading: accountsLoading,
}: {
  accountId: string
  account: ThreadsAccountData | null
  loading: boolean
}) {
  const { updateDisplayName } = useThreadsAccount()
  const [displayName, setDisplayName] = useState('')
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')
  const [saved, setSaved] = useState('')

  useEffect(() => {
    setDisplayName(account?.display_name?.trim() ?? '')
    setError('')
    setSaved('')
  }, [accountId, account?.display_name, account?.update_at])

  const username = account?.username?.trim().replace(/^@/, '')

  async function save() {
    setSaving(true)
    setError('')
    setSaved('')
    try {
      await updateDisplayName(accountId, displayName)
      setSaved('顯示名稱已更新')
    } catch (e) {
      setError(e instanceof ApiError ? e.message : '更新失敗')
    } finally {
      setSaving(false)
    }
  }

  return (
    <div className="grid gap-4">
      <div>
        <SectionTitle>經營帳號顯示名稱</SectionTitle>
        <p className="mt-1 text-sm leading-relaxed text-ink-secondary">
          只影響頂部帳號切換器與設定頁的顯示，不會改變 Threads 上的 @帳號。
        </p>
      </div>

      <Field label="顯示名稱">
        <Input
          value={displayName}
          onChange={(e) => setDisplayName(e.target.value)}
          placeholder={username ? `例如：主帳號（未填則顯示 @${username}）` : '例如：主帳號、品牌號 A'}
          disabled={accountsLoading || saving}
          onKeyDown={(e) => {
            if (e.key === 'Enter') void save()
          }}
        />
      </Field>

      {username ? (
        <p className="text-sm text-muted">
          已連線 Threads 帳號：<span className="font-semibold text-ink-secondary">@{username}</span>
        </p>
      ) : null}

      <div className="flex flex-wrap items-center gap-3">
        <Button type="button" onClick={() => void save()} disabled={accountsLoading || saving}>
          {saving ? '儲存中…' : '儲存顯示名稱'}
        </Button>
      </div>

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