'use client'

/**
 * LiveHostCard - 即時主機狀態卡片
 * ================================
 * Phase 2.5: Magic UI 視覺升級
 *
 * Features:
 * - 自動訂閱 SSE 更新
 * - Metrics 動畫過渡
 * - 狀態變化閃爍效果
 * - Lucide Icons + 精緻 hover 效果
 */

import { useEffect, useState } from 'react'
import { useTranslations } from 'next-intl'
import {
  GlassCard,
  GlassCardHeader,
  GlassCardTitle,
  GlassCardContent,
  GlassCardFooter,
} from '@/components/ui/glass-card'
import { StatusOrb, StatusBadge, type StatusType } from '@/components/ui/status-orb'
import { useHostByIp } from '@/stores/dashboard.store'
import { cn } from '@/lib/utils'
import {
  Server,
  Shield,
  Cpu,
  HardDrive,
  Wifi,
  Gauge,
} from 'lucide-react'

// =============================================================================
// Helper Functions
// =============================================================================

function mapServiceStatus(status: string): StatusType {
  const mapping: Record<string, StatusType> = {
    up: 'healthy',
    down: 'critical',
    degraded: 'warning',
    healthy: 'healthy',
    warning: 'warning',
    critical: 'critical',
    thinking: 'thinking',
    syncing: 'syncing',
    idle: 'idle',
  }
  return mapping[status] || 'idle'
}

function mapHostStatus(status: string): StatusType {
  const mapping: Record<string, StatusType> = {
    healthy: 'healthy',
    degraded: 'warning',
    unhealthy: 'critical',
    unreachable: 'critical',
  }
  return mapping[status] || 'idle'
}

function formatPercent(value: number): string {
  return `${Math.round(value)}%`
}

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

interface LiveHostCardProps {
  ip: string
  fallbackData?: {
    name: string
    role: string
    services: Array<{ name: string; status: StatusType; port?: number | null }>
  }
  className?: string
  onClick?: () => void
}

