'use client'

/**
 * IncidentCard - Phase 7 事件卡片
 * ================================
 *
 * Nothing.tech 視覺規範:
 * - 純白底色 (bg-white)
 * - 極細淺灰邊框 (border border-gray-200)
 * - 無圓角或微圓角 (rounded-sm)
 * - 嚴禁陰影 (shadow-none)
 *
 * 統帥鐵律: 禁止假數據！所有資料必須來自真實 API
 */

import { useTranslations } from 'next-intl'
import { cn } from '@/lib/utils'
import type { IncidentResponse } from '@/lib/api-client'
import { AlertTriangle, Clock, Server, ChevronRight } from 'lucide-react'

// =============================================================================
// Severity Config
// =============================================================================

const SEVERITY_CONFIG = {
  P0: {
    label: 'P0',
    color: 'text-red-600',
    bgColor: 'bg-red-50',
    borderColor: 'border-red-200',
    dotColor: 'bg-red-500',
  },
  P1: {
    label: 'P1',
    color: 'text-orange-600',
    bgColor: 'bg-orange-50',
    borderColor: 'border-orange-200',
    dotColor: 'bg-orange-500',
  },
  P2: {
    label: 'P2',
    color: 'text-amber-600',
    bgColor: 'bg-amber-50',
    borderColor: 'border-amber-200',
    dotColor: 'bg-amber-500',
  },
  P3: {
    label: 'P3',
    color: 'text-gray-600',
    bgColor: 'bg-gray-50',
    borderColor: 'border-gray-200',
    dotColor: 'bg-gray-400',
  },
} as const

const STATUS_CONFIG = {
  investigating: {
    label: 'investigating',
    color: 'text-blue-600',
    bgColor: 'bg-blue-50',
  },
  mitigating: {
    label: 'mitigating',
    color: 'text-purple-600',
    bgColor: 'bg-purple-50',
  },
  resolved: {
    label: 'resolved',
    color: 'text-green-600',
    bgColor: 'bg-green-50',
  },
  closed: {
    label: 'closed',
    color: 'text-gray-500',
    bgColor: 'bg-gray-50',
  },
} as const

// =============================================================================
// Component
// =============================================================================

interface IncidentCardProps {
  incident: IncidentResponse
  onClick?: () => void
  className?: string
}

