'use client'

/**
 * CompactApprovalItem - 緊湊型待簽核項目
 * ======================================
 * UX 優化：列表顯示 + 點擊展開彈窗
 *
 * 特點：
 * - 單行顯示：風險等級 + 標題 + 簽核進度
 * - 快速 Y/n 按鈕（不需長按）
 * - 點擊標題 → 彈窗詳情
 */

import { useState, useCallback } from 'react'
import { useTranslations } from 'next-intl'
import { cn } from '@/lib/utils'
import { AlertTriangle, CheckCircle2, ChevronRight, Shield, XCircle } from 'lucide-react'
import { Dialog } from '@/components/ui/dialog'
import { ApprovalCard, type ApprovalRequest } from './approval-card'

interface CompactApprovalItemProps {
  request: ApprovalRequest
  onApprove: (id: string) => void
  onReject: (id: string) => void
  holdDuration?: number
}

export function CompactApprovalItem({
  request,
  onApprove,
  onReject,
  holdDuration = 1000,
}: CompactApprovalItemProps) {
  const t = useTranslations('approval')
  const tRisk = useTranslations('risk')
  const [showDetail, setShowDetail] = useState(false)
  const [isProcessing, setIsProcessing] = useState(false)

  const isCritical = request.riskLevel === 'critical'
  const isHigh = request.riskLevel === 'high'

  // 快速拒絕（不需彈窗）
  const handleQuickReject = useCallback((e: React.MouseEvent) => {
    e.stopPropagation()
    setIsProcessing(true)
    onReject(request.id)
  }, [onReject, request.id])

  // 簽核（打開彈窗確認）
  const handleApproveClick = useCallback((e: React.MouseEvent) => {
    e.stopPropagation()
    setShowDetail(true)
  }, [])

  // 從彈窗內簽核
  const handleApproveFromModal = useCallback((id: string) => {
    setIsProcessing(true)
    setShowDetail(false)
    onApprove(id)
  }, [onApprove])

  // 從彈窗內拒絕
  const handleRejectFromModal = useCallback((id: string) => {
    setIsProcessing(true)
    setShowDetail(false)
    onReject(id)
  }, [onReject])

  // 解析標題（取 | 前的動作描述）
  const title = request.action.includes('|')
    ? request.action.split('|')[0].trim()
    : request.action

  return (
    <>
      {/* 緊湊列表項目 */}
      <div
        className={cn(
          'group flex items-center gap-3 p-3 rounded-xl cursor-pointer',
          'bg-white border transition-all duration-200',
          'hover:shadow-md hover:-translate-y-0.5',
          isCritical && 'border-l-4 border-l-status-critical border-status-critical/30',
          isHigh && 'border-l-4 border-l-status-warning border-status-warning/30',
          !isCritical && !isHigh && 'border-nothing-gray-200 hover:border-nothing-gray-300',
          isProcessing && 'opacity-50 pointer-events-none'
        )}
        onClick={() => setShowDetail(true)}
      >
        {/* 風險等級指示器 */}
        <div
          className={cn(
            'flex-shrink-0 w-8 h-8 rounded-lg flex items-center justify-center',
            isCritical && 'bg-status-critical/10',
            isHigh && 'bg-status-warning/10',
            request.riskLevel === 'medium' && 'bg-status-warning/10',
            request.riskLevel === 'low' && 'bg-status-healthy/10'
          )}
        >
          {isCritical || isHigh ? (
            <AlertTriangle className={cn(
              'w-4 h-4',
              isCritical ? 'text-status-critical' : 'text-status-warning'
            )} />
          ) : (
            <CheckCircle2 className="w-4 h-4 text-status-healthy" />
          )}
        </div>

        {/* 標題與摘要 */}
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2">
            <span className="font-mono text-sm font-medium text-nothing-gray-900 truncate">
              {title}
            </span>
            <ChevronRight className="w-4 h-4 text-nothing-gray-400 flex-shrink-0 group-hover:translate-x-0.5 transition-transform" />
          </div>
          <div className="flex items-center gap-2 mt-0.5">
            <span className={cn(
              'text-[10px] font-mono font-bold uppercase px-1.5 py-0.5 rounded',
              isCritical && 'bg-status-critical/10 text-status-critical',
              isHigh && 'bg-status-warning/10 text-status-warning',
              request.riskLevel === 'medium' && 'bg-status-warning/10 text-status-warning',
              request.riskLevel === 'low' && 'bg-status-healthy/10 text-status-healthy'
            )}>
              {tRisk(request.riskLevel)}
            </span>
            <span className="text-[10px] font-mono text-nothing-gray-400">
              {request.currentSignatures}/{request.requiredSignatures}
            </span>
          </div>
        </div>

        {/* 快速操作按鈕 */}
        <div className="flex items-center gap-2 flex-shrink-0">
          {/* 拒絕 */}
          <button
            onClick={handleQuickReject}
            className={cn(
              'p-2 rounded-lg border-2 border-dashed border-nothing-gray-300',
              'text-nothing-gray-500 hover:border-status-critical hover:text-status-critical',
              'hover:bg-status-critical/5 transition-all'
            )}
            title={t('reject')}
          >
            <XCircle className="w-4 h-4" />
          </button>

          {/* 簽核（打開詳情） */}
          <button
            onClick={handleApproveClick}
            className={cn(
              'p-2 rounded-lg border-2 border-dashed',
              isCritical ? 'border-status-critical text-status-critical hover:bg-status-critical/5' :
              'border-claw-blue text-claw-blue hover:bg-claw-blue/5',
              'transition-all'
            )}
            title={t('holdToSign')}
          >
            <Shield className="w-4 h-4" />
          </button>
        </div>
      </div>

      {/* 詳情彈窗 */}
      <Dialog
        open={showDetail}
        onClose={() => setShowDetail(false)}
        title={t('approvalDetail')}
        className="max-w-xl"
      >
        <div className="p-4">
          <ApprovalCard
            request={request}
            onApprove={handleApproveFromModal}
            onReject={handleRejectFromModal}
            holdDuration={holdDuration}
          />
        </div>
      </Dialog>
    </>
  )
}
