import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from 'react-router-dom'
import api from '@/lib/api'
import { Badge } from '@/components/Badge'
import { FilterableTable } from '@/components/FilterableTable'
import { MetricCard } from '@/components/MetricCard'
import { formatCurrency, formatPercent, riskColor } from '@/lib/utils'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { MonthPicker } from '@/components/MonthPicker'
import { LineChart, Line, ResponsiveContainer, XAxis, YAxis, Tooltip } from 'recharts'
import { useState } from 'react'

export function RegionalPage() {
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const [riskFilter, setRiskFilter] = useState('')
  const [month, setMonth] = useState('2026-04')
  const [weeklyModal, setWeeklyModal] = useState<{ taskId: number; storeName: string } | null>(null)
  const [weeklyText, setWeeklyText] = useState('')

  const { data: riskData, isLoading: riskLoading } = useQuery({
    queryKey: ['stores/risk', month],
    queryFn: () => api.get('/stores/risk', { params: { month } }),
  })

  const { data: weeklyData, isLoading: weeklyLoading } = useQuery({
    queryKey: ['tasks/weekly-check', month],
    queryFn: () => api.get('/tasks/weekly-check', { params: { month } }),
  })

  const { data: priorityData, isLoading: priorityLoading } = useQuery({
    queryKey: ['stores/priority', month],
    queryFn: () => api.get('/stores/priority', { params: { month } }),
  })

  const { data: benchmarkData } = useQuery({
    queryKey: ['benchmark/composite', month],
    queryFn: () => api.get('/benchmark/composite', { params: { month } }),
  })

  const { data: regionData } = useQuery({
    queryKey: ['region/summary', month],
    queryFn: () => api.get('/region/summary', { params: { month } }),
  })

  const riskRows = ((riskData as any)?.data || []).filter((r: any) => !riskFilter || r.risk_level === riskFilter)
  const weeklyRows = (weeklyData as any)?.data || []
  const priorityRows = (priorityData as any)?.data || []
  const benchmarkRows = (benchmarkData as any)?.data || []
  const regionRows = (regionData as any)?.data || []

  const p0p1 = priorityRows.filter((s: any) => s.action_priority?.startsWith('P0') || s.action_priority?.startsWith('P1'))
  const needCheck = weeklyRows.filter((w: any) => parseInt(w.consecutive_no_improve_weeks) >= 2)

  const pageLoading = riskLoading || weeklyLoading || priorityLoading

  const weeklyMutation = useMutation({
    mutationFn: ({ id, text }: { id: number; text: string }) => api.put(`/tasks/${id}/weekly-check`, { weekly_comment: text }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['tasks/weekly-check'] })
      setWeeklyModal(null)
      setWeeklyText('')
    },
  })

  if (pageLoading) {
    return <LoadingSpinner text="加载区域经理工作台..." />
  }

  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>

      {/* 汇总卡片 */}
      <div className="grid grid-cols-2 gap-3 md:grid-cols-3 lg:grid-cols-7">
        <MetricCard title="营业收入" value={regionRows.reduce((s: number, r: any) => s + Number(r.total_consumption || 0), 0)} format="currency" description="各区域消费金额合计" />
        <MetricCard title="优惠" value={regionRows.reduce((s: number, r: any) => s + Number(r.total_discount || 0), 0)} format="currency" description="各类优惠扣减合计" />
        <MetricCard title="实收" value={regionRows.reduce((s: number, r: any) => s + Number(r.total_received || 0), 0)} format="currency" description="扣除优惠后净收入" />
        <MetricCard title="红黄门店数" value={riskRows.filter((r: any) => r.risk_level !== '绿色').length} />
        <MetricCard title="P0+P1门店" value={p0p1.length} />
        <MetricCard title="需到店检查" value={needCheck.length} />
        <MetricCard title="周检待录入" value={weeklyRows.filter((w: any) => !w.last_check_date).length} />
      </div>

      {/* 区域汇总 */}
      {regionRows.length > 0 && (
        <div className="rounded-lg border bg-card p-4">
          <h2 className="mb-3 text-sm font-bold">区域经营汇总</h2>
          <FilterableTable
            data={regionRows}
            sortOptions={[
              { key: 'region', label: '区域' },
              { key: 'total_consumption', label: '营业收入' },
              { key: 'total_discount', label: '优惠' },
              { key: 'total_received', label: '实收' },
              { key: 'avg_bill_value', label: '客单价' },
              { key: 'store_count', label: '门店数' },
            ]}
            defaultSort="total_consumption"
            defaultOrder="desc"
            columns={[
              { key: 'region', label: '区域' },
              { key: 'store_count', label: '门店数', align: 'right' },
              { 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_received', label: '实收合计', align: 'right', render: (r) => formatCurrency(r.total_received) },
              { key: 'avg_bill_value', label: '客单价', align: 'right', render: (r) => formatCurrency(r.avg_bill_value) },
              { key: 'avg_discount_rate', label: '优惠率', align: 'right', render: (r) => formatPercent(r.avg_discount_rate) },
              { key: 'avg_margin_rate', label: '毛利率', align: 'right', render: (r) => formatPercent(r.avg_margin_rate) },
              { key: 'avg_anomaly_rate', label: '异常率', align: 'right', render: (r) => formatPercent(r.avg_anomaly_rate) },
              { key: 'red_count', label: '红', align: 'center', render: (r) => <span className={r.red_count > 0 ? 'font-bold text-red-600' : ''}>{r.red_count}</span> },
              { key: 'yellow_count', label: '黄', align: 'center', render: (r) => <span className={r.yellow_count > 0 ? 'font-bold text-yellow-600' : ''}>{r.yellow_count}</span> },
              { key: 'green_count', label: '绿', align: 'center', render: (r) => <span className="text-green-600">{r.green_count}</span> },
            ]}
          />
        </div>
      )}

      {/* 风险筛选 */}
      <div className="flex gap-2">
        {['', '红色', '黄色', '绿色'].map((r) => (
          <button
            key={r || 'all'}
            onClick={() => setRiskFilter(r)}
            className={`rounded-md border px-3 py-1.5 text-sm ${riskFilter === r ? 'border-primary bg-primary text-primary-foreground' : ''}`}
          >
            {r || '全部'}
          </button>
        ))}
      </div>

      {/* 门店红黄绿列表 */}
      <div className="rounded-lg border bg-card p-4">
        <h2 className="mb-3 text-sm font-bold">门店风险分级 ({riskRows.length})</h2>
        <FilterableTable
          data={riskRows}
          sortOptions={[
            { key: 'received', label: '实收' },
            { key: 'discount_rate_pct', label: '优惠率' },
            { key: 'theoretical_margin_pct', label: '毛利率' },
            { key: 'anomaly_rate_pct', label: '异常率' },
            { key: 'store_name', label: '门店' },
          ]}
          defaultSort="received"
          defaultOrder="desc"
          filterKey="risk_level"
          filterLabel="全部风险"
          onRowClick={(r) => navigate(`/stores/${r.store_code}`)}
          columns={[
            { key: 'store_name', label: '门店' },
            { key: 'risk_level', label: '风险', render: (r) => <Badge type="risk" text={r.risk_level} /> },
            { key: 'received', label: '实收', align: 'right', render: (r) => formatCurrency(r.received) },
            { key: 'discount_rate_pct', label: '优惠率', align: 'right', render: (r) => formatPercent(r.discount_rate_pct) },
            { key: 'theoretical_margin_pct', label: '毛利率', align: 'right', render: (r) => formatPercent(r.theoretical_margin_pct) },
            { key: 'anomaly_rate_pct', label: '异常率', align: 'right', render: (r) => formatPercent(r.anomaly_rate_pct) },
          ]}
        />
      </div>

      {/* 需到店检查门店 + 周检录入 */}
      {needCheck.length > 0 && (
        <div className="rounded-lg border bg-card p-4">
          <h2 className="mb-3 text-sm font-bold text-red-600">需到店检查门店（连续2周未改善）({needCheck.length})</h2>
          <FilterableTable
            data={needCheck}
            sortOptions={[
              { key: 'consecutive_no_improve_weeks', label: '未改善周数' },
              { key: 'store_name', label: '门店' },
            ]}
            defaultSort="consecutive_no_improve_weeks"
            defaultOrder="desc"
            onRowClick={(r) => navigate(`/tasks/${r.task_id}`)}
            columns={[
              { key: 'store_name', label: '门店' },
              { key: 'problem_indicator', label: '问题指标' },
              { key: 'consecutive_no_improve_weeks', label: '连续未改善周数', align: 'center' },
              { key: 'status', label: '任务状态', render: (r) => <Badge type="status" text={r.status} /> },
              { key: 'action', label: '操作', render: (r) => (
                <button onClick={(e) => { e.stopPropagation(); setWeeklyModal({ taskId: r.task_id, storeName: r.store_name }); setWeeklyText('') }} className="rounded-md border px-2 py-0.5 text-xs hover:bg-muted">录入周检</button>
              ) },
            ]}
          />
        </div>
      )}

      {/* 同类门店基准对比 */}
      {benchmarkRows.length > 0 && (
        <div className="rounded-lg border bg-card p-4">
          <h2 className="mb-3 text-sm font-bold">同类门店基准对比</h2>
          <FilterableTable
            data={benchmarkRows}
            sortOptions={[
              { key: 'benchmark_score', label: '标杆得分' },
              { key: 'received', label: '实收' },
              { key: 'avg_bill_value', label: '客单价' },
              { key: 'discount_rate_pct', label: '优惠率' },
              { key: 'theoretical_margin_pct', label: '毛利率' },
              { key: 'member_bill_share_pct', label: '会员占比' },
            ]}
            defaultSort="benchmark_score"
            defaultOrder="desc"
            onRowClick={(r) => navigate(`/stores/${r.store_code}`)}
            columns={[
              { key: 'store_name', label: '门店' },
              { key: 'benchmark_score', label: '标杆得分', align: 'right', render: (r) => {
                const v = Number(r.benchmark_score || 0)
                return <span className={v >= 80 ? 'text-green-600' : v >= 60 ? 'text-yellow-600' : 'text-red-600'}>{v.toFixed(1)}</span>
              } },
              { key: 'received', label: '实收', align: 'right', render: (r) => formatCurrency(r.received) },
              { key: 'avg_bill_value', label: '客单价', align: 'right', render: (r) => formatCurrency(r.avg_bill_value) },
              { key: 'discount_rate_pct', label: '优惠率', align: 'right', render: (r) => formatPercent(r.discount_rate_pct) },
              { key: 'theoretical_margin_pct', label: '毛利率', align: 'right', render: (r) => formatPercent(r.theoretical_margin_pct) },
              { key: 'member_bill_share_pct', label: '会员占比', align: 'right', render: (r) => formatPercent(r.member_bill_share_pct) },
            ]}
          />
        </div>
      )}

      {/* 周检录入弹窗 */}
      {weeklyModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40" onClick={() => setWeeklyModal(null)}>
          <div className="rounded-lg border bg-card p-4 shadow-lg w-96" onClick={(e) => e.stopPropagation()}>
            <h3 className="mb-2 text-sm font-bold">周检录入 - {weeklyModal.storeName}</h3>
            <textarea
              value={weeklyText}
              onChange={(e) => setWeeklyText(e.target.value)}
              placeholder="录入周度检查评价、指标变化情况、指导意见..."
              className="mb-2 w-full rounded-md border p-2 text-sm"
              rows={4}
            />
            <div className="flex justify-end gap-2">
              <button onClick={() => setWeeklyModal(null)} className="rounded-md border px-3 py-1 text-sm">取消</button>
              <button
                onClick={() => weeklyMutation.mutate({ id: weeklyModal.taskId, text: weeklyText })}
                disabled={!weeklyText || weeklyMutation.isPending}
                className="rounded-md bg-primary px-3 py-1 text-sm text-primary-foreground disabled:opacity-50"
              >
                {weeklyMutation.isPending ? '提交中...' : '提交'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
