import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import api from '@/lib/api'
import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer, BarChart, Bar, CartesianGrid, XAxis, YAxis, Legend } from 'recharts'
import { FilterableTable } from '@/components/FilterableTable'
import { Badge } from '@/components/Badge'
import { MetricCard } from '@/components/MetricCard'
import { useState } from 'react'
import { formatCurrency, formatNumber, formatPercent } from '@/lib/utils'
import { MonthPicker } from '@/components/MonthPicker'

const REVIEW_COLORS = { '达标': '#22c55e', '改善中': '#eab308', '未改善': '#ef4444' }

type ReviewTab = 'summary' | 'grade-change' | 'completion' | 'activity' | 'sku' | 'practice' | 'effectiveness'

const REVIEW_TABS: { key: ReviewTab; label: string }[] = [
  { key: 'summary', label: '验收汇总' },
  { key: 'grade-change', label: '升降级面板' },
  { key: 'completion', label: '任务完成率' },
  { key: 'activity', label: '活动清单' },
  { key: 'sku', label: 'SKU治理' },
  { key: 'practice', label: '经验标准化' },
  { key: 'effectiveness', label: '复盘优化' },
]

export function MonthlyReviewPage() {
  const [month, setMonth] = useState('2026-04')
  const [tab, setTab] = useState<ReviewTab>('summary')

  const { data } = useQuery({
    queryKey: ['monthly-review', month],
    queryFn: () => api.get('/tasks/monthly-review', { params: { month } }),
  })

  const { data: gradeData } = useQuery({
    queryKey: ['grade-change', month],
    queryFn: () => api.get('/tasks/grade-change', { params: { month } }),
    enabled: tab === 'grade-change',
  })

  const { data: completionData } = useQuery({
    queryKey: ['monthly-review/completion', month],
    queryFn: () => api.get('/tasks/monthly-review/completion', { params: { month } }),
    enabled: tab === 'completion',
  })

  const { data: activityData } = useQuery({
    queryKey: ['monthly-review/activity-list', month],
    queryFn: () => api.get('/tasks/monthly-review/activity-list', { params: { month } }),
    enabled: tab === 'activity',
  })

  const { data: skuGovData } = useQuery({
    queryKey: ['monthly-review/sku-governance', month],
    queryFn: () => api.get('/tasks/monthly-review/sku-governance', { params: { month } }),
    enabled: tab === 'sku',
  })

  const { data: effectivenessData } = useQuery({
    queryKey: ['monthly-review/indicator-effectiveness', month],
    queryFn: () => api.get('/tasks/monthly-review/indicator-effectiveness', { params: { month } }),
    enabled: tab === 'effectiveness',
  })

  const rd = (data as any)?.data
  const summary = rd?.summary || { total: 0, passed: 0, improving: 0, failed: 0 }
  const details = rd?.details || []

  const gradeRows = (gradeData as any)?.data || []
  const completionRows = (completionData as any)?.data || []
  const activityRows = (activityData as any)?.data || []
  const skuGov = (skuGovData as any)?.data
  const effectivenessRows = (effectivenessData as any)?.data || []

  const pieData = [
    { name: '达标', value: summary.passed },
    { name: '改善中', value: summary.improving },
    { name: '未改善', value: summary.failed },
  ].filter((d) => d.value > 0)

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="text-xl font-bold">月度验收与复盘</h1>
        <MonthPicker month={month} onChange={setMonth} />
      </div>

      {/* Tab bar */}
      <div className="flex gap-1 border-b">
        {REVIEW_TABS.map(t => (
          <button key={t.key} onClick={() => setTab(t.key)} className={`rounded-t-md border-b-2 px-3 py-2 text-sm font-medium transition-colors ${tab === t.key ? 'border-primary text-primary' : 'border-transparent text-muted-foreground hover:text-foreground'}`}>
            {t.label}
          </button>
        ))}
      </div>

      {/* 验收汇总 Tab */}
      {tab === 'summary' && (
        <>
          <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
            <MetricCard title="总任务数" value={summary.total} />
            <MetricCard title="达标" value={summary.passed} />
            <MetricCard title="改善中" value={summary.improving} />
            <MetricCard title="未改善" value={summary.failed} />
          </div>
          <div className="grid gap-4 lg:grid-cols-2">
            <div className="rounded-lg border bg-card p-4">
              <h2 className="mb-3 text-sm font-bold">验收结果分布</h2>
              {pieData.length > 0 ? (
                <ResponsiveContainer width="100%" height={250}>
                  <PieChart>
                    <Pie data={pieData} cx="50%" cy="50%" outerRadius={70} dataKey="value"
                      labelLine={false} label={({ name, value }: any) => <tspan fontSize={11}>{`${name}: ${value}`}</tspan>}>
                      {pieData.map((d) => <Cell key={d.name} fill={REVIEW_COLORS[d.name as keyof typeof REVIEW_COLORS]} />)}
                    </Pie>
                    <Tooltip formatter={(v: any) => [v, '任务数']} />
                    <Legend wrapperStyle={{ fontSize: 10 }} />
                  </PieChart>
                </ResponsiveContainer>
              ) : <div className="py-20 text-center text-muted-foreground">暂无验收数据</div>}
            </div>
          </div>
          <div className="rounded-lg border bg-card p-4">
            <h2 className="mb-3 text-sm font-bold">验收明细</h2>
            <FilterableTable
              data={details}
              sortOptions={[
                { key: 'store_name', label: '门店' },
                { key: 'problem_indicator', label: '问题指标' },
                { key: 'baseline_value', label: '基线' },
                { key: 'target_value', label: '目标' },
                { key: 'actual_value', label: '实际' },
              ]}
              defaultSort="store_name"
              defaultOrder="asc"
              filterKey="review_result"
              filterLabel="全部结果"
              columns={[
                { key: 'store_name', label: '门店' },
                { key: 'problem_indicator', label: '问题指标' },
                { key: 'baseline_value', label: '基线', align: 'right' },
                { key: 'target_value', label: '目标', align: 'right' },
                { key: 'actual_value', label: '实际', align: 'right' },
                { key: 'review_result', label: '结果', render: (r) => <Badge type="review" text={r.review_result} /> },
              ]}
            />
          </div>
        </>
      )}

      {/* 升降级面板 Tab */}
      {tab === 'grade-change' && (
        <div className="rounded-lg border bg-card p-4">
          <h2 className="mb-3 text-sm font-bold">门店P0/P1/P2升降级面板</h2>
          {gradeRows.length === 0 ? <p className="text-sm text-muted-foreground">暂无升降级数据</p> : (
            <FilterableTable
              data={gradeRows}
              sortOptions={[
                { key: 'change_month', label: '月份' },
                { key: 'store_name', label: '门店' },
                { key: 'change_type', label: '变化' },
              ]}
              defaultSort="change_month"
              defaultOrder="desc"
              filterKey="change_type"
              filterLabel="全部变化"
              columns={[
                { key: 'change_month', label: '月份', render: (r) => r.change_month?.substring(0, 7) },
                { key: 'store_name', label: '门店' },
                { key: 'old_priority', label: '原级别', render: (r) => <Badge type="priority" text={r.old_priority} /> },
                { key: 'new_priority', label: '新级别', render: (r) => <Badge type="priority" text={r.new_priority} /> },
                { key: 'change_type', label: '变化', render: (r) => {
                  const isUpgrade = ['P0→P1', 'P1→P2', 'P0→P2'].includes(r.change_type)
                  return <span className={isUpgrade ? 'text-green-600' : 'text-red-600'}>{isUpgrade ? '↑ 升级' : '↓ 降级'}</span>
                } },
                { key: 'reason', label: '原因', render: (r) => <span className="text-xs">{r.reason}</span> },
              ]}
            />
          )}
        </div>
      )}

      {/* 任务完成率 Tab */}
      {tab === 'completion' && (
        <div className="rounded-lg border bg-card p-4">
          <h2 className="mb-3 text-sm font-bold">任务完成率（按优先级汇总）</h2>
          {completionRows.length === 0 ? <p className="text-sm text-muted-foreground">暂无数据</p> : (
            <>
              <div className="mb-4 grid grid-cols-2 gap-3 md:grid-cols-4">
                {completionRows.map((c: any) => (
                  <div key={c.priority} className="rounded-md border p-3">
                    <p className="text-xs text-muted-foreground">{c.priority}</p>
                    <p className="mt-1 text-xl font-bold">{c.completion_rate}%</p>
                    <p className="text-xs text-muted-foreground">{c.completed}/{c.total} 已完成</p>
                    <div className="mt-2 h-1.5 overflow-hidden rounded-full bg-muted">
                      <div className={`h-full rounded-full ${Number(c.completion_rate) >= 80 ? 'bg-green-500' : Number(c.completion_rate) >= 60 ? 'bg-yellow-500' : 'bg-red-500'}`} style={{ width: `${Math.min(Number(c.completion_rate), 100)}%` }} />
                    </div>
                  </div>
                ))}
              </div>
              <FilterableTable
                data={completionRows}
                sortOptions={[
                  { key: 'priority', label: '优先级' },
                  { key: 'completion_rate', label: '完成率' },
                ]}
                defaultSort="priority"
                defaultOrder="asc"
                columns={[
                  { key: 'priority', label: '优先级', render: (r) => <Badge type="priority" text={r.priority} /> },
                  { key: 'total', label: '总数', align: 'right' },
                  { key: 'completed', label: '已完成', align: 'right' },
                  { key: 'passed', label: '达标', align: 'right', render: (r) => <span className="text-green-600">{r.passed}</span> },
                  { key: 'improving', label: '改善中', align: 'right', render: (r) => <span className="text-yellow-600">{r.improving}</span> },
                  { key: 'failed', label: '未改善', align: 'right', render: (r) => <span className="text-red-600">{r.failed}</span> },
                  { key: 'completion_rate', label: '完成率', align: 'right', render: (r) => `${r.completion_rate}%` },
                ]}
              />
            </>
          )}
        </div>
      )}

      {/* 活动清单 Tab */}
      {tab === 'activity' && (
        <div className="rounded-lg border bg-card p-4">
          <h2 className="mb-3 text-sm font-bold">平台活动停/改/留清单</h2>
          <p className="mb-3 text-xs text-muted-foreground">按活动贡献毛利排序，建议保留高毛利活动、停改低毛利活动</p>
          {activityRows.length === 0 ? <p className="text-sm text-muted-foreground">暂无数据</p> : (
            <FilterableTable
              data={activityRows}
              sortOptions={[
                { key: 'net_contribution', label: '净贡献' },
                { key: 'received', label: '实收' },
                { key: 'discount_cost_rate', label: '优惠成本率' },
                { key: 'bill_count', label: '账单数' },
              ]}
              defaultSort="net_contribution"
              defaultOrder="desc"
              columns={[
                { key: 'marketing_plan', label: '活动方案' },
                { key: 'bill_count', label: '账单数', align: 'right', render: (r) => formatNumber(r.bill_count) },
                { key: 'consumption', label: '消费额', align: 'right', render: (r) => formatCurrency(r.consumption) },
                { key: 'discounts', label: '优惠额', align: 'right', render: (r) => formatCurrency(r.discounts) },
                { key: 'received', label: '实收', align: 'right', render: (r) => formatCurrency(r.received) },
                { key: 'discount_cost_rate', label: '优惠成本率', align: 'right', render: (r) => formatPercent(r.discount_cost_rate) },
                { key: 'net_contribution', label: '净贡献', align: 'right', render: (r) => formatCurrency(r.net_contribution) },
                { key: 'action', label: '建议', render: (r) => {
                  const rate = Number(r.discount_cost_rate || 0)
                  const net = Number(r.net_contribution || 0)
                  if (net > 0 && rate < 15) return <span className="text-green-600">留</span>
                  if (rate > 30) return <span className="text-red-600">停</span>
                  return <span className="text-yellow-600">改</span>
                } },
              ]}
            />
          )}
        </div>
      )}

      {/* SKU治理 Tab */}
      {tab === 'sku' && (
        <div className="space-y-4">
          {skuGov?.summary && (
            <div className="grid grid-cols-3 gap-3">
              {skuGov.summary.map((s: any) => (
                <div key={s.abc_class} className="rounded-lg border bg-card p-4">
                  <p className="text-xs text-muted-foreground">{s.abc_class}</p>
                  <p className="mt-1 text-2xl font-bold">{s.sku_count}</p>
                  <p className="text-xs text-muted-foreground">营收占比: {s.total_revenue_share}%</p>
                </div>
              ))}
            </div>
          )}
          <div className="rounded-lg border bg-card p-4">
            <h2 className="mb-3 text-sm font-bold">长尾SKU治理清单 (C类)</h2>
            {skuGov?.longtail?.length > 0 ? (
              <FilterableTable
                data={skuGov.longtail}
                sortOptions={[
                  { key: 'received_amount', label: '实收' },
                  { key: 'bill_count', label: '账单数' },
                  { key: 'revenue_share_pct', label: '营收占比' },
                ]}
                defaultSort="received_amount"
                defaultOrder="desc"
                columns={[
                  { key: 'dish_name', label: '菜品名' },
                  { key: 'category_level1', label: '一级分类' },
                  { key: 'bill_count', label: '账单数', align: 'right', render: (r) => formatNumber(r.bill_count) },
                  { key: 'received_amount', label: '实收', align: 'right', render: (r) => formatCurrency(r.received_amount) },
                  { key: 'revenue_share_pct', label: '营收占比', align: 'right', render: (r) => `${Number(r.revenue_share_pct).toFixed(2)}%` },
                ]}
              />
            ) : <p className="text-sm text-muted-foreground">暂无长尾SKU数据</p>}
          </div>
        </div>
      )}

      {/* 经验标准化 Tab */}
      {tab === 'practice' && (
        <div className="rounded-lg border bg-card p-4">
          <h2 className="mb-3 text-sm font-bold">经验标准化</h2>
          <p className="text-sm text-muted-foreground mb-3">达标门店的有效经验可标准化推广</p>
          <PracticeSection />
        </div>
      )}

      {/* 复盘优化 Tab */}
      {tab === 'effectiveness' && (
        <div className="rounded-lg border bg-card p-4">
          <h2 className="mb-3 text-sm font-bold">指标有效性评价</h2>
          <p className="mb-3 text-xs text-muted-foreground">评估上月哪些指标真正驱动了改善，哪些没有区分力</p>
          {effectivenessRows.length === 0 ? <p className="text-sm text-muted-foreground">暂无数据</p> : (
            <FilterableTable
              data={effectivenessRows}
              sortOptions={[
                { key: 'pass_rate', label: '达标率' },
                { key: 'task_count', label: '任务数' },
                { key: 'problem_indicator', label: '指标' },
              ]}
              defaultSort="pass_rate"
              defaultOrder="desc"
              columns={[
                { key: 'problem_indicator', label: '指标' },
                { key: 'task_count', label: '任务数', align: 'right' },
                { key: 'passed', label: '达标', align: 'right', render: (r) => <span className="text-green-600">{r.passed}</span> },
                { key: 'improving', label: '改善中', align: 'right', render: (r) => <span className="text-yellow-600">{r.improving}</span> },
                { key: 'failed', label: '未改善', align: 'right', render: (r) => <span className="text-red-600">{r.failed}</span> },
                { key: 'pass_rate', label: '达标率', align: 'right', render: (r) => {
                  const v = Number(r.pass_rate || 0)
                  return <span className={v >= 50 ? 'text-green-600' : v >= 30 ? 'text-yellow-600' : 'text-red-600'}>{v}%</span>
                } },
                { key: 'assessment', label: '评价', render: (r) => {
                  const v = Number(r.pass_rate || 0)
                  if (v >= 50) return <Badge type="review" text="有效" />
                  if (v >= 30) return <Badge type="review" text="待观察" />
                  return <Badge type="review" text="低效" />
                } },
              ]}
            />
          )}
        </div>
      )}
    </div>
  )
}

