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

const PAGE_SIZE = 20

export function ContributionTab({ month }: { month: string }) {
  const [page, setPage] = useState(1)
  const [sort, setSort] = useState('actual_store_contribution_rate_pct')
  const [filter, setFilter] = useState('')
  const [order, setOrder] = useState<'asc' | 'desc'>('asc')
  const { data, isLoading } = useQuery({ queryKey: ['se/contribution', month, page, sort, filter, order], queryFn: () => api.get(`/store-expense/store-contribution?page=${page}&page_size=${PAGE_SIZE}&sort=${sort}&filter=${filter}&order=${order}&month=${month}`) })

  if (isLoading) return <LoadingSpinner text="加载门店贡献利润..." />

  const rows = (data as any)?.data || []
  const meta = (data as any)?.meta || { page, pageSize: PAGE_SIZE, total: 0 }

  const filters = [
    { key: '', label: '全部' },
    { key: 'profitable', label: '盈利门店' },
    { key: 'loss', label: '亏损门店' },
    { key: 'zero_sales', label: '零销售门店' },
  ]

  const sorts = [
    { key: 'actual_store_contribution_rate_pct', label: '贡献率' },
    { key: 'received', label: '实收' },
    { key: 'actual_store_contribution', label: '贡献利润' },
    { key: 'contribution_variance', label: '贡献差异' },
    { key: 'operating_expense_rate_pct', label: '费用率' },
  ]

  return (
    <div className="space-y-4">
      <CollapsibleSection title="门店贡献利润分析" subtitle="实收 - 食材成本 - 营业费用 = 门店贡献利润">
        <FilterableTable
          data={rows}
          serverSide
          page={page}
          onPageChange={setPage}
          sort={sort}
          onSortChange={setSort}
          order={order}
          onOrderChange={setOrder}
          pageSize={PAGE_SIZE}
          total={meta.total}
          filter={filter}
          onFilterChange={setFilter}
          filterButtons={filters}
          sortOptions={sorts}
          defaultSort="actual_store_contribution_rate_pct"
          defaultOrder="asc"
          columns={[
            { key: 'sales_store_name', label: '门店' },
            { key: 'received', label: '实收', align: 'right', render: (r) => formatCurrency(r.received) },
            { key: 'theoretical_cost', label: '理论食材成本', align: 'right', render: (r) => formatCurrency(r.theoretical_cost) },
            { key: 'actual_food_cost', label: '实际食材成本', align: 'right', render: (r) => formatCurrency(r.actual_food_cost) },
            { key: 'operating_expense', label: '营业费用', align: 'right', render: (r) => formatCurrency(r.operating_expense) },
            { key: 'theoretical_store_contribution', label: '理论贡献', align: 'right', render: (r) => formatCurrency(r.theoretical_store_contribution) },
            { key: 'theoretical_store_contribution_rate_pct', label: '理论贡献率', align: 'right', render: (r) => formatPercent(r.theoretical_store_contribution_rate_pct) },
            { key: 'actual_store_contribution', label: '实际贡献', align: 'right', render: (r) => <span className={parseFloat(r.actual_store_contribution) < 0 ? 'text-red-600 font-medium' : 'text-green-600'}>{formatCurrency(r.actual_store_contribution)}</span> },
            { key: 'actual_store_contribution_rate_pct', label: '实际贡献率', align: 'right', render: (r) => <span className={parseFloat(r.actual_store_contribution_rate_pct) < 0 ? 'text-red-600 font-medium' : ''}>{formatPercent(r.actual_store_contribution_rate_pct)}</span> },
            { key: 'contribution_variance', label: '贡献差异', align: 'right', render: (r) => <span className={parseFloat(r.contribution_variance) < 0 ? 'text-red-600' : 'text-green-600'}>{formatCurrency(r.contribution_variance)}</span> },
          ]}
        />
      </CollapsibleSection>
    </div>
  )
}
