import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import api from '@/lib/api'
import { CollapsibleSection } from '@/components/CollapsibleSection'
import { DataTable } from '@/components/DataTable'
import { Pagination } from '@/components/Pagination'
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() {
  const [page, setPage] = useState(1)
  const [sort, setSort] = useState('safety_margin_pct')
  const [filter, setFilter] = useState('')
  const [order, setOrder] = useState('asc')
  const { data, isLoading } = useQuery({ queryKey: ['se/break-even', page, sort, filter, order], queryFn: () => api.get(`/store-expense/break-even?page=${page}&page_size=${PAGE_SIZE}&sort=${sort}&filter=${filter}&order=${order}`) })

  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 - 食材成本率)，安全边际 = (实收 - 平衡点) ÷ 平衡点">
        <div className="flex gap-2 mb-3 flex-wrap">
          {filters.map(f => (
            <button key={f.key} onClick={() => { setFilter(f.key); setPage(1) }} className={`px-3 py-1 rounded text-xs ${filter === f.key ? 'bg-primary text-primary-foreground' : 'bg-muted'}`}>{f.label}</button>
          ))}
          <span className="mx-2 text-muted-foreground">|</span>
          {sorts.map(s => (
            <button key={s.key} onClick={() => { setSort(s.key); setPage(1) }} className={`px-3 py-1 rounded text-xs ${sort === s.key ? 'bg-primary text-primary-foreground' : 'bg-muted'}`}>按{s.label}</button>
          ))}
          <span className="mx-2 text-muted-foreground">|</span>
          <button onClick={() => { setOrder(order === 'asc' ? 'desc' : 'asc'); setPage(1) }} className="px-3 py-1 rounded text-xs bg-muted">
            {order === 'asc' ? '↑ 升序' : '↓ 降序'}
          </button>
        </div>
        <DataTable
          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> },
          ]}
          data={rows}
        />
        <Pagination page={page} pageSize={meta.pageSize} total={meta.total} onPageChange={setPage} />
      </CollapsibleSection>
    </div>
  )
}
