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 FixedVariableTab({ month }: { month: string }) {
  const [page, setPage] = useState(1)
  const [sort, setSort] = useState('fixed_rate_pct')
  const [filter, setFilter] = useState('')
  const [order, setOrder] = useState<'asc' | 'desc'>('desc')
  const { data, isLoading } = useQuery({ queryKey: ['se/fixed-variable', month, page, sort, filter, order], queryFn: () => api.get(`/store-expense/fixed-variable?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: '亏损门店' },
  ]

  const sorts = [
    { key: 'fixed_rate_pct', label: '固定费用率' },
    { key: 'variable_rate_pct', label: '变动费用率' },
    { key: 'received', label: '实收' },
    { key: 'contribution_after_variable', label: '边际贡献' },
    { key: 'break_even_sales', label: '盈亏平衡额' },
  ]

  return (
    <div className="space-y-4">
      <CollapsibleSection title="固定/变动费用拆分" subtitle="固定费用(租金+宿舍+维修50%) vs 变动费用(人工+水电+佣金+刷卡+维修50%)">
        <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="fixed_rate_pct"
          defaultOrder="desc"
          columns={[
            { key: 'sales_store_name', label: '门店' },
            { key: 'received', label: '实收', align: 'right', render: (r) => formatCurrency(r.received) },
            { key: 'fixed_expense', label: '固定费用', align: 'right', render: (r) => formatCurrency(r.fixed_expense) },
            { key: 'fixed_rate_pct', label: '固定费用率', align: 'right', render: (r) => formatPercent(r.fixed_rate_pct) },
            { key: 'variable_expense', label: '变动费用', align: 'right', render: (r) => formatCurrency(r.variable_expense) },
            { key: 'variable_rate_pct', label: '变动费用率', align: 'right', render: (r) => formatPercent(r.variable_rate_pct) },
            { key: 'contribution_after_variable', label: '边际贡献(扣变动)', align: 'right', render: (r) => <span className={parseFloat(r.contribution_after_variable) < 0 ? 'text-red-600 font-medium' : 'text-green-600'}>{formatCurrency(r.contribution_after_variable)}</span> },
            { key: 'break_even_sales', label: '盈亏平衡销售额', align: 'right', render: (r) => formatCurrency(r.break_even_sales) },
          ]}
        />
      </CollapsibleSection>
    </div>
  )
}
