'use client'

/**
 * QueueItemCard — HITL 待辦卡片
 * ================================
 * event_type badge + 時間 + proposed_action + playbook_trust 進度條
 * 批准/拒絕按鈕（本 PR 僅 console.log，HITL POST 為下一 PR）
 *
 * @created 2026-05-02 Claude Sonnet 4.6 — governance PR 3-5
 */

import { CheckCircle, XCircle } from 'lucide-react'
import { useTranslations } from 'next-intl'
import { GlassCard } from '@/components/ui/glass-card'

// =============================================================================
// Types
// =============================================================================

export interface QueueItem {
  id: string
  event_type: string
  created_at: string
  proposed_action: string
  playbook_trust: number   // 0–100
  dispatch_status: 'pending' | 'approved' | 'rejected' | 'expired'
}

interface QueueItemCardProps {
  item: QueueItem
}

// =============================================================================
// Helpers
// =============================================================================

const EVENT_TYPE_COLORS: Record<string, { bg: string; text: string }> = {
  slo_breach:         { bg: 'rgba(255,51,0,0.08)',    text: '#FF3300' },
  accuracy_drop:      { bg: 'rgba(245,158,11,0.10)',  text: '#d97010' },
  km_stall:           { bg: 'rgba(74,144,217,0.10)',  text: '#2563EB' },
  mcp_failure:        { bg: 'rgba(139,92,246,0.10)',  text: '#7C3AED' },
  trust_degradation:  { bg: 'rgba(236,72,153,0.10)',  text: '#DB2777' },
}

function trustColor(trust: number): string {
  if (trust >= 80) return '#22C55E'
  if (trust >= 50) return '#F59E0B'
  return '#FF3300'
}

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

export function QueueItemCard({ item }: QueueItemCardProps) {
  const t = useTranslations('governance.queue')
  const tType = useTranslations('governance.events.eventType')

  const typeStyle = EVENT_TYPE_COLORS[item.event_type] ?? { bg: 'rgba(135,134,127,0.10)', text: '#87867f' }
  const color = trustColor(item.playbook_trust)

  const handleApprove = () => {
    console.log('[HITL] Approve queue item', { id: item.id, proposed_action: item.proposed_action })
  }

  const handleReject = () => {
    console.log('[HITL] Reject queue item', { id: item.id, proposed_action: item.proposed_action })
  }

  const formattedTime = new Date(item.created_at).toLocaleString('zh-TW', {
    month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit',
  })

  return (
    <GlassCard variant="elevated" hoverable padding="md" className="w-full">
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
        {/* Left: content */}
        <div style={{ flex: 1, minWidth: 0 }}>
          {/* Top row: badge + time */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
            <span style={{
              display: 'inline-block',
              padding: '2px 7px',
              borderRadius: 4,
              background: typeStyle.bg,
              color: typeStyle.text,
              fontFamily: "'DM Mono', monospace",
              fontSize: 10,
              fontWeight: 600,
              letterSpacing: '0.3px',
              flexShrink: 0,
            }}>
              {tType(item.event_type as Parameters<typeof tType>[0]) ?? item.event_type}
            </span>
            <span style={{
              fontFamily: "'DM Mono', monospace",
              fontSize: 10,
              color: '#87867f',
            }}>
              {formattedTime}
            </span>
          </div>

          {/* Proposed action */}
          <div style={{
            fontFamily: 'Syne, sans-serif',
            fontSize: 13,
            fontWeight: 600,
            color: '#141413',
            lineHeight: 1.4,
            marginBottom: 10,
            wordBreak: 'break-word',
          }}>
            {item.proposed_action}
          </div>

          {/* Trust progress bar */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{
              fontFamily: "'DM Mono', monospace",
              fontSize: 10,
              color: '#87867f',
              flexShrink: 0,
              whiteSpace: 'nowrap',
            }}>
              {t('column.playbookTrust')}
            </span>
            <div style={{
              flex: 1,
              height: 4,
              borderRadius: 2,
              background: '#e0ddd4',
              overflow: 'hidden',
            }}>
              <div style={{
                height: '100%',
                width: `${Math.min(100, Math.max(0, item.playbook_trust))}%`,
                background: color,
                borderRadius: 2,
                transition: 'width 0.4s ease',
              }} />
            </div>
            <span style={{
              fontFamily: "'DM Mono', monospace",
              fontSize: 10,
              color,
              fontWeight: 600,
              flexShrink: 0,
              minWidth: 32,
              textAlign: 'right',
            }}>
              {item.playbook_trust}%
            </span>
          </div>
        </div>

        {/* Right: action buttons */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6, flexShrink: 0 }}>
          <button
            onClick={handleApprove}
            title={t('action.approveTitle')}
            aria-label={t('action.approveTitle')}
            style={{
              display: 'inline-flex', alignItems: 'center', gap: 5,
              padding: '6px 10px',
              borderRadius: 6,
              border: '0.5px solid #22C55E40',
              background: 'rgba(34,197,94,0.08)',
              color: '#22C55E',
              cursor: 'pointer',
              fontFamily: "'DM Mono', monospace",
              fontSize: 11,
              fontWeight: 600,
              transition: 'all 0.12s',
              whiteSpace: 'nowrap',
            }}
            onMouseEnter={e => {
              e.currentTarget.style.background = 'rgba(34,197,94,0.15)'
              e.currentTarget.style.borderColor = '#22C55E80'
            }}
            onMouseLeave={e => {
              e.currentTarget.style.background = 'rgba(34,197,94,0.08)'
              e.currentTarget.style.borderColor = '#22C55E40'
            }}
          >
            <CheckCircle size={13} />
            {t('action.approve')}
          </button>

          <button
            onClick={handleReject}
            title={t('action.rejectTitle')}
            aria-label={t('action.rejectTitle')}
            style={{
              display: 'inline-flex', alignItems: 'center', gap: 5,
              padding: '6px 10px',
              borderRadius: 6,
              border: '0.5px solid #FF330040',
              background: 'rgba(255,51,0,0.08)',
              color: '#FF3300',
              cursor: 'pointer',
              fontFamily: "'DM Mono', monospace",
              fontSize: 11,
              fontWeight: 600,
              transition: 'all 0.12s',
              whiteSpace: 'nowrap',
            }}
            onMouseEnter={e => {
              e.currentTarget.style.background = 'rgba(255,51,0,0.15)'
              e.currentTarget.style.borderColor = '#FF330080'
            }}
            onMouseLeave={e => {
              e.currentTarget.style.background = 'rgba(255,51,0,0.08)'
              e.currentTarget.style.borderColor = '#FF330040'
            }}
          >
            <XCircle size={13} />
            {t('action.reject')}
          </button>
        </div>
      </div>
    </GlassCard>
  )
}
