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

const SAFETY_COLORS: Record<string, string> = {
  '无法盈利': 'text-red-700 font-bold',
  '未达盈亏平衡': 'text-red-600 font-medium',
  '接近盈亏平衡': 'text-orange-600 font-medium',
  '安全边际较低': 'text-yellow-600',
  '安全边际充足': 'text-green-600',
}

export function BreakEvenTab({ month }: { month: string }) {
  const [page, setPage] = useState(1)
  const [sort, setSort] = useState('safety_margin_pct')
  const [filter, setFilter] = useState('')
  const [order, setOrder] = useState<'asc' | 'desc'>('asc')
  const { data, isLoading } = useQuery({ queryKey: ['se/break-even', month, page, sort, filter, order], queryFn: () => api.get(`/store-expense/break-even?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: 'safety_margin_pct', label: '安全边际率' },
    { key: 'break_even_sales', label: '盈亏平衡额' },
    { key: 'sales_gap', label: '销售缺口' },
    { key: 'food_cost_rate_pct', label: '食材成本率' },
    { key: 'received', label: '实收' },
  ]

  return (
    <div className="space-y-4">
      <CollapsibleSection title="盈亏平衡分析" subtitle="盈亏平衡销售额 = 固定费用 ÷ (1 - 食材成本率)，安全边际 = (实收 - 平衡点) ÷ 平衡点">
        <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="safety_margin_pct"
          defaultOrder="asc"
          columns={[
            { key: 'sales_store_name', label: '门店' },
            { key: 'received', label: '实收', align: 'right', render: (r) => formatCurrency(r.received) },
            { key: 'actual_food_cost', label: '食材成本', align: 'right', render: (r) => formatCurrency(r.actual_food_cost) },
            { key: 'food_cost_rate_pct', label: '食材成本率', align: 'right', render: (r) => formatPercent(r.food_cost_rate_pct) },
            { key: 'operating_expense', label: '营业费用', align: 'right', render: (r) => formatCurrency(r.operating_expense) },
            { key: 'expense_rate_pct', label: '费用率', align: 'right', render: (r) => formatPercent(r.expense_rate_pct) },
            { key: 'break_even_sales', label: '盈亏平衡销售额', align: 'right', render: (r) => formatCurrency(r.break_even_sales) },
            { key: 'sales_gap', label: '销售缺口', align: 'right', render: (r) => <span className={parseFloat(r.sales_gap) < 0 ? 'text-red-600 font-medium' : 'text-green-600'}>{formatCurrency(r.sales_gap)}</span> },
            { key: 'safety_margin_pct', label: '安全边际率', align: 'right', render: (r) => <span className={parseFloat(r.safety_margin_pct) < 0 ? 'text-red-600 font-medium' : ''}>{formatPercent(r.safety_margin_pct)}</span> },
            { key: 'safety_status', label: '安全状态', render: (r) => <span className={SAFETY_COLORS[r.safety_status] || ''}>{r.safety_status}</span> },
          ]}
        />
      </CollapsibleSection>
    </div>
  )
}
