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 { formatCurrency, formatNumber, formatPercent } from '@/lib/utils'
import { useState } from 'react'

const PAGE_SIZE = 15

export function PackagingTab({ month }: { month: string }) {
  const [page, setPage] = useState(1)
  const [sort, setSort] = useState('total_cost')
  const [order, setOrder] = useState<'asc' | 'desc'>('desc')
  const [filter, setFilter] = useState('')

  const { data: ov, isLoading: l1 } = useQuery({ queryKey: ['ca/packaging-overview', month], queryFn: () => api.get('/cost-analysis/packaging-overview', { params: { month } }) })
  const { data: detail, isLoading: l2 } = useQuery({ queryKey: ['ca/packaging-detail', month, page, sort, order, filter], queryFn: () => api.get(`/cost-analysis/packaging-detail`, { params: { month, page, page_size: PAGE_SIZE, sort, order, filter } }) })

  if (l1 || l2) return <LoadingSpinner text="加载包装耗材数据..." />

  const ovData = (ov as any)?.data || {}
  const detailData = (detail as any)?.data || []
  const meta = (detail as any)?.meta || { total: 0 }

  const statusColor = (status: string) => {
    if (status === '核查') return 'bg-red-100 text-red-700'
    if (status === '关注') return 'bg-yellow-100 text-yellow-700'
    return 'bg-green-100 text-green-700'
  }

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
        <MetricCard title="包装物料种类" value={ovData.packaging_types} format="number" />
        <MetricCard title="包装总成本" value={ovData.total_cost} format="currency" />
        <MetricCard title="总损耗量" value={ovData.total_loss_qty} format="number" />
        <MetricCard title="高损耗包装数" value={ovData.high_loss_count} format="number" description="损耗率>20%" />
      </div>

      <CollapsibleSection title="包装物料明细" subtitle="餐盒、餐具、打包袋等耗材使用情况">
        <FilterableTable
          data={detailData}
          serverSide
          page={page}
          onPageChange={setPage}
          sort={sort}
          onSortChange={setSort}
          order={order}
          onOrderChange={setOrder}
          filter={filter}
          onFilterChange={setFilter}
          pageSize={PAGE_SIZE}
          total={meta.total}
          filterButtons={[
            { key: '', label: '全部' },
            { key: 'high_loss', label: '高损耗' },
            { key: 'normal', label: '正常' },
          ]}
          sortOptions={[
            { key: 'total_cost', label: '总成本' },
            { key: 'loss_qty', label: '损耗量' },
            { key: 'avg_loss_rate', label: '损耗率' },
            { key: 'dish_count', label: '涉及菜品数' },
          ]}
          defaultSort="total_cost"
          columns={[
            { key: 'material_name', label: '物料' },
            { key: 'dish_count', label: '涉及菜品数', align: 'right', render: (r) => formatNumber(r.dish_count) },
            { key: 'total_qty', label: '总用量', align: 'right', render: (r) => formatNumber(r.total_qty) },
            { key: 'total_cost', label: '总成本', align: 'right', render: (r) => formatCurrency(r.total_cost) },
            { key: 'loss_qty', label: '损耗量', align: 'right', render: (r) => formatNumber(r.loss_qty) },
            { key: 'avg_loss_rate', label: '平均损耗率', align: 'right', render: (r) => {
              const v = Number(r.avg_loss_rate || 0)
              return <span className={v < -20 ? 'text-red-600' : v < -5 ? 'text-yellow-600' : 'text-green-600'}>{formatPercent(v)}</span>
            }},
            { key: 'status', label: '状态', render: (r) => (
              <span className={`rounded px-2 py-0.5 text-xs font-medium ${statusColor(r.status)}`}>{r.status}</span>
            )},
          ]}
        />
      </CollapsibleSection>
    </div>
  )
}
