import { useQuery } from '@tanstack/react-query'
import api from '@/lib/api'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { FilterableTable } from '@/components/FilterableTable'
import { useState } from 'react'
import { Database, Table, Layers, Settings, ChevronRight, Box, ArrowRight } from 'lucide-react'
import { cn } from '@/lib/utils'

type TabType = 'overview' | 'dimensions' | 'facts' | 'enums' | 'metrics'

const TABLE_LABELS: Record<string, string> = {
  dim_store: '门店主数据',
  dim_sku: 'SKU主数据',
  dim_material: '原料主数据',
  dim_member: '会员主数据',
  dim_employee: '员工主数据',
  dim_channel: '渠道主数据',
  dim_promotion: '活动主数据',
  dim_calendar: '日历主数据',
  dim_supplier: '供应商主数据',
  fact_bill: '账单事实表',
  fact_bill_item: '账单明细事实表',
  fact_payment: '支付事实表',
  fact_promotion_usage: '优惠使用事实表',
  fact_platform_order: '平台订单损益表',
  fact_inventory_snapshot: '库存快照事实表',
  fact_purchase_receipt: '采购收货事实表',
  fact_transfer: '调拨事实表',
  fact_waste: '报损事实表',
  fact_recipe_bom: 'BOM配方事实表',
  fact_employee_shift: '员工排班事实表',
  fact_customer_contact: '会员触达事实表',
  fact_store_task: '门店任务事实表',
  enum_risk_level: '风险等级',
  enum_priority: '任务优先级',
  enum_task_status: '任务状态',
  enum_verification_result: '验收结果',
  enum_sku_type: 'SKU类型',
  enum_sku_status: 'SKU状态',
  enum_business_type: '业态类型',
  enum_channel_group: '渠道分组',
  enum_metric_direction: '指标方向',
  enum_member_status: '会员状态',
  enum_waste_reason: '报损原因',
  enum_management_quadrant: '管理象限',
}

const labelOf = (name: string) => TABLE_LABELS[name] || name

