'use client'

/**
 * ApprovalCard - HITL 授權卡片
 * ============================
 * Phase 2.1: 人機協作核心組件
 * 設計風格: Nothing.tech (毛玻璃 + 極簡 + 風險色彩)
 *
 * i18n: 100% 使用 useTranslations，禁止任何寫死字串
 * 符合 AWOOOI 專案開發憲法 v2.0
 */

import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { cn } from '@/lib/utils'

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

type RiskLevel = 'low' | 'medium' | 'high' | 'critical'

interface DryRunCheck {
  name: string
  passed: boolean
  message?: string
}

interface BlastRadius {
  affectedPods: number
  estimatedDowntime: string
  relatedServices: string[]
  dataImpact: 'NONE' | 'READ_ONLY' | 'WRITE' | 'DESTRUCTIVE'
}

interface ApprovalRequest {
  id: string
  action: string
  description: string
  riskLevel: RiskLevel
  blastRadius: BlastRadius
  dryRunChecks: DryRunCheck[]
  requiredSignatures: number
  currentSignatures: number
  requestedBy: string
  requestedAt: string
}

interface ApprovalCardProps {
  request: ApprovalRequest
  onApprove?: (id: string) => void
  onReject?: (id: string) => void
  className?: string
}

// ==================== Config ====================

const riskStyleConfig: Record<
  RiskLevel,
  { color: string; bgColor: string; borderColor: string }
> = {
  low: {
    color: 'text-status-healthy',
    bgColor: 'bg-status-healthy/10',
    borderColor: 'border-status-healthy/30',
  },
  medium: {
    color: 'text-status-warning',
    bgColor: 'bg-status-warning/10',
    borderColor: 'border-status-warning/30',
  },
  high: {
    color: 'text-nothing-red',
    bgColor: 'bg-nothing-red/10',
    borderColor: 'border-nothing-red/30',
  },
  critical: {
    color: 'text-nothing-red',
    bgColor: 'bg-nothing-red/20',
    borderColor: 'border-nothing-red/50',
  },
}

const dataImpactStyleConfig: Record<
  BlastRadius['dataImpact'],
  { color: string }
> = {
  NONE: { color: 'text-nothing-gray-400' },
  READ_ONLY: { color: 'text-status-healthy' },
  WRITE: { color: 'text-status-warning' },
  DESTRUCTIVE: { color: 'text-nothing-red' },
}

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

