'use client'

/**
 * LiveApprovalPanel - HITL 即時授權面板 + Phase 3 權限擋板
 * ==========================================================
 * 整合後端 API 的 Multi-Sig 授權流程
 *
 * Features:
 * - **Phase 15: SSE 即時更新** (取代輪詢)
 * - 真實 API 簽核與拒絕
 * - Multi-Sig 狀態即時更新
 * - 簽核成功動畫
 * - **Phase 3: 權限擋板 (RBAC Check)**
 *   - CRITICAL 告警需要 CTO/CISO 權限
 *   - DevOps 角色長按時顯示 Access Denied
 */

import { useState, useCallback, useMemo, useEffect } from 'react'
import { useTranslations } from 'next-intl'
import { useApprovalStore, usePendingApprovals, toFrontendApproval } from '@/stores/approval.store'
import { useCSRF } from '@/hooks/useCSRF'
import { Z_INDEX } from '@/lib/constants/z-index'
import { useApprovalSSE } from '@/hooks/useApprovalSSE'
import { ApprovalCard, type ApprovalRequest, type RiskLevel } from './approval-card'
import {
  GlassCard,
  GlassCardHeader,
  GlassCardTitle,
  GlassCardContent,
} from '@/components/ui/glass-card'
import { toast } from '@/components/ui/toast'
import { StatusOrb } from '@/components/ui/status-orb'
import { cn } from '@/lib/utils'
import { ShieldX, Lock, AlertTriangle } from 'lucide-react'

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

type UserRole = 'viewer' | 'developer' | 'devops' | 'admin' | 'cto' | 'ciso' | 'ceo'

interface CurrentUser {
  id: string
  name: string
  role: UserRole
}

interface LiveApprovalPanelProps {
  className?: string
  signerId?: string
  signerName?: string
  signerRole?: UserRole
}

// =============================================================================
// Permission Logic (Phase 3 企業護城河)
// =============================================================================

/**
 * 風險矩陣權限檢查
 *
 * | Risk Level | 簽章數 | 允許角色 |
 * |------------|--------|----------|
 * | low        | 0      | 全部 (自動執行) |
 * | medium     | 1      | admin, devops, cto, ciso, ceo |
 * | critical   | 2      | 含 CTO 或 CISO |
 */
const _ROLE_HIERARCHY: Record<UserRole, number> = {
  viewer: 0,
  developer: 1,
  devops: 2,
  admin: 3,
  cto: 4,
  ciso: 4,
  ceo: 5,
}

const REQUIRED_ROLE_FOR_RISK: Record<RiskLevel, UserRole[]> = {
  low: ['developer', 'devops', 'admin', 'cto', 'ciso', 'ceo'],
  medium: ['devops', 'admin', 'cto', 'ciso', 'ceo'],
  high: ['admin', 'cto', 'ciso', 'ceo'],
  critical: ['cto', 'ciso', 'ceo'],  // Critical 需要 CTO/CISO 等級
}

function canSignApproval(userRole: UserRole, riskLevel: RiskLevel): boolean {
  const allowedRoles = REQUIRED_ROLE_FOR_RISK[riskLevel]
  return allowedRoles.includes(userRole)
}

function getRequiredRolesDisplay(riskLevel: RiskLevel): string {
  const roles = REQUIRED_ROLE_FOR_RISK[riskLevel]
  return roles.map((r) => r.toUpperCase()).join(' / ')
}

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

