import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
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 { Tabs } from '@/components/Tabs'
import { formatNumber } from '@/lib/utils'
import { useState } from 'react'

export function AlertManagementPage() {
  const [tab, setTab] = useState('logs')
  const queryClient = useQueryClient()

  const { data: overviewData, isLoading: overviewLoading } = useQuery({
    queryKey: ['alert/overview'],
    queryFn: () => api.get('/alert/overview'),
  })

  const { data: rulesData, isLoading: rulesLoading } = useQuery({
    queryKey: ['alert/rules'],
    queryFn: () => api.get('/alert/rules'),
  })

  const { data: logsData, isLoading: logsLoading } = useQuery({
    queryKey: ['alert/logs'],
    queryFn: () => api.get('/alert/logs', { params: { page_size: 100 } }),
  })

  const handleMutation = useMutation({
    mutationFn: (data: { id: number; handle_status: string; handle_comment?: string }) =>
      api.patch(`/alert/logs/${data.id}`, { handle_status: data.handle_status, handle_comment: data.handle_comment }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['alert/logs'] }),
  })

  const toggleRuleMutation = useMutation({
    mutationFn: (data: { id: number; is_enabled: boolean }) =>
      api.patch(`/alert/rules/${data.id}`, { is_enabled: data.is_enabled }),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['alert/rules'] }),
  })

  const overview = (overviewData as any)?.data || {}
  const rules = (rulesData as any)?.data || []
  const logs = (logsData as any)?.data || []

  const pageLoading = overviewLoading && tab === 'logs'

  if (pageLoading) {
    return <LoadingSpinner text="加载预警数据..." />
  }

  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">预警规则 · 预警日志 · 处理状态</p>
        </div>
      </div>

      <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
        <MetricCard title="近30天预警总数" value={overview.total_alerts || 0} format="number" description="最近30天触发的预警总数" />
        <MetricCard title="红灯预警" value={overview.red_alerts || 0} format="number" description="严重预警数量" status={overview.red_alerts > 0 ? 'bad' : 'good'} />
        <MetricCard title="待处理预警" value={overview.pending_alerts || 0} format="number" description="尚未处理的预警" status={overview.pending_alerts > 0 ? 'warn' : 'good'} />
        <MetricCard title="今日预警" value={overview.today_alerts || 0} format="number" description="今日触发的预警数" />
      </div>

      <Tabs
        tabs={[
          { key: 'logs', label: '预警日志' },
          { key: 'rules', label: '预警规则' },
        ]}
        active={tab}
        onChange={setTab}
      />

      {tab === 'logs' && (
        <CollapsibleSection title={`预警日志 (${logs.length})`} subtitle="按触发时间降序">
          {logsLoading ? <LoadingSpinner text="加载预警日志..." /> : (
            <FilterableTable
              data={logs}
              filterKey="severity"
              filterLabel="全部级别"
              sortOptions={[
                { key: 'triggered_at', label: '触发时间' },
                { key: 'metric_value', label: '指标值' },
                { key: 'severity', label: '级别' },
              ]}
              defaultSort="triggered_at"
              defaultOrder="desc"
              columns={[
                { key: 'triggered_at', label: '触发时间', render: (r) => (r.triggered_at || '').substring(0, 19).replace('T', ' ') },
                { key: 'rule_name', label: '规则名称' },
                { key: 'store_code', label: '门店编码' },
                { key: 'store_name', label: '门店名称' },
                { key: 'metric_value', label: '指标值', align: 'right', render: (r) => Number(r.metric_value || 0).toFixed(2) },
                { key: 'threshold', label: '阈值', align: 'right', render: (r) => Number(r.threshold || 0).toFixed(2) },
                { key: 'severity', label: '级别', align: 'center', render: (r) => {
                  const colors: Record<string, string> = { red: 'bg-red-100 text-red-700', yellow: 'bg-yellow-100 text-yellow-700' }
                  const labels: Record<string, string> = { red: '红灯', yellow: '黄灯' }
                  return <span className={`rounded px-2 py-0.5 text-xs ${colors[r.severity] || ''}`}>{labels[r.severity] || r.severity}</span>
                }},
                { key: 'handle_status', label: '处理状态', align: 'center', render: (r) => {
                  const colors: Record<string, string> = { pending: 'bg-gray-100 text-gray-600', handling: 'bg-blue-100 text-blue-700', resolved: 'bg-green-100 text-green-700', ignored: 'bg-gray-100 text-gray-500' }
                  const labels: Record<string, string> = { pending: '待处理', handling: '处理中', resolved: '已解决', ignored: '已忽略' }
                  return <span className={`rounded px-2 py-0.5 text-xs ${colors[r.handle_status] || ''}`}>{labels[r.handle_status] || r.handle_status}</span>
                }},
                { key: 'actions', label: '操作', align: 'center', render: (r) => (
                  <div className="flex gap-1">
                    {r.handle_status === 'pending' && (
                      <>
                        <button
                          onClick={() => handleMutation.mutate({ id: r.id, handle_status: 'resolved', handle_comment: '已处理' })}
                          className="rounded bg-green-100 px-2 py-0.5 text-xs text-green-700 hover:bg-green-200"
                        >解决</button>
                        <button
                          onClick={() => handleMutation.mutate({ id: r.id, handle_status: 'ignored', handle_comment: '已忽略' })}
                          className="rounded bg-gray-100 px-2 py-0.5 text-xs text-gray-600 hover:bg-gray-200"
                        >忽略</button>
                      </>
                    )}
                  </div>
                )},
              ]}
            />
          )}
        </CollapsibleSection>
      )}

      {tab === 'rules' && (
        <CollapsibleSection title={`预警规则 (${rules.length})`} subtitle="规则配置与启停">
          {rulesLoading ? <LoadingSpinner text="加载预警规则..." /> : (
            <FilterableTable
              data={rules}
              sortOptions={[
                { key: 'rule_name', label: '规则名称' },
                { key: 'metric', label: '指标' },
                { key: 'threshold', label: '阈值' },
              ]}
              defaultSort="rule_name"
              defaultOrder="asc"
              columns={[
                { key: 'rule_name', label: '规则名称' },
                { key: 'description', label: '描述' },
                { key: 'metric', label: '监控指标' },
                { key: 'operator', label: '比较符', align: 'center' },
                { key: 'threshold', label: '阈值', align: 'right' },
                { key: 'severity', label: '级别', align: 'center', render: (r) => {
                  const colors: Record<string, string> = { red: 'bg-red-100 text-red-700', yellow: 'bg-yellow-100 text-yellow-700' }
                  const labels: Record<string, string> = { red: '红灯', yellow: '黄灯' }
                  return <span className={`rounded px-2 py-0.5 text-xs ${colors[r.severity] || ''}`}>{labels[r.severity] || r.severity}</span>
                }},
                { key: 'check_interval', label: '检查频率', align: 'center' },
                { key: 'push_targets', label: '推送对象' },
                { key: 'is_enabled', label: '状态', align: 'center', render: (r) => (
                  <button
                    onClick={() => toggleRuleMutation.mutate({ id: r.id, is_enabled: !r.is_enabled })}
                    className={`rounded px-2 py-0.5 text-xs ${r.is_enabled ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'}`}
                  >
                    {r.is_enabled ? '启用中' : '已停用'}
                  </button>
                )},
              ]}
            />
          )}
        </CollapsibleSection>
      )}
    </div>
  )
}
