import { useState } from 'react'
import { Loader2, Search, FileText, Database, Lightbulb, ExternalLink, X } from 'lucide-react'
import { PageHeader } from '@/components/PageHeader'
import { EmptyState } from '@/components/EmptyState'
import { useFinancialStatus } from '@/lib/useFinancials'
import { StockFinancialSearch } from '@/components/financials/StockFinancialSearch'
import { StockFinancialDetail } from '@/components/financials/StockFinancialDetail'
import { ReportHistoryPanel } from '@/components/financials/ReportHistoryPanel'
import { LastStockChip } from '@/components/LastStockChip'
import { useLastStock } from '@/lib/useLastStock'
import { fmtBigNum } from '@/lib/format'

const TABLE_LABELS: Record<string, string> = {
  metrics: '核心指标',
  income: '利润表',
  balance_sheet: '资产负债表',
  cash_flow: '现金流量表',
}

const TABLE_ICON: Record<string, typeof FileText> = {
  metrics: Database,
  income: FileText,
  balance_sheet: FileText,
  cash_flow: FileText,
}

export function Financials() {
  const { data: status, isLoading } = useFinancialStatus()
  const { last: lastStock, remember: rememberStock } = useLastStock('financials')
  const [selected, setSelected] = useState<{ symbol: string; name: string } | null>(null)
  const pick = (symbol: string, name: string) => {
    setSelected({ symbol, name })
    rememberStock(symbol, name)
  }

  // 等待 status 加载完, 判断是否有从 local 同步来的数据
  if (isLoading) {
    return (
      <>
        <PageHeader title="财务分析" subtitle="利润表 / 资负表 / 现金流 / 关键指标 / AI分析" />
        <div className="flex items-center justify-center py-16">
          <Loader2 className="h-5 w-5 animate-spin text-muted" />
        </div>
      </>
    )
  }
  if (!status?.available) {
    // 无同步数据
    return (
      <>
        <PageHeader title="财务分析" subtitle="利润表 / 资负表 / 现金流 / 关键指标 / AI分析" />
        <div className="px-8 py-10">
          <div className="mx-auto max-w-md rounded-card border border-warning/30 bg-warning/[0.04] p-8 text-center">
                <div className="flex items-center gap-1.5 text-xs font-medium text-accent">
                  <Lightbulb className="h-3.5 w-3.5 shrink-0" />
                  关于数据源
                </div>
                <p className="mt-1.5 text-[11px] leading-relaxed text-secondary">
                  当前财务数据源需付费,后续会接入免费数据源。如你常用某个免费财务数据源,欢迎在 Issues 中多多推荐哈 ~
                </p>
                <a
                  href="https://github.com/shy3130/tickflow-stock-panel/issues"
                  target="_blank"
                  rel="noreferrer"
                  className="mt-2 inline-flex items-center gap-1 text-[11px] font-medium text-accent hover:underline"
                >
                  前往 Issues 推荐
                  <ExternalLink className="h-3 w-3" />
                </a>
            </div>
          </div>
        </>
      )
    }
    // 有同步数据, 继续展示

  const tables = status?.tables ?? {}
  const available = status?.available ?? false

  return (
    <>
      <PageHeader
        title="财务分析"
        subtitle="利润表 / 资负表 / 现金流 / 关键指标 / AI分析 · Expert"
        right={
          <div className="flex items-center gap-2">
            <LastStockChip stock={lastStock} onSelect={pick} />

          </div>
        }
      />

      <div className="px-8 py-6 space-y-6 max-w-7xl">


        {/* 同步状态卡片 —— 始终显示,反映本地财务数据概况 */}
        {!isLoading && available && (
          <div>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
              {Object.entries(TABLE_LABELS).map(([key, label]) => {
                const info = tables[key]
                const TIcon = TABLE_ICON[key] ?? Database
                const hasData = (info?.rows ?? 0) > 0
                // 本次同步三态: 完成 / 同步中 / 等待 (仅全量同步时未轮到的表才"等待")

                return (
                  <div
                    key={key}
                    className={`rounded-card border p-3.5 transition-colors flex flex-col ${
                      hasData
                        ? 'border-border bg-surface'
                        : 'border-dashed border-border/60 bg-elevated/20'
                    }`}
                  >
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-1.5">
                        <TIcon className={`h-3.5 w-3.5 ${hasData ? 'text-accent' : 'text-muted'}`} />
                        <span className="text-xs font-medium text-foreground">{label}</span>
                      </div>

                    </div>
                    <div className="mt-2 text-xl font-semibold tabular-nums text-foreground">
                      {fmtBigNum(info?.rows ?? 0)}
                      <span className="text-[10px] text-muted ml-1 font-normal">行</span>
                    </div>
                    <div className="text-[11px] text-muted mt-0.5">
                      {fmtBigNum(info?.symbols ?? 0)} 只标的
                    </div>
                  </div>
                )
              })}
            </div>
          </div>
        )}

        {isLoading ? (
          <div className="flex items-center justify-center py-16">
            <Loader2 className="h-5 w-5 animate-spin text-muted" />
          </div>
        ) : !available ? (
          <div className="rounded-card border border-dashed border-border bg-surface px-6 py-14 text-center">
            <Database className="mx-auto h-8 w-8 text-muted" />
            <div className="mt-3 text-sm text-secondary">暂无财务数据</div>
            <div className="mt-1 text-xs text-muted">点击右上角"全部同步"从 TickFlow 拉取</div>
          </div>
        ) : (
          <>
            {/* 个股搜索区 */}
            <div>
              {selected ? (
                // 已选股:紧凑搜索条 + 清除按钮(便于换股)
                <div className="flex items-center gap-3">
                  <div className="flex-1 max-w-xl">
                    <StockFinancialSearch onSelect={pick} />
                  </div>
                  <button
                    onClick={() => setSelected(null)}
                    className="inline-flex items-center gap-1 px-2.5 py-1.5 text-xs text-secondary hover:text-foreground rounded-btn border border-border hover:bg-elevated transition-colors shrink-0"
                    title="清除选择"
                  >
                    <X className="h-3.5 w-3.5" />
                    清除
                  </button>
                </div>
              ) : (
                // 未选股:醒目居中引导
                <div className="flex flex-col items-center gap-3 py-8">
                  <div className="flex items-center gap-2 text-sm text-secondary">
                    <Search className="h-4 w-4 text-accent" />
                    <span>搜索个股查看详细财务数据</span>
                  </div>
                  <div className="w-full max-w-xl">
                    <StockFinancialSearch onSelect={pick} />
                  </div>
                  <div className="text-[11px] text-muted">支持股票代码或名称模糊匹配，如 600000 / 浦发</div>
                </div>
              )}
            </div>

            {/* 个股详情 / 空引导 */}
            <div className="pb-4">
              {selected ? (
                <StockFinancialDetail symbol={selected.symbol} name={selected.name} />
              ) : (
                <EmptyState
                  icon={Search}
                  title="未选择股票"
                  hint="在上方搜索框输入股票代码或名称，选择后即可查看该股的核心指标、利润表、资产负债表与现金流量表。"
                />
              )}
            </div>

            {/* AI 历史分析报告 */}
            {available && <ReportHistoryPanel />}
          </>
        )}
      </div>
    </>
  )
}