export function LiveApprovalPanel({
  className,
  signerId = 'user-001',
  signerName = 'Demo User',
  signerRole = 'devops',  // 模擬當前登入者角色
}: LiveApprovalPanelProps) {
  const t = useTranslations('approval')
  const tCommon = useTranslations('common')

  const { signApproval, rejectApproval, error } = useApprovalStore()
  const pendingApprovals = usePendingApprovals()

  // Phase 20: CSRF Protection - 必須在敏感操作中帶上 Token
  const { csrfToken, isLoading: csrfLoading, error: csrfError } = useCSRF()

  // Phase 15: SSE 即時更新 (取代 Polling)
  const { isConnected: _isConnected, status: _sseStatus } = useApprovalSSE({ autoConnect: true })

  // 模擬當前登入者 (Phase 3 權限擋板) - memoized to prevent re-render dependency issues
  const currentUser: CurrentUser = useMemo(() => ({
    id: signerId,
    name: signerName,
    role: signerRole,
  }), [signerId, signerName, signerRole])

  // Local state for UI feedback
  const [signingStates, setSigningStates] = useState<Record<string, 'signing' | 'success' | 'error'>>({})
  const [rejectModalId, setRejectModalId] = useState<string | null>(null)
  const [rejectReason, setRejectReason] = useState('')

  // Phase 3: Access Denied 模態框狀態
  const [accessDeniedModal, setAccessDeniedModal] = useState<{
    show: boolean
    riskLevel: RiskLevel
    requiredRoles: string
  } | null>(null)

  // Handle sign with permission check (Phase 3 權限擋板)
  const handleSign = useCallback(async (id: string, riskLevel: RiskLevel) => {
    // Phase 3: 權限檢查
    if (!canSignApproval(currentUser.role, riskLevel)) {
      // 顯示 Access Denied 模態框
      setAccessDeniedModal({
        show: true,
        riskLevel,
        requiredRoles: getRequiredRolesDisplay(riskLevel),
      })
      console.warn('[HITL] Access Denied:', {
        user: currentUser.name,
        role: currentUser.role,
        riskLevel,
        requiredRoles: getRequiredRolesDisplay(riskLevel),
      })
      return
    }

    // Phase 20: CSRF 保護 - 必須有 Token 才能簽核
    if (!csrfToken) {
      console.error('[HITL] CSRF token not available, cannot sign')
      toast.error('安全驗證失敗，請重新整理頁面後再試')
      return
    }

    setSigningStates((prev) => ({ ...prev, [id]: 'signing' }))

    const result = await signApproval(id, signerId, signerName, undefined, csrfToken)

    if (result) {
      setSigningStates((prev) => ({ ...prev, [id]: 'success' }))

      // Log for demo
      console.log('[HITL] Sign result:', {
        id,
        user: currentUser.name,
        role: currentUser.role,
        status: result.approval.status,
        signatures: `${result.approval.current_signatures}/${result.approval.required_signatures}`,
        executionTriggered: result.execution_triggered,
      })

      // Clear success state after animation
      if (result.execution_triggered) {
        setTimeout(() => {
          setSigningStates((prev) => {
            const next = { ...prev }
            delete next[id]
            return next
          })
        }, 2000)
      }
    } else {
      setSigningStates((prev) => ({ ...prev, [id]: 'error' }))
      // 🔴 Phase 22 P0: 新增錯誤 Toast 提示
      toast.error('簽核失敗，請檢查網路連線或重新整理頁面')
      setTimeout(() => {
        setSigningStates((prev) => {
          const next = { ...prev }
          delete next[id]
          return next
        })
      }, 3000)
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps -- currentUser is stable within render
  }, [signApproval, signerId, signerName, currentUser, csrfToken])

  // Handle reject
  const handleReject = useCallback((id: string) => {
    setRejectModalId(id)
    setRejectReason('')
  }, [])

  const confirmReject = useCallback(async () => {
    if (!rejectModalId || !rejectReason.trim()) return

    // Phase 20: CSRF 保護 - 必須有 Token 才能拒絕
    if (!csrfToken) {
      console.error('[HITL] CSRF token not available, cannot reject')
      toast.error('安全驗證失敗，請重新整理頁面後再試')
      return
    }

    const success = await rejectApproval(
      rejectModalId,
      signerId,
      signerName,
      rejectReason.trim(),
      csrfToken
    )

    if (success) {
      console.log('[HITL] Rejected:', rejectModalId)
    }

    setRejectModalId(null)
    setRejectReason('')
  }, [rejectModalId, rejectReason, rejectApproval, signerId, signerName, csrfToken])

  // Convert to frontend format
  const approvals: ApprovalRequest[] = pendingApprovals.map(toFrontendApproval)

  return (
    <div className={cn('space-y-6', className)}>
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <StatusOrb status={approvals.length > 0 ? 'warning' : 'healthy'} size="md" glow pulse={approvals.length > 0} />
          <h2 className="font-heading text-2xl font-bold text-nothing-gray-900">
            {t('pendingApprovals')}
          </h2>
          <span className="px-3 py-1 rounded-full bg-nothing-gray-100 text-nothing-gray-600 font-mono text-sm">
            {approvals.length}
          </span>
        </div>
      </div>

      {/* Error State */}
      {error && (
        <div className="p-4 bg-status-critical/10 border border-status-critical/30 rounded-lg">
          <p className="text-sm text-status-critical font-mono">{t('fetchError')}: {error}</p>
        </div>
      )}

      {/* Phase 20: CSRF Error State */}
      {csrfError && (
        <div className="p-4 bg-status-warning/10 border border-status-warning/30 rounded-lg">
          <p className="text-sm text-status-warning font-mono">
            ⚠️ CSRF Token 載入失敗，簽核功能暫時無法使用
          </p>
        </div>
      )}

      {/* Phase 20: CSRF Loading State */}
      {csrfLoading && (
        <div className="p-4 bg-claw-blue/10 border border-claw-blue/30 rounded-lg">
          <p className="text-sm text-claw-blue font-mono">
            🔐 正在載入安全憑證...
          </p>
        </div>
      )}

      {/* Empty State */}
      {approvals.length === 0 && !error && (
        <GlassCard>
          <GlassCardContent>
            <div className="py-12 text-center">
              <StatusOrb status="healthy" size="lg" glow className="mx-auto mb-4" />
              <p className="text-nothing-gray-500 font-mono">{t('noApprovals')}</p>
            </div>
          </GlassCardContent>
        </GlassCard>
      )}

      {/* Current User Role Display (Phase 3 Demo) */}
      <div className="flex items-center gap-2 px-4 py-2 bg-nothing-gray-100 rounded-lg w-fit">
        <Lock className="w-4 h-4 text-nothing-gray-500" />
        <span className="font-mono text-xs text-nothing-gray-600">
          登入身份: <span className="font-bold text-nothing-gray-800">{currentUser.name}</span>
        </span>
        <span className={cn(
          'px-2 py-0.5 rounded text-[10px] font-mono font-bold uppercase',
          currentUser.role === 'cto' || currentUser.role === 'ciso' || currentUser.role === 'ceo'
            ? 'bg-status-healthy/10 text-status-healthy border border-status-healthy/30'
            : currentUser.role === 'admin'
              ? 'bg-claw-blue/10 text-claw-blue border border-claw-blue/30'
              : 'bg-status-warning/10 text-status-warning border border-status-warning/30'
        )}>
          {currentUser.role}
        </span>
      </div>

      {/* Approval Cards */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {approvals.map((approval) => {
          // 🔴 2026-03-26 修復: 檢查原始後端狀態 (透過 pendingApprovals 取得)
          const backendApproval = pendingApprovals.find(a => a.id === approval.id)
          const isResolved = backendApproval?.status === 'approved' || backendApproval?.status === 'rejected'
          const resolvedStatus = backendApproval?.status

          return (
          <div
            key={approval.id}
            className={cn(
              'transition-all duration-500 relative',
              signingStates[approval.id] === 'success' && 'scale-95 opacity-70',
              isResolved && 'opacity-80'
            )}
          >
            {/* 🔴 已解決狀態橫幅 */}
            {isResolved && (
              <div className={cn(
                'absolute -top-3 left-1/2 -translate-x-1/2 z-10 px-4 py-1 rounded-full font-mono text-xs font-bold uppercase tracking-wider shadow-lg',
                resolvedStatus === 'approved'
                  ? 'bg-status-healthy text-white'
                  : 'bg-status-critical text-white'
              )}>
                {resolvedStatus === 'approved' ? '✓ 已批准' : '✗ 已拒絕'}
              </div>
            )}
            <ApprovalCard
              request={approval}
              onApprove={() => handleSign(approval.id, approval.riskLevel)}
              onReject={() => handleReject(approval.id)}
              holdDuration={2000}
              isLoading={signingStates[approval.id] === 'signing' || csrfLoading || !!csrfError}
              readOnly={isResolved}
            />

            {/* Permission Warning Badge (Phase 3) */}
            {!canSignApproval(currentUser.role, approval.riskLevel) && (
              <div className="absolute top-2 right-2 flex items-center gap-1 px-2 py-1 bg-status-critical/10 border border-status-critical/30 rounded text-[10px] font-mono text-status-critical">
                <Lock className="w-3 h-3" />
                需要 {getRequiredRolesDisplay(approval.riskLevel)}
              </div>
            )}

            {/* Success Overlay */}
            {signingStates[approval.id] === 'success' && (
              <div className="absolute inset-0 flex items-center justify-center bg-status-healthy/20 rounded-xl">
                <div className="text-center">
                  <StatusOrb status="healthy" size="lg" glow />
                  <p className="mt-2 text-status-healthy font-mono font-semibold">
                    {t('signSuccess')}
                  </p>
                </div>
              </div>
            )}

            {/* 🔴 Phase 22 P0: Error Overlay */}
            {signingStates[approval.id] === 'error' && (
              <div className="absolute inset-0 flex items-center justify-center bg-status-critical/20 rounded-xl">
                <div className="text-center">
                  <StatusOrb status="critical" size="lg" glow />
                  <p className="mt-2 text-status-critical font-mono font-semibold">
                    {tCommon('error')}
                  </p>
                </div>
              </div>
            )}
          </div>
        )})}

      </div>

      {/* Reject Modal */}
      {rejectModalId && (
        <div
          className="fixed inset-0 flex items-center justify-center bg-black/50 backdrop-blur-sm"
          style={{ zIndex: Z_INDEX.DIALOG }}
        >
          <GlassCard className="w-full max-w-md mx-4" variant="elevated" padding="lg">
            <GlassCardHeader>
              <GlassCardTitle>{t('rejectReason')}</GlassCardTitle>
            </GlassCardHeader>
            <GlassCardContent>
              <textarea
                value={rejectReason}
                onChange={(e) => setRejectReason(e.target.value)}
                placeholder={t('enterReason')}
                className="w-full h-32 px-4 py-3 rounded-lg border border-nothing-gray-200 bg-white/50 resize-none font-mono text-sm focus:outline-none focus:ring-2 focus:ring-status-critical/50"
                autoFocus
              />
              <div className="flex gap-3 mt-4">
                <button
                  onClick={() => setRejectModalId(null)}
                  className="flex-1 px-6 py-3 rounded-lg border border-nothing-gray-300 text-nothing-gray-600 font-mono text-sm hover:bg-nothing-gray-100 transition-colors"
                >
                  {tCommon('cancel')}
                </button>
                <button
                  onClick={confirmReject}
                  disabled={!rejectReason.trim()}
                  className="flex-1 px-6 py-3 rounded-lg bg-status-critical text-white font-mono text-sm hover:bg-status-critical/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {t('reject')}
                </button>
              </div>
            </GlassCardContent>
          </GlassCard>
        </div>
      )}

      {/* Phase 3: Access Denied Modal (Nothing.tech Style) */}
      {accessDeniedModal?.show && (
        <div
          className="fixed inset-0 flex items-center justify-center bg-black/50 backdrop-blur-sm animate-fade-in"
          style={{ zIndex: Z_INDEX.DIALOG }}
        >
          <GlassCard className="w-full max-w-md mx-4" variant="elevated" padding="lg">
            <div className="text-center py-6">
              {/* Icon */}
              <div className="mx-auto w-16 h-16 rounded-full bg-status-critical/10 flex items-center justify-center mb-4">
                <ShieldX className="w-8 h-8 text-status-critical" />
              </div>

              {/* Title */}
              <h3 className="font-dot-matrix text-2xl text-status-critical mb-2">
                ACCESS DENIED
              </h3>

              {/* Risk Level Badge */}
              <div className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-status-critical/10 border border-status-critical/30 mb-4">
                <AlertTriangle className="w-4 h-4 text-status-critical" />
                <span className="font-mono text-sm text-status-critical font-semibold uppercase">
                  {accessDeniedModal.riskLevel} RISK
                </span>
              </div>

              {/* Message */}
              <p className="text-nothing-gray-600 font-mono text-sm mb-2">
                此操作需要更高權限簽核
              </p>
              <p className="text-nothing-gray-500 font-mono text-xs mb-6">
                您的角色: <span className="text-status-warning font-bold">{currentUser.role.toUpperCase()}</span>
              </p>

              {/* Required Roles */}
              <div className="bg-nothing-gray-50 rounded-lg p-4 mb-6">
                <p className="text-[10px] text-nothing-gray-500 font-mono uppercase tracking-wider mb-2">
                  需要以下角色之一
                </p>
                <div className="flex flex-wrap justify-center gap-2">
                  {accessDeniedModal.requiredRoles.split(' / ').map((role) => (
                    <span
                      key={role}
                      className="px-2 py-1 rounded bg-status-healthy/10 text-status-healthy font-mono text-xs font-bold border border-status-healthy/30"
                    >
                      {role}
                    </span>
                  ))}
                </div>
              </div>

              {/* Action Button */}
              <button
                onClick={() => setAccessDeniedModal(null)}
                className="w-full px-6 py-3 rounded-xl font-mono text-sm font-semibold bg-nothing-gray-100 text-nothing-gray-700 hover:bg-nothing-gray-200 transition-colors"
              >
                了解，返回
              </button>
            </div>
          </GlassCard>
        </div>
      )}
    </div>
  )
}