export function ApprovalCard({
  request,
  onApprove,
  onReject,
  className,
}: ApprovalCardProps) {
  const t = useTranslations('approval')
  const tRisk = useTranslations('risk')
  const tBlast = useTranslations('blastRadius')
  const tDryRun = useTranslations('dryRun')

  const [confirmStep, setConfirmStep] = useState<0 | 1 | 2>(0)

  const riskStyle = riskStyleConfig[request.riskLevel]
  const dataImpactStyle = dataImpactStyleConfig[request.blastRadius?.dataImpact ?? 'NONE']
  const allChecksPassed = request.dryRunChecks?.every((c) => c.passed) ?? true
  const needsMoreSignatures = request.currentSignatures < request.requiredSignatures
  const isDestructive = request.blastRadius?.dataImpact === 'DESTRUCTIVE'

  // i18n: 風險等級標籤
  const riskLabel = tRisk(request.riskLevel)

  // i18n: 資料影響標籤
  const dataImpactLabel = tBlast(
    request.blastRadius?.dataImpact === 'READ_ONLY' ? 'readOnly' :
    request.blastRadius?.dataImpact === 'WRITE' ? 'write' :
    request.blastRadius?.dataImpact === 'DESTRUCTIVE' ? 'destructive' : 'none'
  )

  const handleApprove = () => {
    if (isDestructive && confirmStep < 2) {
      setConfirmStep((prev) => Math.min(prev + 1, 2) as 0 | 1 | 2)
      if (confirmStep === 1) {
        onApprove?.(request.id)
        setConfirmStep(0)
      }
    } else {
      onApprove?.(request.id)
    }
  }

  const handleReject = () => {
    setConfirmStep(0)
    onReject?.(request.id)
  }

  return (
    <div className={cn('glass-panel p-6 space-y-5', className)}>
      {/* Header: Risk Badge + Action */}
      <div className="flex items-start justify-between gap-4">
        <div className="flex-1 min-w-0">
          {/* Risk Badge */}
          <div
            className={cn(
              'inline-flex items-center gap-2 px-3 py-1 rounded-full border text-xs font-mono tracking-wider mb-3',
              riskStyle.bgColor,
              riskStyle.borderColor,
              riskStyle.color
            )}
          >
            <span
              className={cn(
                'w-2 h-2 rounded-full',
                request.riskLevel === 'critical' && 'animate-pulse',
                request.riskLevel === 'low' && 'bg-status-healthy',
                request.riskLevel === 'medium' && 'bg-status-warning',
                (request.riskLevel === 'high' || request.riskLevel === 'critical') && 'bg-nothing-red'
              )}
            />
            {riskLabel}
          </div>

          {/* Action Title */}
          <h3 className="font-display text-display-sm text-nothing-white truncate">
            {request.action}
          </h3>
          <p className="text-nothing-gray-400 text-sm mt-1">
            {request.description}
          </p>
        </div>

        {/* Signature Counter */}
        <div className="text-right shrink-0">
          <div className="font-mono text-xs text-nothing-gray-500 mb-1">
            {t('signatures')}
          </div>
          <div
            className={cn(
              'font-mono text-lg',
              needsMoreSignatures ? 'text-status-warning' : 'text-status-healthy'
            )}
          >
            {request.currentSignatures}/{request.requiredSignatures}
          </div>
        </div>
      </div>

      {/* Divider */}
      <div className="h-px bg-nothing-gray-800" />

      {/* Blast Radius Section */}
      <div className="space-y-3">
        <h4 className="font-mono text-xs text-nothing-gray-500 tracking-wider">
          {tBlast('title')}
        </h4>
        <div className="grid grid-cols-2 gap-3">
          {/* Affected Pods */}
          <div className="bg-nothing-gray-900 rounded-card p-3">
            <div className="font-mono text-xs text-nothing-gray-500 mb-1">
              {tBlast('affectedPods')}
            </div>
            <div className="font-mono text-lg text-nothing-white">
              {request.blastRadius?.affectedPods ?? 0}
            </div>
          </div>

          {/* Estimated Downtime */}
          <div className="bg-nothing-gray-900 rounded-card p-3">
            <div className="font-mono text-xs text-nothing-gray-500 mb-1">
              {tBlast('estimatedDowntime')}
            </div>
            <div className="font-mono text-lg text-nothing-white">
              {request.blastRadius?.estimatedDowntime ?? '0'}
            </div>
          </div>

          {/* Related Services */}
          <div className="bg-nothing-gray-900 rounded-card p-3">
            <div className="font-mono text-xs text-nothing-gray-500 mb-1">
              {tBlast('relatedServices')}
            </div>
            <div className="flex flex-wrap gap-1 mt-1">
              {(request.blastRadius?.relatedServices ?? []).map((service) => (
                <span
                  key={service}
                  className="px-2 py-0.5 bg-nothing-gray-800 rounded text-xs font-mono text-nothing-gray-300"
                >
                  {service}
                </span>
              ))}
            </div>
          </div>

          {/* Data Impact */}
          <div className="bg-nothing-gray-900 rounded-card p-3">
            <div className="font-mono text-xs text-nothing-gray-500 mb-1">
              {tBlast('dataImpact')}
            </div>
            <div className={cn('font-mono text-lg', dataImpactStyle.color)}>
              {dataImpactLabel}
            </div>
          </div>
        </div>
      </div>

      {/* Divider */}
      <div className="h-px bg-nothing-gray-800" />

      {/* Dry-Run Checks */}
      <div className="space-y-3">
        <h4 className="font-mono text-xs text-nothing-gray-500 tracking-wider">
          {tDryRun('validation')}
        </h4>
        <div className="space-y-2">
          {request.dryRunChecks.map((check) => (
            <div
              key={check.name}
              className="flex items-center justify-between bg-nothing-gray-900 rounded-card px-4 py-2"
            >
              <div className="flex items-center gap-3">
                <div
                  className={cn(
                    'w-5 h-5 rounded-full flex items-center justify-center text-xs',
                    check.passed
                      ? 'bg-status-healthy/20 text-status-healthy'
                      : 'bg-nothing-red/20 text-nothing-red'
                  )}
                >
                  {check.passed ? '✓' : '✗'}
                </div>
                <span className="font-mono text-sm text-nothing-white">
                  {check.name}
                </span>
              </div>
              {check.message && (
                <span className="font-mono text-xs text-nothing-gray-500">
                  {check.message}
                </span>
              )}
            </div>
          ))}
        </div>
      </div>

      {/* Divider */}
      <div className="h-px bg-nothing-gray-800" />

      {/* Footer: Meta + Actions */}
      <div className="flex items-center justify-between">
        {/* Meta */}
        <div className="font-mono text-xs text-nothing-gray-600">
          <span>{t('requestedBy')} </span>
          <span className="text-nothing-gray-400">{request.requestedBy}</span>
          <span className="mx-2">|</span>
          <span>{request.requestedAt}</span>
        </div>

        {/* Action Buttons */}
        <div className="flex items-center gap-3">
          {/* Reject Button */}
          <button
            onClick={handleReject}
            className={cn(
              'px-5 py-2 rounded-button font-mono text-sm transition-all',
              'border border-nothing-gray-700 text-nothing-gray-400',
              'hover:border-nothing-red hover:text-nothing-red hover:bg-nothing-red/10'
            )}
          >
            {t('reject')}
          </button>

          {/* Approve Button - with DESTRUCTIVE protection */}
          {isDestructive && confirmStep === 1 ? (
            <button
              onClick={handleApprove}
              disabled={!allChecksPassed}
              className={cn(
                'px-5 py-2 rounded-button font-mono text-sm transition-all animate-pulse',
                'bg-nothing-red text-nothing-white border-2 border-nothing-red',
                'hover:bg-nothing-red/80'
              )}
            >
              {t('confirmDestructive')}
            </button>
          ) : (
            <button
              onClick={handleApprove}
              disabled={!allChecksPassed}
              className={cn(
                'px-5 py-2 rounded-button font-mono text-sm transition-all',
                allChecksPassed
                  ? isDestructive
                    ? 'bg-nothing-red/20 text-nothing-red border border-nothing-red/50 hover:bg-nothing-red/30'
                    : 'bg-nothing-white text-nothing-black hover:bg-nothing-gray-200'
                  : 'bg-nothing-gray-800 text-nothing-gray-600 cursor-not-allowed'
              )}
            >
              {needsMoreSignatures
                ? t('needMore', { count: request.requiredSignatures - request.currentSignatures })
                : isDestructive
                  ? t('approveDestructive')
                  : t('approve')}
            </button>
          )}
        </div>
      </div>
    </div>
  )
}

// ==================== Export Types ====================

export type { ApprovalRequest, DryRunCheck, BlastRadius, RiskLevel }
