import { useQuery } from '@tanstack/react-query'
import { useNavigate } from 'react-router-dom'
import api from '@/lib/api'
import { cn } from '@/lib/utils'
import { AlertTriangle, Activity, CheckCircle, XCircle } from 'lucide-react'

export function StatusBanner({ month }: { month?: string }) {
  const navigate = useNavigate()
  const m = month || '2026-04'

  const { data: riskData } = useQuery({
    queryKey: ['stores/risk', m],
    queryFn: () => api.get('/stores/risk', { params: { month: m } }),
    staleTime: 5 * 60 * 1000,
  })

  const { data: alertsData } = useQuery({
    queryKey: ['sa-alerts', m],
    queryFn: () => api.get('/situational-awareness/alerts', { params: { month: m } }),
    staleTime: 5 * 60 * 1000,
  })

  const { data: loopHealth } = useQuery({
    queryKey: ['loop-health'],
    queryFn: () => api.get('/tasks/loop-health'),
    staleTime: 5 * 60 * 1000,
  })

  const riskRows = (riskData as any)?.data || []
  const alertSummary = (alertsData as any)?.data
  const lh = (loopHealth as any)?.data

  const red = riskRows.filter((r: any) => r.risk_level === '红色').length
  const yellow = riskRows.filter((r: any) => r.risk_level === '黄色').length
  const green = riskRows.filter((r: any) => r.risk_level === '绿色').length
  const total = riskRows.length || 1

  const alertRed = alertSummary?.red || 0
  const alertOrange = alertSummary?.orange || 0
  const alertTotal = alertSummary?.total || 0

  const loopScore = lh ? (
    (parseFloat(lh.task_generation_rate) +
    parseFloat(lh.store_execution_rate) +
    parseFloat(lh.weekly_check_rate) +
    parseFloat(lh.monthly_review_rate) +
    parseFloat(lh.practice_promotion_rate)) / 5
  ) : null

  return (
    <div className="flex items-center gap-4 rounded-lg border bg-card px-4 py-2 text-sm shadow-sm">
      {/* 门店风险分布 */}
      <div className="flex items-center gap-2" title="数据来源: /stores/risk · 按风险等级统计门店数量(红/黄/绿)">
        <Activity size={16} className="text-muted-foreground" />
        <span className="text-xs font-medium text-muted-foreground">门店风险</span>
        <button
          onClick={() => navigate('/')}
          title="红色: 存在严重问题需紧急整改"
          className="flex items-center gap-1 rounded px-1.5 py-0.5 transition-colors hover:bg-muted"
        >
          <span className="h-2.5 w-2.5 rounded-full bg-red-500" />
          <span className="font-bold text-red-600">{red}</span>
        </button>
        <button
          onClick={() => navigate('/')}
          title="黄色: 存在风险需关注"
          className="flex items-center gap-1 rounded px-1.5 py-0.5 transition-colors hover:bg-muted"
        >
          <span className="h-2.5 w-2.5 rounded-full bg-yellow-500" />
          <span className="font-bold text-yellow-600">{yellow}</span>
        </button>
        <button
          onClick={() => navigate('/')}
          title="绿色: 经营正常"
          className="flex items-center gap-1 rounded px-1.5 py-0.5 transition-colors hover:bg-muted"
        >
          <span className="h-2.5 w-2.5 rounded-full bg-green-500" />
          <span className="font-bold text-green-600">{green}</span>
        </button>
      </div>

      <div className="h-4 w-px bg-border" />

      {/* 风险分布条 */}
      <div className="hidden h-2 w-32 overflow-hidden rounded-full md:flex" title={`红${red} 黄${yellow} 绿${green} / 共${total}家`}>
        <div className="bg-red-500" style={{ width: `${red / total * 100}%` }} />
        <div className="bg-yellow-500" style={{ width: `${yellow / total * 100}%` }} />
        <div className="bg-green-500" style={{ width: `${green / total * 100}%` }} />
      </div>

      <div className="h-4 w-px bg-border" />

      {/* 预警 */}
      <button
        onClick={() => navigate('/situational-awareness')}
        title="数据来源: /situational-awareness/alerts · 营收异动·成本异动·人力异动·平台依赖·任务逾期，每类最多10条"
        className={cn(
          'flex items-center gap-1.5 rounded px-2 py-0.5 transition-colors hover:bg-muted',
          alertRed > 0 && 'bg-red-50'
        )}
      >
        <AlertTriangle size={16} className={alertRed > 0 ? 'text-red-600' : alertOrange > 0 ? 'text-orange-600' : 'text-muted-foreground'} />
        <span className="text-xs font-medium text-muted-foreground">预警</span>
        {alertRed > 0 && <span className="rounded bg-red-600 px-1.5 py-0.5 text-xs font-bold text-white" title={`红色 ${alertRed} 条`}>{alertRed}</span>}
        {alertOrange > 0 && <span className="rounded bg-orange-500 px-1.5 py-0.5 text-xs font-bold text-white" title={`橙色 ${alertOrange} 条`}>{alertOrange}</span>}
        {alertRed === 0 && alertOrange === 0 && (
          <span className="flex items-center gap-1 text-xs text-green-600">
            <CheckCircle size={14} />
            正常
          </span>
        )}
      </button>

      {loopScore !== null && (
        <>
          <div className="h-4 w-px bg-border" />
          {/* 闭环健康度 */}
          <button
            onClick={() => navigate('/')}
            title="数据来源: /tasks/loop-health · 任务生成率·店长执行率·区域周检率·月度验收率·经验推广率 五项均值"
            className="flex items-center gap-1.5 rounded px-2 py-0.5 transition-colors hover:bg-muted"
          >
            <span className="text-xs font-medium text-muted-foreground">闭环健康度</span>
            <span className={cn(
              'text-sm font-bold',
              loopScore >= 80 ? 'text-green-600' : loopScore >= 60 ? 'text-yellow-600' : 'text-red-600'
            )}>
              {loopScore.toFixed(1)}%
            </span>
            <div className="h-1.5 w-12 overflow-hidden rounded-full bg-muted">
              <div
                className={cn(
                  'h-full rounded-full',
                  loopScore >= 80 ? 'bg-green-500' : loopScore >= 60 ? 'bg-yellow-500' : 'bg-red-500'
                )}
                style={{ width: `${Math.min(loopScore, 100)}%` }}
              />
            </div>
          </button>
        </>
      )}

      <div className="ml-auto flex items-center gap-2 text-xs text-muted-foreground">
        <span>{m}</span>
        {alertRed > 0 ? (
          <span className="flex items-center gap-1 text-red-600">
            <XCircle size={12} />
            需关注
          </span>
        ) : (
          <span className="flex items-center gap-1 text-green-600">
            <CheckCircle size={12} />
            运行正常
          </span>
        )}
      </div>
    </div>
  )
}
