import * as React from 'react'
import type { SituationUpdate, ConflictEvent } from '@/data/mockData'
import { History, RefreshCw } from 'lucide-react'
import { fetchAndSetSituation } from '@/store/situationStore'

interface EventTimelinePanelProps {
  updates: SituationUpdate[]
  conflictEvents?: ConflictEvent[]
  className?: string
}

const CAT_LABELS: Record<string, string> = {
  deployment: '部署',
  alert: '警报',
  intel: '情报',
  diplomatic: '外交',
  other: '其他',
}
function formatTime(iso: string): string {
  const d = new Date(iso)
  return d.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false })
}

type TimelineItem = {
  id: string
  summary: string
  timestamp: string
  source: 'gdelt' | 'rss'
  category?: string
  severity?: string
}

export function EventTimelinePanel({ updates = [], conflictEvents = [], className = '' }: EventTimelinePanelProps) {
  const [refreshing, setRefreshing] = React.useState(false)
  const handleRefresh = React.useCallback(async () => {
    setRefreshing(true)
    await fetchAndSetSituation().finally(() => setRefreshing(false))
  }, [])
  // 合并 GDELT + RSS，按时间倒序（最新在前）
  const merged: TimelineItem[] = [
    ...(conflictEvents || []).map((e) => ({
      id: e.event_id,
      summary: e.title,
      timestamp: e.event_time,
      source: 'gdelt' as const,
      category: 'alert',
      severity: e.impact_score >= 7 ? 'high' : e.impact_score >= 4 ? 'medium' : 'low',
    })),
    ...(updates || []).map((u) => ({
      id: u.id,
      summary: u.summary,
      timestamp: u.timestamp,
      source: 'rss' as const,
      category: u.category,
      severity: u.severity,
    })),
  ]
    .sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
    .slice(0, 8)

  return (
    <div className={`flex min-w-0 max-w-[280px] shrink flex-col overflow-hidden rounded border border-military-border bg-military-panel/80 ${className}`}>
      <div className="flex shrink-0 items-center justify-between border-b border-military-border px-3 py-1.5">
        <span className="flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wider text-military-text-secondary">
          <History className="h-3.5 w-3.5 shrink-0 text-military-accent" />
          事件脉络
        </span>
        <button
          type="button"
          onClick={handleRefresh}
          disabled={refreshing}
          className="flex items-center gap-1 rounded p-0.5 text-[8px] text-military-text-secondary/80 hover:bg-military-border/30 hover:text-cyan-400 disabled:opacity-50"
          title="刷新"
        >
          <RefreshCw className={`h-3 w-3 ${refreshing ? 'animate-spin' : ''}`} />
          刷新
        </button>
      </div>
      <div className="min-h-0 max-h-[140px] flex-1 overflow-y-auto overflow-x-hidden px-2 py-1">
        {merged.length === 0 ? (
          <p className="py-4 text-center text-[11px] text-military-text-secondary">暂无事件</p>
        ) : (
          <ul className="space-y-2">
            {merged.map((item) => (
              <li key={item.id} className="flex gap-2 border-b border-military-border/50 pb-2 last:border-0 last:pb-0">
                <span className="shrink-0 pt-0.5">
                  <span className={`inline-block h-1.5 w-1.5 rounded-full ${item.source === 'gdelt' ? 'bg-cyan-500' : 'bg-amber-500'}`} />
                </span>
                <div className="min-w-0 flex-1 text-right">
                  <p className="text-[11px] leading-tight text-military-text-primary line-clamp-2">{item.summary}</p>
                  <span className="mt-0.5 flex items-center justify-end gap-1 text-[9px] text-military-text-secondary">
                    {formatTime(item.timestamp)}
                    <span className="text-military-text-secondary/60">
                      {item.source === 'gdelt' ? 'GDELT' : CAT_LABELS[item.category ?? ''] ?? '新闻'}
                    </span>
                  </span>
                </div>
              </li>
            ))}
          </ul>
        )}
      </div>
    </div>
  )
}
