import { useQuery } from '@tanstack/react-query'
import api from '@/lib/api'
import { CollapsibleSection } from '@/components/CollapsibleSection'
import { MetricCard } from '@/components/MetricCard'
import { formatCurrency, formatPercent } from '@/lib/utils'
import { ComposedChart, Bar, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts'

interface KPISectionProps {
  month: string
  level: 'hq' | 'region' | 'store'
  storeCode?: string
  defaultOpen?: boolean
}

export function KPISection({ month, level, storeCode, defaultOpen = true }: KPISectionProps) {
  const params: any = { month, level }
  if (level === 'store' && storeCode) params.store_code = storeCode

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

  if (isLoading) {
    return (
      <CollapsibleSection title="KPI达成率" subtitle="收入目标 · 利润目标" defaultOpen={defaultOpen}>
        <p className="py-8 text-center text-sm text-muted-foreground">加载中...</p>
      </CollapsibleSection>
    )
  }

  const d = (data as any)?.data

  if (level === 'region') {
    const rows = Array.isArray(d) ? d : []
    if (rows.length === 0) {
      return (
        <CollapsibleSection title="KPI达成率" subtitle="收入目标 · 利润目标" defaultOpen={defaultOpen}>
          <p className="py-8 text-center text-sm text-muted-foreground">暂无数据</p>
        </CollapsibleSection>
      )
    }

    const chartData = rows.map((r: any) => ({
      name: r.region,
      收入目标: Number(r.revenue_target || 0),
      收入实际: Number(r.actual_revenue || 0),
      利润目标: Number(r.profit_target || 0),
      利润实际: Number(r.actual_profit || 0),
      收入达成率: Number(r.revenue_achievement_pct || 0),
      利润达成率: Number(r.profit_achievement_pct || 0),
    }))

    const totalActualRevenue = rows.reduce((s: number, r: any) => s + Number(r.actual_revenue || 0), 0)
    const totalTargetRevenue = rows.reduce((s: number, r: any) => s + Number(r.revenue_target || 0), 0)
    const totalActualProfit = rows.reduce((s: number, r: any) => s + Number(r.actual_profit || 0), 0)
    const totalTargetProfit = rows.reduce((s: number, r: any) => s + Number(r.profit_target || 0), 0)
    const revAchievement = totalTargetRevenue > 0 ? totalActualRevenue / totalTargetRevenue * 100 : 0
    const profitAchievement = totalTargetProfit > 0 ? totalActualProfit / totalTargetProfit * 100 : 0

    return (
      <CollapsibleSection title="KPI达成率" subtitle="收入目标 · 利润目标 · 各区域对比" defaultOpen={defaultOpen}>
        <div className="mb-4 grid grid-cols-2 gap-3 md:grid-cols-4">
          <MetricCard title="收入达成率" value={revAchievement} format="percent" status={revAchievement >= 100 ? 'good' : revAchievement >= 80 ? 'warn' : 'bad'} description="实际收入 / 目标收入" />
          <MetricCard title="利润达成率" value={profitAchievement} format="percent" status={profitAchievement >= 100 ? 'good' : profitAchievement >= 80 ? 'warn' : 'bad'} description="实际利润 / 目标利润" />
          <MetricCard title="目标收入" value={totalTargetRevenue} format="currency" description="各区域目标合计" />
          <MetricCard title="目标利润" value={totalTargetProfit} format="currency" description="各区域利润目标合计" />
        </div>
        <ResponsiveContainer width="100%" height={300}>
          <ComposedChart 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" domain={[80, 120]} tickFormatter={(v) => `${v}%`} tick={{ fontSize: 10 }} />
            <Tooltip formatter={(v: any, name: any) => name.includes('达成率') ? `${Number(v).toFixed(1)}%` : formatCurrency(v)} />
            <Legend />
            <Bar yAxisId="left" dataKey="收入目标" fill="#eab308" />
            <Bar yAxisId="left" dataKey="收入实际" fill="#22c55e" />
            <Bar yAxisId="left" dataKey="利润目标" fill="#f97316" />
            <Bar yAxisId="left" dataKey="利润实际" fill="#3b82f6" />
            <Line yAxisId="right" type="monotone" dataKey="收入达成率" stroke="#ef4444" strokeWidth={2} dot={{ r: 4 }} />
            <Line yAxisId="right" type="monotone" dataKey="利润达成率" stroke="#a855f7" strokeWidth={2} dot={{ r: 4 }} />
          </ComposedChart>
        </ResponsiveContainer>
      </CollapsibleSection>
    )
  }

  // HQ / Store 单实体模式
  const kpi = d || {}
  const revAchievement = Number(kpi.revenue_achievement_pct || 0)
  const profitAchievement = Number(kpi.profit_achievement_pct || 0)
  const profitMargin = Number(kpi.profit_margin_pct || 0)

  const chartData = [
    { name: '收入', 目标: Number(kpi.revenue_target || 0), 实际: Number(kpi.actual_revenue || 0), 达成率: revAchievement },
    { name: '利润', 目标: Number(kpi.profit_target || 0), 实际: Number(kpi.actual_profit || 0), 达成率: profitAchievement },
  ]

  return (
    <CollapsibleSection title="KPI达成率" subtitle="收入目标 · 利润目标" defaultOpen={defaultOpen}>
      <div className="mb-4 grid grid-cols-2 gap-3 md:grid-cols-4">
        <MetricCard title="收入达成率" value={revAchievement} format="percent" status={revAchievement >= 100 ? 'good' : revAchievement >= 80 ? 'warn' : 'bad'} description="实际收入 / 目标收入" />
        <MetricCard title="利润达成率" value={profitAchievement} format="percent" status={profitAchievement >= 100 ? 'good' : profitAchievement >= 80 ? 'warn' : 'bad'} description="实际利润 / 目标利润" />
        <MetricCard title="目标收入" value={kpi.revenue_target} format="currency" description="月度收入目标" />
        <MetricCard title="利润率" value={profitMargin} format="percent" status={profitMargin >= 10 ? 'good' : profitMargin >= 5 ? 'warn' : 'bad'} description="实际利润 / 实际收入" />
      </div>
      <ResponsiveContainer width="100%" height={250}>
        <ComposedChart data={chartData} margin={{ top: 20, right: 20, bottom: 20, left: 20 }}>
          <CartesianGrid strokeDasharray="3 3" />
          <XAxis dataKey="name" tick={{ fontSize: 12 }} />
          <YAxis yAxisId="left" tickFormatter={(v) => v >= 10000 ? `${(v / 10000).toFixed(0)}万` : v} tick={{ fontSize: 10 }} />
          <YAxis yAxisId="right" orientation="right" domain={[0, 120]} tickFormatter={(v) => `${v}%`} tick={{ fontSize: 10 }} />
          <Tooltip formatter={(v: any, name: any) => name === '达成率' ? `${Number(v).toFixed(1)}%` : formatCurrency(v)} />
          <Legend />
          <Bar yAxisId="left" dataKey="目标" fill="#eab308" />
          <Bar yAxisId="left" dataKey="实际" fill="#22c55e" />
          <Line yAxisId="right" type="monotone" dataKey="达成率" stroke="#ef4444" strokeWidth={2} dot={{ r: 5 }} />
        </ComposedChart>
      </ResponsiveContainer>
    </CollapsibleSection>
  )
}
