import { useQuery } from '@tanstack/react-query'
import { useState } from 'react'
import api from '@/lib/api'
import { FilterableTable } from '@/components/FilterableTable'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { CollapsibleSection } from '@/components/CollapsibleSection'
import { MetricCard } from '@/components/MetricCard'
import { KPISection } from '@/components/KPISection'
import { formatCurrency, formatNumber, formatPercent } from '@/lib/utils'
import { MonthPicker } from '@/components/MonthPicker'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts'

export function RegionComparisonPage() {
  const [month, setMonth] = useState('2026-04')

  const { data, isLoading } = useQuery({
    queryKey: ['analytics-enhanced/region/comparison', month],
    queryFn: () => api.get('/analytics-enhanced/region/comparison', { params: { month } }),
  })

  const { data: forecastData, isLoading: forecastLoading } = useQuery({
    queryKey: ['analytics-enhanced/region/kpi-forecast', month],
    queryFn: () => api.get('/analytics-enhanced/region/kpi-forecast', { params: { month } }),
  })

  if (isLoading || forecastLoading) {
    return <LoadingSpinner text="加载区域对比数据..." />
  }

  const rows = (data as any)?.data || []
  const forecastRows = (forecastData as any)?.data || []

  const totalConsumption = rows.reduce((s: number, r: any) => s + Number(r.total_consumption || 0), 0)
  const totalDiscount = rows.reduce((s: number, r: any) => s + Number(r.total_discount || 0), 0)
  const totalRevenue = rows.reduce((s: number, r: any) => s + Number(r.total_revenue || 0), 0)
  const totalStores = rows.reduce((s: number, r: any) => s + Number(r.store_count || 0), 0)
  const avgMargin = rows.length > 0 ? rows.reduce((s: number, r: any) => s + Number(r.avg_margin_pct || 0), 0) / rows.length : 0

  const chartData = rows.map((r: any) => ({
    name: r.region,
    总收入: Number(r.total_revenue || 0),
    店均收入: Number(r.revenue_per_store || 0),
    客单价: Number(r.avg_bill_value || 0),
  }))

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-bold">区域对比排名</h1>
          <p className="mt-0.5 text-xs text-muted-foreground">区域营收 · 费用率 · KPI达成预测 · {month}</p>
        </div>
        <MonthPicker month={month} onChange={setMonth} />
      </div>

      {/* 概览指标 */}
      <CollapsibleSection title="区域总览" subtitle="全区域汇总">
        <div className="grid grid-cols-2 gap-3 md:grid-cols-3 lg:grid-cols-6">
          <MetricCard title="营业收入" value={totalConsumption} format="currency" description="各区域消费金额合计" />
          <MetricCard title="优惠" value={totalDiscount} format="currency" description="各类优惠扣减合计" />
          <MetricCard title="实收" value={totalRevenue} format="currency" description="扣除优惠后净收入" />
          <MetricCard title="区域总数" value={rows.length} format="number" description="有数据的区域数量" />
          <MetricCard title="门店总数" value={totalStores} format="number" description="所有区域门店数" />
          <MetricCard title="平均毛利率" value={avgMargin} format="percent" description="各区域平均理论毛利率" />
        </div>
      </CollapsibleSection>

      {/* KPI达成率 */}
      <KPISection month={month} level="region" />

      {/* 区域收入对比图 */}
      <div className="grid gap-4 lg:grid-cols-2">
        <CollapsibleSection title="区域收入对比" subtitle="各区域总收入与店均收入">
          <ResponsiveContainer width="100%" height={280}>
            <BarChart data={chartData} margin={{ top: 20, right: 20, bottom: 20, left: 20 }}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="name" tick={{ fontSize: 11 }} />
              <YAxis yAxisId="left" tickFormatter={(v) => v >= 10000 ? `${(v / 10000).toFixed(0)}万` : v} tick={{ fontSize: 10 }} />
              <YAxis yAxisId="right" orientation="right" tickFormatter={(v) => v >= 10000 ? `${(v / 10000).toFixed(0)}万` : v} tick={{ fontSize: 10 }} />
              <Tooltip formatter={(v: any, name: any) => formatCurrency(v)} />
              <Legend />
              <Bar yAxisId="left" dataKey="总收入" fill="#3b82f6" />
              <Bar yAxisId="right" dataKey="店均收入" fill="#22c55e" />
            </BarChart>
          </ResponsiveContainer>
        </CollapsibleSection>
      </div>

      {/* 区域对比明细 */}
      <CollapsibleSection title="区域对比明细" subtitle="按总收入降序">
        <FilterableTable
          data={rows}
          filterKey="region"
          filterLabel="全部区域"
          sortOptions={[
            { key: 'total_consumption', label: '营业收入' },
            { key: 'total_discount', label: '优惠' },
            { key: 'total_revenue', label: '实收' },
            { key: 'revenue_per_store', label: '店均收入' },
            { key: 'avg_bill_value', label: '客单价' },
            { key: 'avg_margin_pct', label: '毛利率' },
            { key: 'member_penetration_pct', label: '会员渗透率' },
            { key: 'avg_expense_rate', label: '费用率' },
          ]}
          defaultSort="total_revenue"
          defaultOrder="desc"
          columns={[
            { key: 'region', label: '区域' },
            { key: 'store_count', label: '门店数', align: 'right', render: (r) => formatNumber(r.store_count) },
            { key: 'total_consumption', label: '营业收入', align: 'right', render: (r) => formatCurrency(r.total_consumption) },
            { key: 'total_discount', label: '优惠', align: 'right', render: (r) => formatCurrency(r.total_discount) },
            { key: 'total_revenue', label: '实收', align: 'right', render: (r) => formatCurrency(r.total_revenue) },
            { key: 'revenue_per_store', label: '店均收入', align: 'right', render: (r) => formatCurrency(r.revenue_per_store) },
            { key: 'avg_bill_value', label: '客单价', align: 'right', render: (r) => formatCurrency(r.avg_bill_value) },
            { key: 'bill_count', label: '账单数', align: 'right', render: (r) => formatNumber(r.bill_count) },
            { key: 'avg_margin_pct', label: '毛利率', align: 'right', render: (r) => formatPercent(r.avg_margin_pct) },
            { key: 'member_count', label: '会员数', align: 'right', render: (r) => formatNumber(r.member_count) },
            { key: 'member_penetration_pct', label: '会员渗透率', align: 'right', render: (r) => formatPercent(r.member_penetration_pct) },
            { key: 'avg_expense_rate', label: '费用率', align: 'right', render: (r) => formatPercent(r.avg_expense_rate) },
            { key: 'avg_rent_rate', label: '租金率', align: 'right', render: (r) => formatPercent(r.avg_rent_rate) },
            { key: 'avg_wage_rate', label: '工资率', align: 'right', render: (r) => formatPercent(r.avg_wage_rate) },
          ]}
        />
      </CollapsibleSection>

      {/* KPI达成预测明细 */}
      <CollapsibleSection title="KPI达成预测明细" subtitle="月度目标 vs 实际完成">
        <FilterableTable
          data={forecastRows}
          filterKey="region"
          filterLabel="全部区域"
          sortOptions={[
            { key: 'actual_revenue', label: '已完成' },
            { key: 'target_revenue', label: '目标' },
            { key: 'achievement_pct', label: '达成率' },
          ]}
          defaultSort="actual_revenue"
          defaultOrder="desc"
          columns={[
            { key: 'region', label: '区域' },
            { key: 'target_revenue', label: '月度目标', align: 'right', render: (r) => formatCurrency(r.target_revenue) },
            { key: 'actual_revenue', label: '已完成收入', align: 'right', render: (r) => formatCurrency(r.actual_revenue) },
            { key: 'actual_bills', label: '已完成账单', align: 'right', render: (r) => formatNumber(r.actual_bills) },
            { key: 'avg_daily_revenue', label: '日均收入', align: 'right', render: (r) => formatCurrency(r.avg_daily_revenue) },
            { key: 'forecast_revenue', label: '外推预测', align: 'right', render: (r) => formatCurrency(r.forecast_revenue) },
            { key: 'achievement_pct', label: '收入达成率', align: 'right', render: (r) => {
              const v = Number(r.achievement_pct || 0)
              return <span className={v >= 100 ? 'font-medium text-green-600' : v >= 80 ? 'text-yellow-600' : 'font-medium text-red-600'}>{v.toFixed(1)}%</span>
            }},
            { key: 'bill_achievement_pct', label: '账单达成率', align: 'right', render: (r) => {
              const v = Number(r.bill_achievement_pct || 0)
              return <span className={v >= 100 ? 'font-medium text-green-600' : v >= 80 ? 'text-yellow-600' : 'font-medium text-red-600'}>{v.toFixed(1)}%</span>
            }},
          ]}
        />
      </CollapsibleSection>
    </div>
  )
}