function PracticeSection() {
  const queryClient = useQueryClient()
  const [showForm, setShowForm] = useState(false)
  const [form, setForm] = useState({ practice_module: '', benchmark_store_name: '', key_actions: '', success_metrics: '' })

  const { data } = useQuery({
    queryKey: ['practices'],
    queryFn: () => api.get('/tasks/practices'),
  })

  const practices = (data as any)?.data || []

  const createMutation = useMutation({
    mutationFn: (data: any) => api.post('/tasks/practices', data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['practices'] })
      setShowForm(false)
      setForm({ practice_module: '', benchmark_store_name: '', key_actions: '', success_metrics: '' })
    },
  })

  return (
    <div className="space-y-3">
      <button onClick={() => setShowForm(!showForm)} className="rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground">
        {showForm ? '取消' : '+ 新增经验'}
      </button>
      {showForm && (
        <div className="rounded-md border p-3 space-y-2">
          <input placeholder="经验模块（如：收入提升/成本控制/会员运营）" value={form.practice_module} onChange={(e) => setForm({ ...form, practice_module: e.target.value })} className="w-full rounded-md border p-2 text-sm" />
          <input placeholder="标杆门店名称" value={form.benchmark_store_name} onChange={(e) => setForm({ ...form, benchmark_store_name: e.target.value })} className="w-full rounded-md border p-2 text-sm" />
          <textarea placeholder="关键动作描述" value={form.key_actions} onChange={(e) => setForm({ ...form, key_actions: e.target.value })} className="w-full rounded-md border p-2 text-sm" rows={2} />
          <input placeholder="验收指标（如：实收增长15%）" value={form.success_metrics} onChange={(e) => setForm({ ...form, success_metrics: e.target.value })} className="w-full rounded-md border p-2 text-sm" />
          <button onClick={() => createMutation.mutate(form)} disabled={!form.practice_module || !form.key_actions || createMutation.isPending} className="rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground disabled:opacity-50">
            {createMutation.isPending ? '提交中...' : '提交'}
          </button>
        </div>
      )}
      {practices.length === 0 ? (
        <p className="text-sm text-muted-foreground">暂无标准化经验</p>
      ) : practices.map((p: any) => (
        <div key={p.id} className="rounded-md border p-3">
          <div className="flex items-center justify-between">
            <span className="text-sm font-medium">{p.practice_module}</span>
            <Badge text={p.status} />
          </div>
          <p className="mt-1 text-xs text-muted-foreground">标杆：{p.benchmark_store_name}</p>
          <p className="mt-1 text-xs">{p.key_actions}</p>
        </div>
      ))}
    </div>
  )
}
