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, formatNumber } from '@/lib/utils'

const PAGE_SIZE = 20

export function EfficiencyTab({ month }: { month: string }) {
  const [page, setPage] = useState(1)
  const [sort, setSort] = useState('received_per_sqm')
  const [filter, setFilter] = useState('')
  const [order, setOrder] = useState<'asc' | 'desc'>('desc')
  const { data, isLoading } = useQuery({ queryKey: ['se/efficiency', month, page, sort, filter, order], queryFn: () => api.get(`/store-expense/efficiency?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: 'received_per_sqm', label: '坪效' },
    { key: 'wage_rate_pct', label: '人工率' },
    { key: 'received', label: '实收' },
    { key: 'bill_count', label: '账单数' },
    { key: 'avg_ticket_size', 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="received_per_sqm"
          defaultOrder="desc"
          columns={[
            { key: 'sales_store_name', label: '门店' },
            { key: 'received', label: '实收', align: 'right', render: (r) => formatCurrency(r.received) },
            { key: 'area_sqm', label: '面积(㎡)', align: 'right', render: (r) => formatNumber(r.area_sqm) },
            { key: 'received_per_sqm', label: '坪效', align: 'right', render: (r) => <span className={parseFloat(r.received_per_sqm) < 1000 ? 'text-red-600 font-medium' : parseFloat(r.received_per_sqm) > 4000 ? 'text-green-600 font-medium' : ''}>{formatNumber(r.received_per_sqm)}</span> },
            { key: 'wage_expense', label: '人工成本', align: 'right', render: (r) => formatCurrency(r.wage_expense) },
            { key: 'wage_rate_pct', label: '人工成本率', align: 'right', render: (r) => <span className={parseFloat(r.wage_rate_pct) > 35 ? 'text-red-600 font-medium' : ''}>{formatPercent(r.wage_rate_pct)}</span> },
            { key: 'revenue_per_wage', label: '人效(元/元人工)', align: 'right', render: (r) => formatNumber(r.revenue_per_wage) },
            { key: 'bill_count', label: '账单数', align: 'right', render: (r) => formatNumber(r.bill_count) },
            { key: 'avg_ticket_size', label: '客单价', align: 'right', render: (r) => formatCurrency(r.avg_ticket_size) },
            { key: 'efficiency_level', label: '效率等级', render: (r) => <span className={r.efficiency_level === '坪效偏低' || r.efficiency_level === '坪效极低' ? 'text-red-600' : r.efficiency_level === '坪效优秀' ? 'text-green-600' : ''}>{r.efficiency_level}</span> },
            { key: 'suggestion', label: '建议' },
          ]}
        />
      </CollapsibleSection>
    </div>
  )
}
