import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import api from '@/lib/api'
import { FilterableTable } from '@/components/FilterableTable'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { CollapsibleSection } from '@/components/CollapsibleSection'
import { MetricCard } from '@/components/MetricCard'
import { formatNumber } from '@/lib/utils'

const IMPORT_TYPES = ['POS', '外卖', '库存', '费用', '薪资']

export function DataImportPage() {
  const queryClient = useQueryClient()

  const { data: logData, isLoading } = useQuery({
    queryKey: ['product/import-logs'],
    queryFn: () => api.get('/product/import-logs'),
  })

  const { data: qualityData } = useQuery({
    queryKey: ['product/quality-rules'],
    queryFn: () => api.get('/product/quality-rules'),
  })

  const triggerMutation = useMutation({
    mutationFn: (import_type: string) => api.post('/product/import/trigger', { import_type }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['product/import-logs'] }),
  })

  if (isLoading) return <LoadingSpinner text="加载数据导入日志..." />

  const logs = (logData as any)?.data || []
  const rules = (qualityData as any)?.data || []

  const successCount = logs.filter((l: any) => l.status === 'success').length
  const failedCount = logs.filter((l: any) => l.status === 'failed').length
  const runningCount = logs.filter((l: any) => l.status === 'running').length

  return (
    <div className="space-y-4">
      <div>
        <h1 className="text-xl font-bold">数据自动采集管道</h1>
        <p className="mt-0.5 text-xs text-muted-foreground">ETL管道 · 数据质量 · 导入监控</p>
      </div>

      <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
        <MetricCard title="导入记录" value={logs.length} format="number" description="总导入次数" />
        <MetricCard title="成功" value={successCount} format="number" description="成功导入次数" status="good" />
        <MetricCard title="失败" value={failedCount} format="number" description="失败导入次数" status="bad" />
        <MetricCard title="进行中" value={runningCount} format="number" description="正在执行的任务" status="warn" />
      </div>

      <CollapsibleSection title="手动触发导入" subtitle="选择数据源进行导入">
        <div className="flex flex-wrap gap-2">
          {IMPORT_TYPES.map(type => (
            <button
              key={type}
              onClick={() => triggerMutation.mutate(type)}
              disabled={triggerMutation.isPending}
              className="rounded bg-primary px-4 py-2 text-sm text-primary-foreground disabled:opacity-50"
            >
              导入{type}数据
            </button>
          ))}
        </div>
      </CollapsibleSection>

      <CollapsibleSection title={`导入日志 (${logs.length})`} subtitle="按时间降序">
        <FilterableTable
          data={logs}
          filterKey="import_type"
          filterLabel="全部类型"
          sortOptions={[
            { key: 'created_at', label: '创建时间' },
            { key: 'records_count', label: '记录数' },
          ]}
          defaultSort="created_at"
          defaultOrder="desc"
          columns={[
            { key: 'import_type', label: '导入类型' },
            { key: 'status', label: '状态', align: 'center', render: (r) => {
              const colors: Record<string, string> = { success: 'text-green-600', failed: 'text-red-600', running: 'text-yellow-600', pending: 'text-blue-600' }
              return <span className={`font-bold ${colors[r.status] || ''}`}>{r.status}</span>
            }},
            { key: 'records_count', label: '记录数', align: 'right', render: (r) => formatNumber(r.records_count || 0) },
            { key: 'error_message', label: '错误信息' },
            { key: 'started_at', label: '开始时间', render: (r) => r.started_at ? (r.started_at as string).substring(0, 19).replace('T', ' ') : '-' },
            { key: 'completed_at', label: '完成时间', render: (r) => r.completed_at ? (r.completed_at as string).substring(0, 19).replace('T', ' ') : '-' },
          ]}
        />
      </CollapsibleSection>

      <CollapsibleSection title={`数据质量规则 (${rules.length})`}>
        <FilterableTable
          data={rules}
          filterKey="rule_type"
          filterLabel="全部规则"
          sortOptions={[{ key: 'table_name', label: '表名' }, { key: 'rule_type', label: '规则类型' }]}
          defaultSort="table_name"
          defaultOrder="asc"
          columns={[
            { key: 'rule_name', label: '规则名称' },
            { key: 'table_name', label: '表名' },
            { key: 'column_name', label: '字段' },
            { key: 'rule_type', label: '规则类型', align: 'center' },
            { key: 'is_enabled', label: '启用', align: 'center', render: (r) => r.is_enabled ? '✅' : '❌' },
          ]}
        />
      </CollapsibleSection>
    </div>
  )
}