export function OntologyPage() {
  const [tab, setTab] = useState<TabType>('overview')
  const [selectedTable, setSelectedTable] = useState<string | null>(null)
  const [metricFilter, setMetricFilter] = useState('全部')

  const { data: overview, isLoading: overviewLoading } = useQuery({
    queryKey: ['ontology/overview'],
    queryFn: () => api.get('/tasks/ontology/overview'),
    enabled: tab === 'overview',
  })

  const { data: dimData, isLoading: dimLoading } = useQuery({
    queryKey: ['ontology/dim', selectedTable],
    queryFn: () => api.get(`/tasks/ontology/dim/${selectedTable}`),
    enabled: tab === 'dimensions' && !!selectedTable,
  })

  const { data: factData, isLoading: factLoading } = useQuery({
    queryKey: ['ontology/fact', selectedTable],
    queryFn: () => api.get(`/tasks/ontology/fact/${selectedTable}`),
    enabled: tab === 'facts' && !!selectedTable,
  })

  const { data: enumData, isLoading: enumLoading } = useQuery({
    queryKey: ['ontology/enum', selectedTable],
    queryFn: () => api.get(`/tasks/ontology/enum/${selectedTable}`),
    enabled: tab === 'enums' && !!selectedTable,
  })

  const { data: metricsData, isLoading: metricsLoading } = useQuery({
    queryKey: ['ontology/metrics'],
    queryFn: () => api.get('/tasks/ontology/metrics'),
    enabled: tab === 'metrics',
  })

  const ov = (overview as any)?.data
  const dim = (dimData as any)?.data
  const fact = (factData as any)?.data
  const enumRows = (enumData as any)?.data || []
  const metrics = (metricsData as any)?.data || []

  if (tab === 'overview' && overviewLoading) return <LoadingSpinner text="加载本体标准概览..." />
  if (tab === 'dimensions' && dimLoading) return <LoadingSpinner text="加载维度主数据..." />
  if (tab === 'facts' && factLoading) return <LoadingSpinner text="加载事实表..." />
  if (tab === 'enums' && enumLoading) return <LoadingSpinner text="加载枚举标准..." />
  if (tab === 'metrics' && metricsLoading) return <LoadingSpinner text="加载指标标准..." />

  const tabs: { key: TabType; label: string; icon: any }[] = [
    { key: 'overview', label: '概览', icon: Database },
    { key: 'dimensions', label: '维度主数据', icon: Box },
    { key: 'facts', label: '事实表', icon: Table },
    { key: 'enums', label: '枚举标准', icon: Layers },
    { key: 'metrics', label: '指标标准', icon: Settings },
  ]

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-bold">本体标准</h1>
      </div>

      {/* Tab bar */}
      <div className="flex gap-1 border-b">
        {tabs.map(t => {
          const Icon = t.icon
          return (
            <button
              key={t.key}
              onClick={() => { setTab(t.key); setSelectedTable(null) }}
              className={cn(
                'flex items-center gap-2 px-4 py-2 text-sm font-medium border-b-2 transition-colors',
                tab === t.key ? 'border-primary text-primary' : 'border-transparent text-muted-foreground hover:text-foreground'
              )}
            >
              <Icon size={16} />
              {t.label}
            </button>
          )
        })}
      </div>

      {/* Overview */}
      {tab === 'overview' && ov && (
        <div className="space-y-4">
          <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
            <StatCard title="维度主数据表" value={ov.dimensions?.length || 0} unit="张" icon={Box} color="text-blue-500" />
            <StatCard title="事实表" value={ov.facts?.length || 0} unit="张" icon={Table} color="text-green-500" />
            <StatCard title="枚举标准表" value={ov.enums?.length || 0} unit="张" icon={Layers} color="text-purple-500" />
            <StatCard title="指标标准" value={ov.metrics?.total || 0} unit={`条 (已标准化 ${ov.metrics?.standardized || 0})`} icon={Settings} color="text-orange-500" />
          </div>

          <div className="grid gap-4 lg:grid-cols-2">
            <TableListCard title="维度主数据" tables={ov.dimensions} icon={Box} onOpen={(name) => { setTab('dimensions'); setSelectedTable(name) }} />
            <TableListCard title="事实表" tables={ov.facts} icon={Table} onOpen={(name) => { setTab('facts'); setSelectedTable(name) }} />
          </div>

          <div className="grid gap-4 lg:grid-cols-2">
            <TableListCard title="枚举标准" tables={ov.enums} icon={Layers} onOpen={(name) => { setTab('enums'); setSelectedTable(name) }} />
            <div className="rounded-lg border p-4">
              <h3 className="mb-3 flex items-center gap-2 text-sm font-bold"><Settings size={16} /> 指标标准概览</h3>
              <div className="space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">总指标数</span>
                  <span className="font-bold">{ov.metrics?.total || 0}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">已标准化</span>
                  <span className="font-bold text-green-600">{ov.metrics?.standardized || 0}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">待标准化</span>
                  <span className="font-bold text-orange-600">{(ov.metrics?.total || 0) - (ov.metrics?.standardized || 0)}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">已启用</span>
                  <span className="font-bold text-blue-600">{ov.metrics?.active || 0}</span>
                </div>
                <button onClick={() => setTab('metrics')} className="mt-2 flex items-center gap-1 text-xs text-primary hover:underline">
                  查看全部指标 <ChevronRight size={12} />
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Dimensions */}
      {tab === 'dimensions' && (
        <div className="space-y-4">
          {!selectedTable ? (
            <div className="grid gap-3 md:grid-cols-3">
              {ov?.dimensions?.map((t: any) => (
                <TableCard key={t.table_name} name={t.table_name} label={labelOf(t.table_name)} columnCount={t.column_count} rowCount={t.row_count} onClick={() => setSelectedTable(t.table_name)} />
              ))}
            </div>
          ) : (
            <div className="space-y-4">
              <button onClick={() => setSelectedTable(null)} className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground">
                <ChevronRight size={14} className="rotate-180" /> 返回列表
              </button>
              <h2 className="text-lg font-bold">{labelOf(selectedTable)} <code className="text-sm text-muted-foreground">{selectedTable}</code></h2>
              <div className="rounded-lg border">
                <FilterableTable
                  data={dim?.rows || []}
                  sortOptions={dim?.columns?.slice(0, 5).map((c: any) => ({ key: c.column_name, label: c.column_name })) || []}
                  defaultSort={dim?.columns?.[0]?.column_name || ''}
                  defaultOrder="asc"
                  pageSize={20}
                  columns={dim?.columns?.map((c: any) => ({
                    key: c.column_name,
                    label: c.column_name,
                    render: (r: any) => {
                      const val = r[c.column_name]
                      if (val === null || val === undefined) return <span className="text-muted-foreground">—</span>
                      if (typeof val === 'object') return <code className="text-xs">{JSON.stringify(val)}</code>
                      if (c.data_type === 'timestamp with time zone' || c.data_type === 'timestamp without time zone') return <span className="text-xs">{String(val).substring(0, 19)}</span>
                      return <span className="text-xs">{String(val)}</span>
                    }
                  })) || []}
                />
              </div>
              <div className="text-xs text-muted-foreground">字段定义：</div>
              <div className="rounded-lg border p-3">
                <table className="w-full text-xs">
                  <thead>
                    <tr className="border-b text-left">
                      <th className="pb-2 pr-4 font-medium">字段名</th>
                      <th className="pb-2 pr-4 font-medium">类型</th>
                      <th className="pb-2 pr-4 font-medium">可空</th>
                      <th className="pb-2 font-medium">默认值</th>
                    </tr>
                  </thead>
                  <tbody>
                    {dim?.columns?.map((c: any) => (
                      <tr key={c.column_name} className="border-b last:border-0">
                        <td className="py-1.5 pr-4 font-mono">{c.column_name}</td>
                        <td className="py-1.5 pr-4 text-muted-foreground">{c.data_type}</td>
                        <td className="py-1.5 pr-4">{c.is_nullable === 'YES' ? '✓' : <span className="text-red-500">✗</span>}</td>
                        <td className="py-1.5 text-muted-foreground">{c.column_default || '—'}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      )}

      {/* Facts */}
      {tab === 'facts' && (
        <div className="space-y-4">
          {!selectedTable ? (
            <div className="grid gap-3 md:grid-cols-3">
              {ov?.facts?.map((t: any) => (
                <TableCard key={t.table_name} name={t.table_name} label={labelOf(t.table_name)} columnCount={t.column_count} rowCount={t.row_count} onClick={() => setSelectedTable(t.table_name)} />
              ))}
            </div>
          ) : (
            <div className="space-y-4">
              <button onClick={() => setSelectedTable(null)} className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground">
                <ChevronRight size={14} className="rotate-180" /> 返回列表
              </button>
              <h2 className="text-lg font-bold">{labelOf(selectedTable)} <code className="text-sm text-muted-foreground">{selectedTable}</code></h2>
              <div className="flex items-center gap-4 text-sm">
                <span className="text-muted-foreground">字段数: <span className="font-bold text-foreground">{fact?.columns?.length || 0}</span></span>
                <span className="text-muted-foreground">数据量: <span className="font-bold text-foreground">{Number(fact?.total || 0).toLocaleString()}</span> 行</span>
              </div>
              <div className="rounded-lg border p-3">
                <table className="w-full text-xs">
                  <thead>
                    <tr className="border-b text-left">
                      <th className="pb-2 pr-4 font-medium">字段名</th>
                      <th className="pb-2 pr-4 font-medium">类型</th>
                      <th className="pb-2 pr-4 font-medium">可空</th>
                      <th className="pb-2 font-medium">默认值</th>
                    </tr>
                  </thead>
                  <tbody>
                    {fact?.columns?.map((c: any) => (
                      <tr key={c.column_name} className="border-b last:border-0">
                        <td className="py-1.5 pr-4 font-mono">{c.column_name}</td>
                        <td className="py-1.5 pr-4 text-muted-foreground">{c.data_type}</td>
                        <td className="py-1.5 pr-4">{c.is_nullable === 'YES' ? '✓' : <span className="text-red-500">✗</span>}</td>
                        <td className="py-1.5 text-muted-foreground">{c.column_default || '—'}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      )}

      {/* Enums */}
      {tab === 'enums' && (
        <div className="space-y-4">
          {!selectedTable ? (
            <div className="grid gap-3 md:grid-cols-3">
              {ov?.enums?.map((t: any) => (
                <TableCard key={t.table_name} name={t.table_name} label={labelOf(t.table_name)} columnCount={t.column_count} rowCount={t.row_count} onClick={() => setSelectedTable(t.table_name)} />
              ))}
            </div>
          ) : (
            <div className="space-y-4">
              <button onClick={() => setSelectedTable(null)} className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground">
                <ChevronRight size={14} className="rotate-180" /> 返回列表
              </button>
              <h2 className="text-lg font-bold">{labelOf(selectedTable)} <code className="text-sm text-muted-foreground">{selectedTable}</code></h2>
              <div className="rounded-lg border">
                <FilterableTable
                  data={enumRows}
                  sortOptions={Object.keys(enumRows[0] || {}).slice(0, 3).map(k => ({ key: k, label: k }))}
                  defaultSort={Object.keys(enumRows[0] || {})[0] || ''}
                  defaultOrder="asc"
                  columns={Object.keys(enumRows[0] || {}).map(k => ({ key: k, label: k }))}
                />
              </div>
            </div>
          )}
        </div>
      )}

      {/* Metrics */}
      {tab === 'metrics' && (
        <div className="space-y-4">
          <div className="flex gap-2 flex-wrap">
            {['全部', '收入', '成本', '优惠', '会员', '商品', '库存', '风险'].map(cat => (
              <button key={cat} onClick={() => setMetricFilter(cat)} className={cn(
                'rounded-md border px-3 py-1 text-xs font-medium transition-colors',
                metricFilter === cat ? 'bg-primary text-primary-foreground border-primary' : 'hover:bg-muted'
              )}>{cat}</button>
            ))}
          </div>
          <div className="rounded-lg border">
            <FilterableTable
              data={metricFilter === '全部' ? metrics : metrics.filter((m: any) => m.metric_category === metricFilter)}
              sortOptions={[
                { key: 'indicator_name', label: '指标名称' },
                { key: 'metric_category', label: '分类' },
                { key: 'owner', label: '负责人' },
                { key: 'update_frequency', label: '频率' },
              ]}
              defaultSort="indicator_name"
              defaultOrder="asc"
              filterKey="metric_category"
              filterLabel="全部分类"
              columns={[
                { key: 'metric_code', label: '指标编码', render: (r: any) => <code className="text-xs text-blue-600">{r.metric_code || '—'}</code> },
                { key: 'indicator_name', label: '指标名称', render: (r: any) => <span className="font-medium">{r.indicator_name}</span> },
                { key: 'metric_category', label: '分类', render: (r: any) => r.metric_category ? <span className="rounded bg-muted px-2 py-0.5 text-xs">{r.metric_category}</span> : <span className="text-muted-foreground">—</span> },
                { key: 'business_definition', label: '业务定义', render: (r: any) => <span className="text-xs">{r.business_definition}</span> },
                { key: 'formula', label: '计算公式', render: (r: any) => <code className="text-xs">{r.formula}</code> },
                { key: 'unit', label: '单位', align: 'center' as const },
                { key: 'direction', label: '方向', render: (r: any) => r.direction === 'higher_better' ? <span className="text-green-600">↑越高越好</span> : r.direction === 'lower_better' ? <span className="text-red-600">↓越低越好</span> : '—' },
                { key: 'owner', label: '负责人', align: 'center' as const },
                { key: 'yellow_threshold', label: '黄线', align: 'right' as const, render: (r: any) => r.yellow_threshold ?? '—' },
                { key: 'red_threshold', label: '红线', align: 'right' as const, render: (r: any) => r.red_threshold ?? '—' },
                { key: 'update_frequency', label: '频率', align: 'center' as const },
                { key: 'version', label: '版本', render: (r: any) => <span className="text-xs text-muted-foreground">{r.version || '—'}</span> },
              ]}
            />
          </div>
        </div>
      )}
    </div>
  )
}

function StatCard({ title, value, unit, icon: Icon, color }: { title: string; value: number; unit: string; icon: any; color: string }) {
  return (
    <div className="rounded-lg border p-4">
      <div className="flex items-center justify-between">
        <p className="text-xs text-muted-foreground">{title}</p>
        <Icon size={16} className={color} />
      </div>
      <p className="mt-2 text-2xl font-bold">{value}</p>
      <p className="text-xs text-muted-foreground">{unit}</p>
    </div>
  )
}

function TableListCard({ title, tables, icon: Icon, onOpen }: { title: string; tables: any[]; icon: any; onOpen: (name: string) => void }) {
  return (
    <div className="rounded-lg border p-4">
      <h3 className="mb-3 flex items-center gap-2 text-sm font-bold"><Icon size={16} /> {title}</h3>
      <div className="space-y-1">
        {tables?.map((t) => (
          <button key={t.table_name} onClick={() => onOpen(t.table_name)} className="flex w-full items-center justify-between rounded-md px-3 py-2 text-sm hover:bg-muted transition-colors">
            <div className="flex items-center gap-2">
              <code className="text-xs text-muted-foreground">{t.table_name}</code>
              <span className="text-xs">{labelOf(t.table_name)}</span>
            </div>
            <div className="flex items-center gap-3 text-xs text-muted-foreground">
              <span>{t.column_count}列</span>
              <span>{Number(t.row_count).toLocaleString()}行</span>
              <ArrowRight size={12} />
            </div>
          </button>
        ))}
      </div>
    </div>
  )
}

function TableCard({ name, label, columnCount, rowCount, onClick }: { name: string; label: string; columnCount: number; rowCount: number; onClick: () => void }) {
  return (
    <button onClick={onClick} className="rounded-lg border p-4 text-left hover:border-primary hover:shadow-sm transition-all">
      <div className="flex items-center justify-between">
        <span className="font-medium">{label}</span>
        <ArrowRight size={14} className="text-muted-foreground" />
      </div>
      <code className="mt-1 block text-xs text-muted-foreground">{name}</code>
      <div className="mt-2 flex gap-4 text-xs text-muted-foreground">
        <span>{columnCount} 字段</span>
        <span>{Number(rowCount).toLocaleString()} 行</span>
      </div>
    </button>
  )
}
