import { Link } from 'react-router-dom'
import { AccountAiSettings } from '../components/AccountAiSettings'
import { PlacementResearchSettings } from '../components/PlacementResearchSettings'
import { AccountConnectionMode } from '../components/AccountConnectionMode'
import { AccountDisplayNameSettings } from '../components/AccountDisplayNameSettings'
import { ExtensionInstallCard } from '../components/ExtensionInstallCard'
import { useThreadsAccount } from '../threads/ThreadsAccountContext'
import { OnboardingGuideTarget } from '../components/OnboardingGuide'
import { Card, Notice, PageTitle, QuickLinkCard, SectionTitle } from '../components/ui'

export function SettingsPage() {
  const { activeAccountId, activeAccount, loading: accountsLoading } = useThreadsAccount()
  const connectionsPath = activeAccountId
    ? `/threads/${activeAccountId}/connections`
    : '/'

  return (
    <div className="grid gap-4">
      <PageTitle
        title="設定"
        subtitle="修改經營帳號顯示名稱與連線模式。AI 設定同一登入帳號共用，切換經營帳號不會改變。"
      />

      {!activeAccountId && !accountsLoading ? (
        <Notice
          tone="warning"
          title="尚未選擇經營帳號"
          message="請從頂部 Account Switcher 建立或選擇 Threads 帳號，再回來設定。"
        />
      ) : null}

      <div className="grid gap-4 md:grid-cols-2">
        <QuickLinkCard
          to={connectionsPath}
          icon="threads"
          title="Threads 連線細節"
          desc="API 狀態、Chrome Session 同步（開發模式用）"
        />
        <QuickLinkCard
          to="/personas"
          icon="persona"
          title="人設庫"
          desc="建立風格策略，發文時在帳號工作區選擇"
        />
      </div>

      <Card>
        <ExtensionInstallCard />
      </Card>

      {activeAccountId ? (
        <>
          <Card>
            <AccountDisplayNameSettings
              accountId={activeAccountId}
              account={activeAccount}
              loading={accountsLoading}
            />
          </Card>

          <OnboardingGuideTarget step="connection">
            <Card>
              <AccountConnectionMode accountId={activeAccountId} connectionsPath={connectionsPath} />
            </Card>
          </OnboardingGuideTarget>

          <Card>
            <PlacementResearchSettings />
          </Card>

          <Card className="grid gap-4">
            <div className="flex flex-wrap items-center justify-between gap-2">
              <div>
                <SectionTitle>AI 設定</SectionTitle>
                <p className="mt-1 text-sm text-ink-secondary">
                  此登入帳號下的所有經營帳號共用同一組 provider 與 API key。
                </p>
              </div>
              <Link to={connectionsPath} className="ac-btn-secondary inline-flex px-4 py-2 text-sm">
                連線設定
              </Link>
            </div>
            <AccountAiSettings accountId={activeAccountId} />
          </Card>
        </>
      ) : (
        <Card>
          <p className="text-sm text-ink-secondary">選擇帳號後即可設定連線模式與 AI API key。</p>
        </Card>
      )}
    </div>
  )
}