import { useQuery } from '@tanstack/react-query'
import api from '@/lib/api'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { CollapsibleSection } from '@/components/CollapsibleSection'
import { MetricCard } from '@/components/MetricCard'
import { formatNumber, formatCurrency } from '@/lib/utils'
import { useState } from 'react'
import { MonthPicker } from '@/components/MonthPicker'

export function DataQualityPage() {
  const [month, setMonth] = useState('2026-04')
  const { data: qualityData, isLoading } = useQuery({
    queryKey: ['data-quality', month],
    queryFn: () => api.get('/data-quality', { params: { month } }),
  })

  const dq = (qualityData as any)?.data || {}

  if (isLoading) {
    return <LoadingSpinner text="加载数据质量检查..." />
  }

  const totalBills = Number(dq.total_bills || 0)
  const missingBillNo = Number(dq.missing_bill_no || 0)
  const missingStoreCode = Number(dq.missing_store_code || 0)
  const zeroConsumption = Number(dq.zero_consumption || 0)
  const negativeReceived = Number(dq.negative_received || 0)
  const zeroReceived = Number(dq.zero_received || 0)
  const discountGtConsumption = Number(dq.discount_gt_consumption || 0)
  const storeCount = Number(dq.store_count || 0)
  const totalDishRecords = Number(dq.total_dish_records || 0)
  const dishMissingStore = Number(dq.dish_missing_store || 0)
  const dishMissingDish = Number(dq.dish_missing_dish || 0)
  const negativeConsumptionCount = Number(dq.negative_consumption_count || 0)
  const negativeConsumptionAmount = Number(dq.negative_consumption_amount || 0)

  // 四层状态规则：完整性、准确性、一致性、时效性
  const completenessStatus = missingBillNo === 0 && missingStoreCode === 0 && dishMissingStore === 0 && dishMissingDish === 0 ? '正常' : '异常'
  const accuracyStatus = negativeReceived === 0 && zeroConsumption < totalBills * 0.01 && discountGtConsumption === 0 ? '正常' : '需关注'
  const consistencyStatus = negativeConsumptionCount === 0 ? '正常' : '异常'
  const timelinessStatus = '正常'

  // 综合质量状态：任一异常即为不可直接使用
  const overallStatus = completenessStatus === '正常' && accuracyStatus === '正常' && consistencyStatus === '正常' ? '正常' : '需修复'

  // 利润数据置信等级
  const profitConfidence = overallStatus === '正常' ? 'A：已对账' : accuracyStatus === '需关注' ? 'B：待桥接' : 'C：异常'

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-bold">数据质量看板</h1>
          <p className="mt-0.5 text-xs text-muted-foreground">账单与菜品明细数据质量检查 · {dq.min_date?.substring(0, 10)} ~ {dq.max_date?.substring(0, 10)}</p>
        </div>
        <MonthPicker month={month} onChange={setMonth} />
      </div>

      {/* 质量状态总览 */}
      <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
        <div className={`rounded-lg border p-4 shadow-sm ${completenessStatus === '正常' ? 'border-green-200 bg-green-50/30' : 'border-red-200 bg-red-50/30'}`}>
          <p className="text-xs text-muted-foreground">完整性</p>
          <p className={`mt-1 text-lg font-bold ${completenessStatus === '正常' ? 'text-green-600' : 'text-red-600'}`}>{completenessStatus}</p>
          <p className="mt-0.5 text-[10px] text-muted-foreground">缺失字段检查</p>
        </div>
        <div className={`rounded-lg border p-4 shadow-sm ${accuracyStatus === '正常' ? 'border-green-200 bg-green-50/30' : 'border-yellow-200 bg-yellow-50/30'}`}>
          <p className="text-xs text-muted-foreground">准确性</p>
          <p className={`mt-1 text-lg font-bold ${accuracyStatus === '正常' ? 'text-green-600' : 'text-yellow-600'}`}>{accuracyStatus}</p>
          <p className="mt-0.5 text-[10px] text-muted-foreground">负值、零值、越界检查</p>
        </div>
        <div className={`rounded-lg border p-4 shadow-sm ${consistencyStatus === '正常' ? 'border-green-200 bg-green-50/30' : 'border-red-200 bg-red-50/30'}`}>
          <p className="text-xs text-muted-foreground">一致性</p>
          <p className={`mt-1 text-lg font-bold ${consistencyStatus === '正常' ? 'text-green-600' : 'text-red-600'}`}>{consistencyStatus}</p>
          <p className="mt-0.5 text-[10px] text-muted-foreground">库存负耗用等跨表检查</p>
        </div>
        <div className={`rounded-lg border p-4 shadow-sm ${profitConfidence.startsWith('A') ? 'border-green-200 bg-green-50/30' : profitConfidence.startsWith('B') ? 'border-yellow-200 bg-yellow-50/30' : 'border-red-200 bg-red-50/30'}`}>
          <p className="text-xs text-muted-foreground">利润数据置信等级</p>
          <p className={`mt-1 text-sm font-bold ${profitConfidence.startsWith('A') ? 'text-green-600' : profitConfidence.startsWith('B') ? 'text-yellow-600' : 'text-red-600'}`}>{profitConfidence}</p>
        </div>
      </div>

      {/* 账单数据质量 */}
      <CollapsibleSection title="账单数据质量" subtitle="原始账单表完整性检查">
        <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
          <MetricCard title="总账单数" value={totalBills} format="number" description="账单事实表总记录数" />
          <MetricCard title="覆盖门店数" value={storeCount} format="number" description="有交易记录的门店数量" />
          <MetricCard title="缺失账单号" value={missingBillNo} format="number" description="账单号为空的记录数，应为0" />
          <MetricCard title="缺失门店编码" value={missingStoreCode} format="number" description="门店编码为空的记录数，应为0" />
        </div>
        <div className="mt-3 grid grid-cols-2 gap-3 md:grid-cols-4">
          <MetricCard title="零消费账单" value={zeroConsumption} format="number" description="消费额为0的账单数，可能为撤单、赠送或导入问题" />
          <MetricCard title="负实收账单" value={negativeReceived} format="number" description="实收为负数的账单数，需区分退款、冲销和异常录入" />
          <MetricCard title="零实收账单" value={zeroReceived} format="number" description="实收为0的账单数，影响账单数、客单和优惠判断" />
          <MetricCard title="优惠大于消费" value={discountGtConsumption} format="number" description="优惠额超过消费额的账单数，需检查字段定义和冲销逻辑" />
        </div>
        {missingBillNo > 0 && (
          <div className="mt-3 rounded-md border border-yellow-200 bg-yellow-50/50 p-3">
            <p className="text-xs text-yellow-700">
              <span className="font-medium">提示：</span>
              {missingBillNo} 条账单缺失账单号，可能导致重复统计或关联失败，需排查源文件
            </p>
          </div>
        )}
        {missingStoreCode > 0 && (
          <div className="mt-3 rounded-md border border-red-200 bg-red-50/50 p-3">
            <p className="text-xs text-red-700">
              <span className="font-medium">提示：</span>
              {missingStoreCode} 条账单缺失门店编码，无法归属门店，需修复映射
            </p>
          </div>
        )}
      </CollapsibleSection>

      {/* 菜品明细数据质量 */}
      <CollapsibleSection title="菜品明细数据质量" subtitle="菜品销售明细表完整性检查">
        <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
          <MetricCard title="总菜品记录数" value={totalDishRecords} format="number" description="菜品销售明细表总记录数" />
          <MetricCard title="缺失门店" value={dishMissingStore} format="number" description="门店编码为空的记录数" />
          <MetricCard title="缺失菜品名" value={dishMissingDish} format="number" description="菜品名称为空的记录数" />
          <div className={`rounded-lg border p-4 shadow-sm ${dishMissingStore === 0 && dishMissingDish === 0 ? 'border-green-200 bg-green-50/30' : 'border-red-200 bg-red-50/30'}`}>
            <p className="text-xs text-muted-foreground">菜品质量状态</p>
            <p className={`mt-1 text-lg font-bold ${dishMissingStore === 0 && dishMissingDish === 0 ? 'text-green-600' : 'text-red-600'}`}>
              {dishMissingStore === 0 && dishMissingDish === 0 ? '正常' : '异常'}
            </p>
          </div>
        </div>
        {dishMissingStore > 0 && (
          <div className="mt-3 rounded-md border border-red-200 bg-red-50/50 p-3">
            <p className="text-xs text-red-700">
              <span className="font-medium">提示：</span>
              {dishMissingStore} 条菜品明细缺失门店编码，无法进行门店级SKU分析
            </p>
          </div>
        )}
      </CollapsibleSection>

      {/* 库存数据质量 */}
      <CollapsibleSection title="库存数据质量" subtitle="库存倒挤成本异常检查" defaultOpen={false}>
        <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
          <MetricCard title="负耗用记录数" value={negativeConsumptionCount} format="number" description="消费金额为负数的库存记录数，可能扭曲成本和库存周转" />
          <MetricCard title="负耗用金额" value={negativeConsumptionAmount} format="currency" description="负耗用记录的金额合计，需排查盘点差异或录入错误" />
        </div>
        {negativeConsumptionCount > 0 && (
          <div className="mt-3 rounded-md border border-red-200 bg-red-50/50 p-3">
            <p className="text-xs text-red-700">
              <span className="font-medium">提示：</span>
              {negativeConsumptionCount} 条库存负耗用记录，金额 {formatCurrency(negativeConsumptionAmount)}，可能扭曲成本和库存周转，需排查盘点差异或录入错误
            </p>
          </div>
        )}
      </CollapsibleSection>

      {/* 数据治理建议 */}
      <CollapsibleSection title="数据治理建议" subtitle="基于管理体系的数据质量要求" defaultOpen={false}>
        <div className="space-y-3 text-sm">
          <div className="rounded-md border border-blue-200 bg-blue-50/50 p-3">
            <p className="font-medium text-blue-700">统一编码</p>
            <p className="mt-1 text-xs text-muted-foreground">门店、SKU、原料、会员、员工、渠道、活动必须使用稳定编码。名称只能用于展示，不能作为唯一关联键</p>
          </div>
          <div className="rounded-md border border-blue-200 bg-blue-50/50 p-3">
            <p className="font-medium text-blue-700">每次导入自动检查</p>
            <p className="mt-1 text-xs text-muted-foreground">文件齐全性、日期完整性、行数金额对账、映射失败数量、重复账单、空值检查、异常金额、账单与明细对账、销售与成本单位匹配</p>
          </div>
          <div className="rounded-md border border-blue-200 bg-blue-50/50 p-3">
            <p className="font-medium text-blue-700">口径变更管理</p>
            <p className="mt-1 text-xs text-muted-foreground">口径变更必须保留版本和生效日期，不能直接覆盖历史结果。月报出具后如需更正，应记录更正原因和影响金额</p>
          </div>
        </div>
      </CollapsibleSection>
    </div>
  )
}