export function LiveHostCard({
  ip,
  fallbackData,
  className,
  onClick,
}: LiveHostCardProps) {
  const t = useTranslations('status')
  const tDashboard = useTranslations('dashboard')
  const tCommon = useTranslations('common')
  const host = useHostByIp(ip)

  // Track status changes for flash effect
  const [isFlashing, setIsFlashing] = useState(false)
  const [prevStatus, setPrevStatus] = useState<string | null>(null)

  useEffect(() => {
    if (host && prevStatus && host.status !== prevStatus) {
      setIsFlashing(true)
      setTimeout(() => setIsFlashing(false), 500)
    }
    if (host) {
      setPrevStatus(host.status)
    }
  }, [host, prevStatus])

  // Use fallback if no data from store
  if (!host) {
    if (!fallbackData) {
      return (
        <GlassCard className={cn('h-full animate-pulse', className)}>
          <div className="h-40 flex items-center justify-center">
            <span className="text-nothing-gray-400 font-mono text-sm">
              {tCommon('loading')} {ip}
            </span>
          </div>
        </GlassCard>
      )
    }

    // Render with fallback data
    return (
      <GlassCard hoverable className={cn('h-full flex flex-col opacity-60', className)}>
        <GlassCardHeader>
          <div className="flex items-center gap-3">
            <StatusOrb status="idle" size="md" />
            <span className="inline-flex items-center px-2 py-0.5 rounded-md bg-nothing-gray-100 text-nothing-gray-600 text-xs font-mono">
              {ip}
            </span>
          </div>
        </GlassCardHeader>
        <GlassCardTitle className="mb-4">{fallbackData.name}</GlassCardTitle>
        <GlassCardContent>
          <div className="space-y-2">
            {fallbackData.services.map((service) => (
              <div key={service.name} className="flex items-center gap-2 py-1.5 px-2">
                <StatusOrb status="idle" size="sm" />
                <span className="font-mono text-sm text-nothing-gray-500">
                  {service.name}
                </span>
              </div>
            ))}
          </div>
        </GlassCardContent>
        <GlassCardFooter>
          <span className="text-xs text-nothing-gray-400">{tDashboard('waitingData')}</span>
        </GlassCardFooter>
      </GlassCard>
    )
  }

  const overallStatus = mapHostStatus(host.status)
  const statusLabel = t(overallStatus)

  // Role icon mapping
  const getRoleIcon = (role: string) => {
    const icons: Record<string, typeof Server> = {
      devops: HardDrive,
      security: Shield,
      k3s: Server,
      ai_web: Cpu,
    }
    const Icon = icons[role] || Server
    return <Icon className="w-4 h-4" />
  }

  return (
    <GlassCard
      hoverable
      clickable={!!onClick}
      onClick={onClick}
      className={cn(
        'h-full flex flex-col transition-all duration-300',
        'hover:-translate-y-1 hover:shadow-card-hover',
        isFlashing && 'ring-2 ring-status-warning/50 animate-pulse',
        overallStatus === 'critical' && 'ring-1 ring-status-critical/30',
        className
      )}
      aria-label={`${host.name} - ${statusLabel}`}
    >
      {/* Header - Enhanced */}
      <GlassCardHeader>
        <div className="flex items-center gap-3">
          <div className={cn(
            'w-10 h-10 rounded-xl flex items-center justify-center',
            'transition-all duration-300',
            overallStatus === 'healthy'
              ? 'bg-status-healthy/10 text-status-healthy'
              : overallStatus === 'warning'
                ? 'bg-status-warning/10 text-status-warning'
                : overallStatus === 'critical'
                  ? 'bg-status-critical/10 text-status-critical'
                  : 'bg-nothing-gray-100 text-nothing-gray-500'
          )}>
            {getRoleIcon(host.role || '')}
          </div>
          <div className="flex flex-col gap-1">
            <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-nothing-gray-50 border border-nothing-gray-100 text-nothing-gray-700 text-xs font-mono">
              <Wifi className="w-3 h-3" />
              {host.ip}
            </span>
          </div>
        </div>
        <StatusOrb status={overallStatus} size="md" glow pulse={overallStatus === 'critical'} />
      </GlassCardHeader>

      {/* Title - Enhanced */}
      <div className="mb-4">
        <GlassCardTitle className="text-lg">{host.name}</GlassCardTitle>
        {host.role && (
          <span className="text-[10px] text-nothing-gray-400 font-mono uppercase tracking-widest">
            {host.role.replace('_', ' ')}
          </span>
        )}
      </div>

      {/* Services List */}
      <GlassCardContent>
        <div className="space-y-2">
          {host.services.map((service) => (
            <div
              key={service.name}
              className="flex items-center justify-between py-1.5 px-2 rounded-lg hover:bg-nothing-gray-100/50 transition-colors"
            >
              <div className="flex items-center gap-2">
                <StatusOrb status={mapServiceStatus(service.status)} size="sm" />
                <span className="font-mono text-sm text-nothing-gray-800">
                  {service.name}
                </span>
              </div>
              <div className="flex items-center gap-2">
                {service.port && (
                  <span className="text-xs text-nothing-gray-400 font-mono">
                    :{service.port}
                  </span>
                )}
                {service.latency_ms !== null && service.latency_ms !== undefined && (
                  <span
                    className={cn(
                      'text-xs font-mono',
                      service.latency_ms > 100
                        ? 'text-status-warning'
                        : 'text-nothing-gray-500'
                    )}
                  >
                    {service.latency_ms.toFixed(1)}ms
                  </span>
                )}
              </div>
            </div>
          ))}
        </div>

        {/* Metrics Bar */}
        {host.metrics && (
          <div className="mt-4 pt-3 border-t border-nothing-gray-100">
            <div className="grid grid-cols-2 gap-3">
              {/* CPU */}
              <MetricBar
                label={tDashboard('cpu')}
                value={host.metrics.cpu_percent}
                warningThreshold={60}
                criticalThreshold={80}
                collectingLabel={tDashboard('waitingData')}
                baselineValue={host.metrics.cpu_baseline?.baseline_value}
                baselineLabel={tDashboard('baseline')}
              />

              {/* Memory */}
              <MetricBar
                label={tDashboard('memory')}
                value={host.metrics.memory_percent}
                warningThreshold={70}
                criticalThreshold={85}
                collectingLabel={tDashboard('waitingData')}
                baselineValue={host.metrics.memory_baseline?.baseline_value}
                baselineLabel={tDashboard('baseline')}
              />
            </div>
          </div>
        )}
      </GlassCardContent>

      {/* Footer */}
      <GlassCardFooter>
        <div className="flex items-center justify-between">
          <StatusBadge status={overallStatus} label={statusLabel} size="sm" />
          <span className="text-xs text-nothing-gray-400 font-mono">
            {new Date(host.last_check).toLocaleTimeString('zh-TW', {
              hour: '2-digit',
              minute: '2-digit',
              second: '2-digit',
            })}
          </span>
        </div>
      </GlassCardFooter>
    </GlassCard>
  )
}

