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

const PAGE_SIZE = 15

export function QualityTab({ month }: { month: string }) {
  const [dishPage, setDishPage] = useState(1)
  const [matPage, setMatPage] = useState(1)
  const [dishSort, setDishSort] = useState('sales_amount')
  const [dishOrder, setDishOrder] = useState<'asc' | 'desc'>('desc')
  const [matSort, setMatSort] = useState('dish_count')
  const [matOrder, setMatOrder] = useState<'asc' | 'desc'>('desc')

  const { data: ov, isLoading: l1 } = useQuery({ queryKey: ['ca/data-quality', month], queryFn: () => api.get('/cost-analysis/data-quality', { params: { month } }) })
  const { data: dishes, isLoading: l2 } = useQuery({ queryKey: ['ca/unmatched-dishes', month, dishPage, dishSort, dishOrder], queryFn: () => api.get(`/cost-analysis/unmatched-dishes`, { params: { month, page: dishPage, page_size: PAGE_SIZE, sort: dishSort, order: dishOrder } }) })
  const { data: materials, isLoading: l3 } = useQuery({ queryKey: ['ca/unmatched-materials', month, matPage, matSort, matOrder], queryFn: () => api.get(`/cost-analysis/unmatched-materials`, { params: { month, page: matPage, page_size: PAGE_SIZE, sort: matSort, order: matOrder } }) })

  if (l1 || l2 || l3) return <LoadingSpinner text="加载数据质量..." />

  const ovData = (ov as any)?.data || {}
  const dishData = (dishes as any)?.data || []
  const dishMeta = (dishes as any)?.meta || { total: 0 }
  const matData = (materials as any)?.data || []
  const matMeta = (materials as any)?.meta || { total: 0 }

  const dishMatchRate = ovData.total_dishes > 0 ? (Number(ovData.matched_dishes) / Number(ovData.total_dishes) * 100) : 0
  const matMatchRate = ovData.total_materials > 0 ? (Number(ovData.matched_materials) / Number(ovData.total_materials) * 100) : 0

  const qualityChecks = [
    { check: 'BOM覆盖率', value: `${ovData.bom_coverage || 0}%`, abnormal: `${ovData.total_sku - ovData.sku_with_bom}个SKU缺BOM`, status: Number(ovData.bom_coverage) < 80 ? '异常' : '正常' },
    { check: '菜品匹配率', value: `${dishMatchRate.toFixed(2)}%`, abnormal: `${Number(ovData.total_dishes) - Number(ovData.matched_dishes)}个未匹配`, status: dishMatchRate < 90 ? '异常' : '正常' },
    { check: '物料匹配率', value: `${matMatchRate.toFixed(2)}%`, abnormal: `${Number(ovData.total_materials) - Number(ovData.matched_materials)}个未匹配`, status: matMatchRate < 90 ? '异常' : '正常' },
    { check: '零实际用量BOM', value: `${ovData.zero_actual_bom}条`, abnormal: 'standard_net_quantity = 0', status: Number(ovData.zero_actual_bom) > 0 ? '异常' : '正常' },
    { check: '负毛利率菜品', value: `${ovData.negative_margin_count}道`, abnormal: '实际毛利率 < 0', status: Number(ovData.negative_margin_count) > 0 ? '异常' : '正常' },
    { check: '理论负毛利菜品', value: `${ovData.negative_theo_margin_count}道`, abnormal: '理论毛利率 < 0', status: Number(ovData.negative_theo_margin_count) > 0 ? '异常' : '正常' },
  ]

  const checkColor = (status: string) => status === '异常' ? 'bg-red-100 text-red-700' : 'bg-green-100 text-green-700'

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-2 gap-3 md:grid-cols-3">
        <MetricCard title="BOM覆盖率" value={ovData.bom_coverage} format="percent" description="有BOM的SKU占总SKU比例" />
        <MetricCard title="菜品匹配率" value={dishMatchRate.toFixed(2)} format="percent" />
        <MetricCard title="物料匹配率" value={matMatchRate.toFixed(2)} format="percent" />
      </div>

      <CollapsibleSection title="BOM数据质量检查" subtitle="每月固定检查项">
        <FilterableTable
          data={qualityChecks}
          sortOptions={[
            { key: 'check', label: '检查项' },
            { key: 'status', label: '状态' },
          ]}
          defaultSort="check"
          defaultOrder="asc"
          filterKey="status"
          filterLabel="全部状态"
          columns={[
            { key: 'check', label: '检查项' },
            { key: 'value', label: '值', align: 'right' },
            { key: 'abnormal', label: '异常说明' },
            { key: 'status', label: '状态', render: (r) => (
              <span className={`rounded px-2 py-0.5 text-xs font-medium ${checkColor(r.status)}`}>{r.status}</span>
            )},
          ]}
        />
      </CollapsibleSection>

      <CollapsibleSection title="未匹配菜品清单" subtitle="菜品成本报表中未匹配到销售数据的菜品" defaultOpen={false}>
        <FilterableTable
          data={dishData}
          serverSide
          page={dishPage}
          onPageChange={setDishPage}
          sort={dishSort}
          onSortChange={setDishSort}
          order={dishOrder}
          onOrderChange={setDishOrder}
          pageSize={PAGE_SIZE}
          total={dishMeta.total}
          sortOptions={[
            { key: 'sales_amount', label: '销售额' },
            { key: 'dish_name', label: '菜品名' },
          ]}
          defaultSort="sales_amount"
          columns={[
            { key: 'dish_name', label: '菜品名' },
            { key: 'dish_code', label: '编码' },
            { key: 'category_level1', label: '品类' },
            { key: 'sales_amount', label: '销售额', align: 'right', render: (r) => formatCurrency(r.sales_amount) },
          ]}
        />
      </CollapsibleSection>

      <CollapsibleSection title="未匹配物料清单" subtitle="未匹配到库存数据的物料" defaultOpen={false}>
        <FilterableTable
          data={matData}
          serverSide
          page={matPage}
          onPageChange={setMatPage}
          sort={matSort}
          onSortChange={setMatSort}
          order={matOrder}
          onOrderChange={setMatOrder}
          pageSize={PAGE_SIZE}
          total={matMeta.total}
          sortOptions={[
            { key: 'dish_count', label: '涉及菜品数' },
            { key: 'loss_amount', label: '损耗金额' },
            { key: 'material_name', label: '物料名' },
          ]}
          defaultSort="dish_count"
          columns={[
            { key: 'material_name', label: '物料名' },
            { key: 'material_type', label: '类型', align: 'center' },
            { key: 'dish_count', label: '涉及菜品数', align: 'right', render: (r) => formatNumber(r.dish_count) },
            { key: 'loss_amount', label: '损耗金额', align: 'right', render: (r) => formatCurrency(r.loss_amount) },
          ]}
        />
      </CollapsibleSection>
    </div>
  )
}