export function IncidentCard({
  incident,
  onClick,
  className,
}: IncidentCardProps) {
  const t = useTranslations('incident')

  const severityConfig = SEVERITY_CONFIG[incident.severity]
  const statusConfig = STATUS_CONFIG[incident.status]

  // 格式化時間
  const createdAt = new Date(incident.created_at)
  const timeAgo = getTimeAgo(createdAt)

  return (
    <div
      onClick={onClick}
      className={cn(
        // Nothing.tech 核心規範
        'bg-white',
        'border border-gray-200',
        'rounded-sm',
        'shadow-none',
        // 互動狀態
        'transition-colors duration-150',
        onClick && 'cursor-pointer hover:bg-gray-50 hover:border-gray-300',
        // 佈局 (p-6 靈魂注入)
        'p-6',
        className
      )}
    >
      {/* Header: ID + Severity Badge */}
      <div className="flex items-start justify-between gap-4 mb-4">
        <div className="flex items-center gap-2 min-w-0">
          {/* Severity Dot */}
          <span
            className={cn(
              'w-2 h-2 rounded-full flex-shrink-0',
              severityConfig.dotColor,
              (incident.severity === 'P0' || incident.severity === 'P1') &&
                'animate-pulse'
            )}
          />
          {/* Incident ID */}
          <span className="font-mono text-sm text-ink truncate">
            {incident.incident_id}
          </span>
        </div>

        {/* Severity Badge (Dot Matrix 靈魂注入) */}
        <span
          className={cn(
            'px-3 py-1 text-sm font-dot-matrix font-bold rounded-sm border',
            severityConfig.bgColor,
            severityConfig.color,
            severityConfig.borderColor
          )}
        >
          {severityConfig.label}
        </span>
      </div>

      {/* Status Badge */}
      <div className="mb-4">
        <span
          className={cn(
            'inline-flex items-center px-2.5 py-1 text-xs font-mono font-medium rounded-sm',
            statusConfig.bgColor,
            statusConfig.color
          )}
        >
          {t(`status.${statusConfig.label}`)}
        </span>
      </div>

      {/* Affected Services */}
      <div className="mb-4">
        <div className="flex items-center gap-1.5 text-xs text-ink-secondary mb-2">
          <Server className="w-3 h-3" />
          <span>{t('affectedServices')}</span>
        </div>
        <div className="flex flex-wrap gap-1.5">
          {incident.affected_services.slice(0, 3).map((service) => (
            <span
              key={service}
              className="px-2 py-1 text-xs font-mono bg-gray-100 text-ink rounded-sm"
            >
              {service}
            </span>
          ))}
          {incident.affected_services.length > 3 && (
            <span className="px-2 py-1 text-xs text-ink-secondary">
              +{incident.affected_services.length - 3}
            </span>
          )}
        </div>
      </div>

      {/* Footer: Stats + Time */}
      <div className="flex items-center justify-between pt-4 border-t border-gray-100">
        <div className="flex items-center gap-4 text-xs text-ink-secondary">
          {/* Signal Count */}
          <span className="flex items-center gap-1.5 font-mono">
            <AlertTriangle className="w-3.5 h-3.5" />
            <span className="font-dot-matrix text-ink">{incident.signal_count}</span> {t('signals')}
          </span>
          {/* Proposal Count */}
          {incident.proposal_count > 0 && (
            <span className="flex items-center gap-1.5 font-mono text-purple-600">
              <span className="font-dot-matrix">{incident.proposal_count}</span> {t('proposals')}
            </span>
          )}
        </div>

        {/* Time + Arrow */}
        <div className="flex items-center gap-1.5 text-xs text-ink-secondary">
          <Clock className="w-3.5 h-3.5" />
          <span className="font-mono">{timeAgo}</span>
          {onClick && <ChevronRight className="w-3.5 h-3.5" />}
        </div>
      </div>
    </div>
  )
}

// =============================================================================
// Grid Container
// =============================================================================

interface IncidentCardGridProps {
  children: React.ReactNode
  className?: string
}

export function IncidentCardGrid({ children, className }: IncidentCardGridProps) {
  return (
    <div
      className={cn(
        'grid grid-cols-1 md:grid-cols-2 gap-3',
        className
      )}
    >
      {children}
    </div>
  )
}

// =============================================================================
// Empty State
// =============================================================================

export function IncidentEmptyState() {
  const t = useTranslations('incident')

  return (
    <div className="flex flex-col items-center justify-center py-12 text-center">
      <div className="w-12 h-12 rounded-full bg-gray-100 flex items-center justify-center mb-4">
        <AlertTriangle className="w-6 h-6 text-gray-400" />
      </div>
      <p className="text-sm text-gray-500 font-medium">
        {t('emptyState')}
      </p>
      <p className="text-xs text-gray-400 mt-1">
        {t('emptyStateDescription')}
      </p>
    </div>
  )
}

// =============================================================================
// Utilities
// =============================================================================

function getTimeAgo(date: Date): string {
  const now = new Date()
  const diffMs = now.getTime() - date.getTime()
  const diffMins = Math.floor(diffMs / 60000)
  const diffHours = Math.floor(diffMs / 3600000)
  const diffDays = Math.floor(diffMs / 86400000)

  if (diffMins < 1) return 'just now'
  if (diffMins < 60) return `${diffMins}m ago`
  if (diffHours < 24) return `${diffHours}h ago`
  return `${diffDays}d ago`
}
