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 DeliveryTab({ month }: { month: string }) {
  const [page, setPage] = useState(1)
  const [sort, setSort] = useState('commission_to_delivery_sales_pct')
  const [filter, setFilter] = useState('')
  const [order, setOrder] = useState<'asc' | 'desc'>('desc')
  const { data, isLoading } = useQuery({ queryKey: ['se/delivery', month, page, sort, filter, order], queryFn: () => api.get(`/store-expense/delivery-commission?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: 'commission_to_delivery_sales_pct', label: '佣金率' },
    { key: 'delivery_sales_share_pct', label: '外卖占比' },
    { key: 'delivery_received', label: '外卖收入' },
    { key: 'received', label: '实收' },
    { key: 'combined_platform_cost_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="commission_to_delivery_sales_pct"
          defaultOrder="desc"
          columns={[
            { key: 'sales_store_name', label: '门店' },
            { key: 'received', label: '实收', align: 'right', render: (r) => formatCurrency(r.received) },
            { key: 'delivery_received', label: '外卖收入', align: 'right', render: (r) => formatCurrency(r.delivery_received) },
            { key: 'delivery_sales_share_pct', label: '外卖占比', align: 'right', render: (r) => <span className={parseFloat(r.delivery_sales_share_pct) > 40 ? 'text-red-600 font-medium' : parseFloat(r.delivery_sales_share_pct) > 25 ? 'text-orange-600' : ''}>{formatPercent(r.delivery_sales_share_pct)}</span> },
            { key: 'delivery_commission_expense', label: '佣金支出', align: 'right', render: (r) => formatCurrency(r.delivery_commission_expense) },
            { key: 'commission_to_delivery_sales_pct', label: '佣金率', align: 'right', render: (r) => <span className={parseFloat(r.commission_to_delivery_sales_pct) > 25 ? 'text-red-600 font-medium' : ''}>{formatPercent(r.commission_to_delivery_sales_pct)}</span> },
            { key: 'combined_platform_cost_rate_pct', label: '综合平台成本率', align: 'right', render: (r) => formatPercent(r.combined_platform_cost_rate_pct) },
            { key: 'delivery_type', label: '外卖类型' },
            { key: 'suggestion', label: '建议' },
          ]}
        />
      </CollapsibleSection>
    </div>
  )
}
