'use client'

/**
 * GroupNode — React Flow 自定義群組節點
 * ======================================
 * Sprint 5R B2: 新增展開/收合點擊互動
 *
 * 收合時: 群組名稱 + 服務數 + 健康摘要 (點擊展開)
 * 展開時: 背景容器，內部節點由 elkjs 排列 (點擊收合)
 *
 * 建立時間: 2026-04-08 (台北時區)
 * 修改時間: 2026-04-10 — B2 展開/收合互動 (Claude Code Sprint 5R)
 */

import { memo, type CSSProperties, useCallback } from 'react'
import { type NodeProps } from '@xyflow/react'
import { useTranslations } from 'next-intl'
import { ChevronDown, ChevronRight } from 'lucide-react'

// C2: 群組標籤 i18n
const GROUP_LABELS: Record<string, string> = {
  infra: 'groupInfra', security: 'groupSecurity', k3s: 'groupK3s', aiData: 'groupAiData',
}

function GroupNodeInner({ data }: NodeProps) {
  const t = useTranslations('topology')
  const d = data as Record<string, any>
  const borderColor = d.borderColor || '#e0ddd4'
  const bgColor = d.bgColor || 'rgba(0,0,0,0.01)'
  const color = d.color || '#87867f'
  const healthySvc = d.healthyServices || 0
  const totalSvc = d.serviceCount || 0
  const hasWarning = healthySvc < totalSvc
  const isExpanded = d.isExpanded || false
  const onToggle = d.onToggle as ((id: string) => void) | undefined

  const handleClick = useCallback(() => {
    onToggle?.(d.id || '')
  }, [onToggle, d.id])

  const style: CSSProperties = {
    border: `0.5px solid ${borderColor}`,
    borderRadius: 10,
    background: bgColor,
    padding: '8px 12px',
    minWidth: 200,
    minHeight: isExpanded ? 120 : 80,
    fontFamily: "'DM Mono', monospace",
    cursor: 'pointer',
    userSelect: 'none',
  }

  return (
    <div style={style} onClick={handleClick}>
      {/* 群組標題 */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
        {isExpanded
          ? <ChevronDown size={12} color={color} />
          : <ChevronRight size={12} color={color} />
        }
        <span style={{ fontSize: 12, fontWeight: 600, color: '#141413' }}>
          {t(GROUP_LABELS[d.labelKey] || 'groupInfra')} (.{d.ipSuffix})
        </span>
      </div>

      {/* 摘要 */}
      <div style={{ fontSize: 10, color: '#555550' }}>
        {totalSvc} {t('services')} · {hasWarning
          ? <span style={{ color: '#F59E0B' }}>{totalSvc - healthySvc} {t('warning')}</span>
          : <span style={{ color: '#22C55E' }}>{t('allHealthy')}</span>
        }
      </div>

      {/* 指標 (如果有) */}
      {d.metrics && (
        <div style={{ display: 'flex', gap: 8, marginTop: 4, fontSize: 9, color: '#87867f' }}>
          {d.metrics.cpu_percent != null && (
            <span>CPU: <b style={{ color: d.metrics.cpu_percent > 80 ? '#F59E0B' : '#141413' }}>{d.metrics.cpu_percent}%</b></span>
          )}
          {d.metrics.memory_percent != null && (
            <span>RAM: <b style={{ color: d.metrics.memory_percent > 80 ? '#F59E0B' : '#141413' }}>{d.metrics.memory_percent}%</b></span>
          )}
        </div>
      )}
    </div>
  )
}

export const GroupNode = memo(GroupNodeInner, (prev, next) => {
  const p = prev.data as Record<string, any>
  const n = next.data as Record<string, any>
  return (
    p.status === n.status &&
    p.healthyServices === n.healthyServices &&
    p.serviceCount === n.serviceCount &&
    p.isExpanded === n.isExpanded
  )
})
