'use client'

/**
 * ApprovalThreadItem - 對話列表中的單一審核項目
 * ================================================
 * Phase 11: #48 ApprovalThread 子組件
 *
 * Features:
 * - 顯示風險等級、標題、時間戳
 * - 選中狀態視覺回饋
 * - 懸停效果
 * - Nothing.tech 風格
 *
 * i18n: 100% next-intl
 */

import { useMemo } from 'react'
import { useTranslations } from 'next-intl'
import { cn } from '@/lib/utils'
import { StatusOrb } from '@/components/ui/status-orb'
import type { ApprovalRequest } from './approval-card'
import { Clock, AlertTriangle, Shield, Zap } from 'lucide-react'

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

interface ApprovalThreadItemProps {
  approval: ApprovalRequest
  isSelected: boolean
  onSelect: () => void
}

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

/**
 * 風險等級對應的顏色和圖示
 */
function getRiskConfig(riskLevel: ApprovalRequest['riskLevel']) {
  switch (riskLevel) {
    case 'critical':
      return {
        color: 'text-status-critical',
        bgColor: 'bg-status-critical/10',
        borderColor: 'border-status-critical/30',
        icon: AlertTriangle,
        orbStatus: 'critical' as const,
      }
    case 'high':
      return {
        color: 'text-status-warning',
        bgColor: 'bg-status-warning/10',
        borderColor: 'border-status-warning/30',
        icon: Shield,
        orbStatus: 'warning' as const,
      }
    case 'medium':
      return {
        color: 'text-claw-blue',
        bgColor: 'bg-claw-blue/10',
        borderColor: 'border-claw-blue/30',
        icon: Zap,
        orbStatus: 'healthy' as const,
      }
    case 'low':
    default:
      return {
        color: 'text-nothing-gray-500',
        bgColor: 'bg-nothing-gray-100',
        borderColor: 'border-nothing-gray-200',
        icon: Clock,
        orbStatus: 'healthy' as const,
      }
  }
}

/**
 * 格式化時間戳為相對時間
 */
function formatRelativeTime(timestamp: string, t: ReturnType<typeof useTranslations>): string {
  const date = new Date(timestamp)
  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 t('justNow')
  } else if (diffMins < 60) {
    return t('minutesAgo', { count: diffMins })
  } else if (diffHours < 24) {
    return t('hoursAgo', { count: diffHours })
  } else {
    return t('daysAgo', { count: diffDays })
  }
}

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

export function ApprovalThreadItem({
  approval,
  isSelected,
  onSelect,
}: ApprovalThreadItemProps) {
  const t = useTranslations('approval')

  const riskConfig = useMemo(() => getRiskConfig(approval.riskLevel), [approval.riskLevel])
  const RiskIcon = riskConfig.icon

  const relativeTime = useMemo(
    () => formatRelativeTime(approval.requestedAt, t),
    [approval.requestedAt, t]
  )

  // 提取動作類型摘要
  const actionSummary = useMemo(() => {
    // 截取 action 的前 30 個字元作為摘要
    const action = approval.action || ''
    return action.length > 30 ? action.slice(0, 30) + '...' : action
  }, [approval.action])

  return (
    <button
      onClick={onSelect}
      className={cn(
        'relative w-full text-left p-3 rounded-xl transition-all duration-200',
        'border border-transparent',
        'hover:bg-nothing-gray-50',
        'focus:outline-none focus:ring-2 focus:ring-claw-blue/50',
        isSelected && [
          'bg-claw-blue/5',
          'border-claw-blue/30',
          'shadow-sm',
        ],
        !isSelected && 'hover:border-nothing-gray-200'
      )}
    >
      {/* 頂部: 風險指示器 + 時間 */}
      <div className="flex items-center justify-between mb-2">
        <div className={cn(
          'flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-mono',
          riskConfig.bgColor,
          riskConfig.color
        )}>
          <RiskIcon className="w-3 h-3" />
          <span className="uppercase">{approval.riskLevel}</span>
        </div>
        <span className="text-xs text-nothing-gray-400 font-mono">
          {relativeTime}
        </span>
      </div>

      {/* 中間: 動作描述 */}
      <div className="mb-2">
        <h4 className={cn(
          'font-heading text-sm font-medium truncate',
          isSelected ? 'text-claw-blue' : 'text-nothing-gray-900'
        )}>
          {approval.description}
        </h4>
      </div>

      {/* 底部: 動作類型 + 狀態指示 */}
      <div className="flex items-center justify-between">
        <span className="text-xs text-nothing-gray-500 font-mono truncate max-w-[70%]">
          {actionSummary}
        </span>
        <StatusOrb
          status={riskConfig.orbStatus}
          size="sm"
          pulse={approval.riskLevel === 'critical'}
        />
      </div>

      {/* 選中指示線 */}
      {isSelected && (
        <div className="absolute left-0 top-1/2 -translate-y-1/2 w-1 h-8 bg-claw-blue rounded-r-full" />
      )}
    </button>
  )
}