// =============================================================================
// Metric Bar Component
// =============================================================================

interface MetricBarProps {
  label: string
  value: number | null | undefined
  warningThreshold?: number
  criticalThreshold?: number
  collectingLabel?: string
  baselineValue?: number | null
  baselineLabel?: string
}

function MetricBar({
  label,
  value,
  warningThreshold = 60,
  criticalThreshold = 80,
  collectingLabel = '-',
  baselineValue,
  // Note: baselineLabel prop kept for future use but not used currently
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  baselineLabel,
}: MetricBarProps) {
  // Handle null/undefined values - show collecting state
  if (value === null || value === undefined) {
    return (
      <div className="p-3 rounded-xl bg-nothing-gray-50/50 border border-nothing-gray-100">
        <div className="flex items-center justify-between mb-2">
          <span className="text-[10px] text-nothing-gray-500 uppercase tracking-wider font-mono">{label}</span>
          <span className="text-xs font-mono text-nothing-gray-400 animate-pulse">
            {collectingLabel}
          </span>
        </div>
        <div className="h-2 bg-nothing-gray-100 rounded-full overflow-hidden">
          <div className="h-full w-1/4 bg-nothing-gray-200 rounded-full animate-shimmer bg-[length:200%_100%] bg-gradient-to-r from-nothing-gray-200 via-nothing-gray-100 to-nothing-gray-200" />
        </div>
      </div>
    )
  }

  const color =
    value >= criticalThreshold
      ? 'bg-gradient-to-r from-status-critical to-status-critical/80'
      : value >= warningThreshold
        ? 'bg-gradient-to-r from-status-warning to-status-warning/80'
        : 'bg-gradient-to-r from-status-healthy to-status-healthy/80'

  const glowColor =
    value >= criticalThreshold
      ? 'shadow-[0_0_10px_rgba(255,51,0,0.3)]'
      : value >= warningThreshold
        ? 'shadow-[0_0_10px_rgba(245,158,11,0.3)]'
        : ''

  return (
    <div className={cn(
      'p-3 rounded-xl border transition-all duration-300',
      value >= criticalThreshold
        ? 'bg-status-critical/5 border-status-critical/20'
        : value >= warningThreshold
          ? 'bg-status-warning/5 border-status-warning/20'
          : 'bg-nothing-gray-50/50 border-nothing-gray-100'
    )}>
      <div className="flex items-center justify-between mb-2">
        <div className="flex items-center gap-1.5">
          {label.toLowerCase().includes('cpu') ? (
            <Cpu className="w-3 h-3 text-nothing-gray-400" />
          ) : (
            <Gauge className="w-3 h-3 text-nothing-gray-400" />
          )}
          <span className="text-[10px] text-nothing-gray-500 uppercase tracking-wider font-mono">{label}</span>
        </div>
        <div className="flex items-center gap-1.5">
          <span
            className={cn(
              'text-sm font-mono font-bold tabular-nums',
              value >= criticalThreshold
                ? 'text-status-critical'
                : value >= warningThreshold
                  ? 'text-status-warning'
                  : 'text-nothing-gray-700'
            )}
          >
            {formatPercent(value)}
          </span>
          {/* Dynamic Baseline Display */}
          {baselineValue !== null && baselineValue !== undefined && (
            <span className="text-[9px] font-mono text-nothing-gray-300">
              ({formatPercent(baselineValue)})
            </span>
          )}
        </div>
      </div>
      <div className="h-2 bg-nothing-gray-100 rounded-full overflow-hidden">
        <div
          className={cn(
            'h-full rounded-full transition-all duration-500 ease-out',
            color,
            glowColor
          )}
          style={{ width: `${Math.min(value, 100)}%` }}
        />
      </div>
    </div>
  )
}
