import { useCallback, useMemo, useState } from 'react'
import { ApiError } from '../api/client'
import {
  patchCopyMissionSimilarAccount,
  similarAccountStatusLabel,
  sortSimilarAccounts,
} from '../lib/copyMissionSimilarAccounts'
import { threadsProfileUrl } from '../lib/threadsLinks'
import { similarAccountTone, viralAccountRowClass, viralAuthorTier, viralEngagementTier } from '../lib/viralSignals'
import type { CopyMissionData, CopySimilarAccountData } from '../types/copyMission'
import { similarAccountSourceLabel, similarAccountSourceTier } from '../types/copyMission'
import { VerifiedAuthorBadge } from './VerifiedAuthorBadge'
import { Badge, Button, Card } from './ui'

type Props = {
  mission: CopyMissionData
  personaId: string
  onMissionUpdate: (mission: CopyMissionData) => void
  onAddScanTag?: (username: string) => void
  onMessage?: (message: string) => void
  onError?: (message: string) => void
}

export function CopyMissionSimilarAccountsCard({
  mission,
  personaId,
  onMissionUpdate,
  onAddScanTag,
  onMessage,
  onError,
}: Props) {
  const [actionError, setActionError] = useState('')
  const accounts = useMemo(
    () => sortSimilarAccounts(mission.research_map?.similar_accounts ?? []),
    [mission.research_map?.similar_accounts],
  )

  const patchStatus = useCallback(
    async (username: string, status: 'recommended' | 'pinned' | 'excluded') => {
      const prev = mission
      const nextAccounts = (mission.research_map?.similar_accounts ?? []).map((item) =>
        item.username === username ? { ...item, status } : item,
      )
      onMissionUpdate({
        ...mission,
        research_map: { ...mission.research_map, similar_accounts: nextAccounts },
      })
      setActionError('')
      onError?.('')
      try {
        const updated = await patchCopyMissionSimilarAccount(personaId, mission.id, username, status)
        onMissionUpdate(updated)
        onMessage?.(
          status === 'pinned'
            ? `已釘選 @${username}`
            : status === 'excluded'
              ? `已排除 @${username}`
              : `已還原 @${username}`,
        )
      } catch (e) {
        onMissionUpdate(prev)
        const message = e instanceof ApiError ? e.message : '更新參考帳號失敗'
        setActionError(message)
        onError?.(message)
      }
    },
    [mission, onError, onMessage, onMissionUpdate, personaId],
  )

  if (!accounts.length) return null

  return (
    <Card className="hx-copy-similar-accounts">
      <h3 className="hx-copy-section-title">參考帳號</h3>
      <p className="text-xs text-muted">
        海巡後依主題與互動篩選；可釘選保留、排除不再推薦。藍勾與高互動列會以邊框標示。
      </p>
      {actionError ? <p className="text-sm text-danger">{actionError}</p> : null}
      <ul className="hx-copy-similar-accounts__list">
        {accounts.map((acc) => (
          <SimilarAccountRow
            key={acc.username}
            acc={acc}
            onPatch={patchStatus}
            onAddScanTag={onAddScanTag}
          />
        ))}
      </ul>
    </Card>
  )
}

function SimilarAccountRow({
  acc,
  onPatch,
  onAddScanTag,
}: {
  acc: CopySimilarAccountData
  onPatch: (username: string, status: 'recommended' | 'pinned' | 'excluded') => void
  onAddScanTag?: (username: string) => void
}) {
  const profileHref = threadsProfileUrl(acc.username, acc.profile_url)
  const tier = viralAuthorTier(acc)
  const engagementTier = viralEngagementTier(acc.engagement_score)
  const sourceTier = similarAccountSourceTier(acc.matched_source)
  const sourceTone = similarAccountTone(acc.matched_source, acc.author_verified)
  const rowClass = [
    viralAccountRowClass(tier),
    acc.status === 'pinned' ? 'hx-copy-similar-accounts__item--pinned' : '',
    acc.status === 'excluded' ? 'hx-copy-similar-accounts__item--excluded' : '',
  ]
    .filter(Boolean)
    .join(' ')
  const statusLabel = similarAccountStatusLabel(acc.status)

  return (
    <li className={rowClass}>
      <div className="min-w-0 flex-1 space-y-1">
        <div className="flex flex-wrap items-center gap-2">
          {profileHref ? (
            <a
              href={profileHref}
              target="_blank"
              rel="noreferrer"
              className="text-sm font-semibold text-brand hover:underline"
            >
              @{acc.username}
            </a>
          ) : (
            <span className="text-sm font-semibold text-ink">@{acc.username}</span>
          )}
          {acc.author_verified ? <VerifiedAuthorBadge compact /> : null}
          {sourceTier !== 'unknown' ? (
            <Badge tone={sourceTone}>{similarAccountSourceLabel(sourceTier)}</Badge>
          ) : null}
          {engagementTier === 'hot' ? <Badge tone="success">高互動</Badge> : null}
          {acc.engagement_score ? <Badge tone="brand">互動 {acc.engagement_score}</Badge> : null}
          {statusLabel ? <Badge tone="brand">{statusLabel}</Badge> : null}
          {acc.confidence ? <span className="text-xs text-muted">置信度 {acc.confidence}</span> : null}
          {acc.follower_count ? (
            <span className="text-xs text-muted">{acc.follower_count.toLocaleString()} 粉絲</span>
          ) : null}
          {acc.like_count ? <span className="text-xs text-muted">{acc.like_count} 讚</span> : null}
          {acc.post_count ? <span className="text-xs text-muted">{acc.post_count} 則相關貼文</span> : null}
        </div>
        {acc.reason ? <p className="text-xs leading-relaxed text-ink-secondary">{acc.reason}</p> : null}
      </div>
      <div className="flex flex-wrap gap-2">
        {acc.status === 'pinned' ? (
          <Button variant="ghost" onClick={() => void onPatch(acc.username, 'recommended')}>
            取消釘選
          </Button>
        ) : acc.status !== 'excluded' ? (
          <Button variant="soft" onClick={() => void onPatch(acc.username, 'pinned')}>
            釘選
          </Button>
        ) : null}
        {acc.status === 'excluded' ? (
          <Button variant="ghost" onClick={() => void onPatch(acc.username, 'recommended')}>
            取消排除
          </Button>
        ) : (
          <Button variant="ghost" onClick={() => void onPatch(acc.username, 'excluded')}>
            排除
          </Button>
        )}
        {onAddScanTag ? (
          <Button variant="ghost" onClick={() => onAddScanTag(acc.username)}>
            加入海巡
          </Button>
        ) : null}
      </div>
    </li>
  )
}