import { useEffect, useMemo, useState } from 'react'
import { Server, Wifi, WifiOff, Trash2, ChevronDown, ChevronUp, RefreshCw, Cpu, MemoryStick, ArrowUp, ArrowDown, Pencil, BarChart2, CloudDownload, Copy, Check, Activity } from 'lucide-react'
import ContainerRow from './ContainerRow'
import { tagColor } from './TagInput'
import { IconButton, ProgressBar } from './ui/controls'
import { formatBps, formatRam, loadColor, loadBarColor } from '../lib/format'

/** Métrique système avec barre de progression (CPU, RAM). */
function Metric({ icon: Icon, label, percent: rawPercent, detail }) {
  const percent = Number.isFinite(rawPercent) ? rawPercent : 0
  return (
    <div className="flex-1 min-w-[130px]">
      <div className="flex items-center gap-1.5 text-xs text-gray-400 mb-1">
        <Icon size={11} className="text-indigo-400 flex-shrink-0" />
        <span>{label}</span>
        <span className={`font-medium tabular-nums ml-auto ${loadColor(percent)}`}>
          {percent.toFixed(percent >= 10 ? 0 : 1)} %
        </span>
      </div>
      <ProgressBar value={percent} barClass={loadBarColor(percent)} />
      {detail && <p className="text-[11px] text-gray-600 mt-1">{detail}</p>}
    </div>
  )
}

export default function VpsCard({ vps, query = '', onAction, onLogs, onDelete, onUpdate, onEdit, onStats, onUpdateAgent, onExport }) {
  const storageKey = `vps:${vps.id}:collapsed`
  const [collapsed, setCollapsed] = useState(() => localStorage.getItem(storageKey) === '1')
  const [updatingProject, setUpdatingProject] = useState(null)
  const [updatingAgent, setUpdatingAgent] = useState(false)
  const [exported, setExported] = useState(false)
  const [servicesExpanded, setServicesExpanded] = useState(false)

  useEffect(() => {
    localStorage.setItem(storageKey, collapsed ? '1' : '0')
  }, [storageKey, collapsed])

  const handleExport = async () => {
    const copied = await onExport(vps.id)
    if (!copied) return
    setExported(true)
    setTimeout(() => setExported(false), 2000)
  }

  const running = vps.containers.filter(c => c.status === 'running').length
  const total   = vps.containers.length

  // Quand une recherche est active, on n'affiche que les conteneurs concernés —
  // sauf si aucun ne correspond (le VPS est alors visible via son nom ou un tag).
  const visibleContainers = useMemo(() => {
    if (!query) return vps.containers
    const matching = vps.containers.filter(c =>
      [c.name, c.image, c.compose_project].filter(Boolean).some(v => v.toLowerCase().includes(query))
    )
    return matching.length > 0 ? matching : vps.containers
  }, [vps.containers, query])

  const hiddenCount = total - visibleContainers.length

  const composeProjects = [...new Set(vps.containers.map(c => c.compose_project).filter(Boolean))]

  const handleUpdate = async (project) => {
    setUpdatingProject(project)
    try { await onUpdate(vps.id, project) } finally { setUpdatingProject(null) }
  }

  const handleUpdateAgent = async () => {
    setUpdatingAgent(true)
    try { await onUpdateAgent(vps.id) } finally { setUpdatingAgent(false) }
  }

  return (
    <div className="bg-gray-900 border border-gray-800 rounded-xl overflow-hidden flex flex-col">
      {/* Header */}
      <div className="flex items-center gap-3 px-4 py-3 border-b border-gray-800">
        <div className={`p-2 rounded-lg flex-shrink-0 ${vps.online ? 'bg-emerald-500/10' : 'bg-red-500/10'}`}>
          <Server size={15} className={vps.online ? 'text-emerald-400' : 'text-red-400'} />
        </div>

        <div className="flex-1 min-w-0">
          <h3 className="font-semibold text-sm truncate">{vps.name}</h3>
          <p className="text-xs text-gray-500 truncate">{vps.host}</p>
        </div>

        <div className="flex items-center gap-1 flex-shrink-0">
          {vps.online ? (
            <span className="flex items-center gap-1.5 text-xs text-emerald-400 mr-1">
              <Wifi size={12} />
              <span className="hidden sm:inline whitespace-nowrap">{running}/{total} actifs</span>
            </span>
          ) : (
            <span className="flex items-center gap-1.5 text-xs text-red-400 mr-1">
              <WifiOff size={12} />
              <span className="hidden sm:inline">Hors ligne</span>
            </span>
          )}

          <IconButton
            icon={collapsed ? ChevronDown : ChevronUp}
            label={collapsed ? 'Déplier la carte' : 'Replier la carte'}
            aria-expanded={!collapsed}
            onClick={() => setCollapsed(c => !c)}
          />

          {vps.online && (
            <IconButton
              icon={BarChart2}
              label="Graphiques de performance"
              tone="accent"
              onClick={() => onStats(vps.id, vps.name)}
            />
          )}

          <IconButton
            icon={exported ? Check : Copy}
            label={exported ? 'Config copiée !' : 'Exporter la config (copier le JSON)'}
            tone={exported ? 'success' : 'default'}
            onClick={handleExport}
          />

          <IconButton icon={Pencil} label="Modifier ce VPS" onClick={() => onEdit(vps)} />
          <IconButton icon={Trash2} label="Supprimer ce VPS" tone="danger" onClick={() => onDelete(vps.id)} />
        </div>
      </div>

      {/* Erreur de connexion */}
      {!vps.online && vps.error && (
        <div className="px-4 py-2.5 bg-red-950/30 border-b border-red-900/30 text-xs text-red-400 font-mono break-words">
          {vps.error}
        </div>
      )}

      {/* Version de l'agent + bouton mise à jour */}
      {vps.online && (
        <div className="px-4 py-2 border-b border-gray-800/60 flex flex-wrap items-center gap-x-3 gap-y-2">
          <span className="text-xs text-gray-500">Agent&nbsp;:</span>
          {vps.agent_version ? (
            <span
              className={`inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium border ${
                vps.agent_up_to_date
                  ? 'bg-emerald-500/10 border-emerald-500/30 text-emerald-400'
                  : 'bg-orange-500/10 border-orange-500/30 text-orange-400'
              }`}
              title={vps.agent_up_to_date ? 'Agent à jour' : `Mise à jour disponible (attendu : ${vps.expected_agent_version})`}
            >
              {vps.agent_up_to_date ? '✓' : '⚠'} v{vps.agent_version}
            </span>
          ) : (
            <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium border bg-gray-700/30 border-gray-600/30 text-gray-500">
              inconnu
            </span>
          )}
          {(!vps.agent_up_to_date || vps.agent_version === 'unknown') && (
            <button
              onClick={handleUpdateAgent}
              disabled={updatingAgent}
              className="flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs bg-orange-500/10 border border-orange-500/30 text-orange-300 hover:bg-orange-500/30 hover:text-orange-100 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              title={`Mettre à jour l'agent vers v${vps.expected_agent_version}`}
            >
              <CloudDownload size={11} className={updatingAgent ? 'animate-bounce' : ''} />
              {updatingAgent ? 'Mise à jour...' : 'Mettre à jour l\'agent'}
            </button>
          )}
        </div>
      )}

      {/* Boutons de mise à jour par projet compose */}
      {vps.online && composeProjects.length > 0 && (
        <div className="px-4 py-2 border-b border-gray-800/60 flex flex-wrap gap-2">
          {composeProjects.map(project => (
            <button
              key={project}
              onClick={() => handleUpdate(project)}
              disabled={!!updatingProject}
              className="flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs bg-indigo-600/20 border border-indigo-500/30 text-indigo-300 hover:bg-indigo-600/40 hover:text-indigo-100 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              title={`docker compose pull && up -d (${project})`}
            >
              <RefreshCw size={11} className={updatingProject === project ? 'animate-spin' : ''} />
              Update {project}
            </button>
          ))}
        </div>
      )}

      {/* Informations système */}
      {vps.online && vps.system && !collapsed && (
        <div className="px-4 py-3 border-b border-gray-800/60 bg-gray-900/50 space-y-2.5">
          <div className="flex flex-wrap gap-4">
            <Metric
              icon={Cpu}
              label="CPU"
              percent={vps.system.cpu_percent}
            />
            <Metric
              icon={MemoryStick}
              label="RAM"
              percent={vps.system.ram_percent}
              detail={`${formatRam(vps.system.ram_used)} / ${formatRam(vps.system.ram_total)}`}
            />
          </div>
          <div className="flex items-center gap-4 text-xs text-gray-400">
            <span className="flex items-center gap-1" title="Débit sortant">
              <ArrowUp size={11} className="text-sky-400" />
              <span className="tabular-nums">{formatBps(vps.system.net_sent_per_sec)}</span>
            </span>
            <span className="flex items-center gap-1" title="Débit entrant">
              <ArrowDown size={11} className="text-violet-400" />
              <span className="tabular-nums">{formatBps(vps.system.net_recv_per_sec)}</span>
            </span>
          </div>
        </div>
      )}

      {/* Tags */}
      {vps.tags?.length > 0 && !collapsed && (
        <div className="px-4 py-2 border-b border-gray-800/60 flex flex-wrap gap-1.5">
          {vps.tags.map(tag => (
            <span
              key={tag}
              className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium border ${tagColor(tag)}`}
            >
              {tag}
            </span>
          ))}
        </div>
      )}

      {/* Description */}
      {vps.description && !collapsed && (
        <p className="px-4 py-2 text-xs text-gray-500 border-b border-gray-800/60">{vps.description}</p>
      )}

      {/* Services systemd */}
      {!collapsed && vps.online && vps.services?.length > 0 && (
        <div className="border-b border-gray-800/60">
          <button
            onClick={() => setServicesExpanded(e => !e)}
            aria-expanded={servicesExpanded}
            className="w-full flex items-center justify-between px-4 py-2 text-xs text-gray-400 hover:bg-gray-800/40 transition-colors"
          >
            <span className="flex items-center gap-1.5">
              <Activity size={11} className="text-indigo-400" />
              Services systemd
              <span className="ml-1 px-1.5 py-0.5 rounded-full bg-gray-800 text-gray-500 text-[10px]">
                {vps.services.filter(s => s.active === 'active').length}/{vps.services.length}
              </span>
              {vps.services.some(s => s.active === 'failed') && (
                <span className="ml-1 px-1.5 py-0.5 rounded-full bg-red-500/10 text-red-400 text-[10px]">
                  {vps.services.filter(s => s.active === 'failed').length} en échec
                </span>
              )}
            </span>
            {servicesExpanded ? <ChevronUp size={12} /> : <ChevronDown size={12} />}
          </button>
          {servicesExpanded && (
            <div className="divide-y divide-gray-800/40 max-h-64 overflow-y-auto">
              {vps.services.map(svc => {
                const isActive  = svc.active === 'active'
                const isFailed  = svc.active === 'failed'
                const dotColor  = isActive ? 'bg-emerald-400' : isFailed ? 'bg-red-400' : 'bg-gray-500'
                const nameColor = isActive ? 'text-gray-200' : isFailed ? 'text-red-400' : 'text-gray-500'
                return (
                  <div key={svc.name} className="flex items-center gap-2.5 px-4 py-1.5 hover:bg-gray-800/30">
                    <span className={`w-1.5 h-1.5 rounded-full flex-shrink-0 ${dotColor}`} />
                    <span className={`text-xs font-mono truncate flex-1 ${nameColor}`}>{svc.name}</span>
                    <span className={`text-[10px] px-1.5 py-0.5 rounded flex-shrink-0 ${
                      isActive  ? 'bg-emerald-500/10 text-emerald-400' :
                      isFailed  ? 'bg-red-500/10 text-red-400' :
                                  'bg-gray-700/40 text-gray-500'
                    }`}>{svc.sub}</span>
                  </div>
                )
              })}
            </div>
          )}
        </div>
      )}

      {/* Conteneurs */}
      {!collapsed && vps.online && (
        <div className="divide-y divide-gray-800/50 flex-1">
          {total === 0 ? (
            <p className="px-4 py-6 text-sm text-gray-600 text-center">Aucun conteneur détecté.</p>
          ) : (
            <>
              {hiddenCount > 0 && (
                <p className="px-4 py-1.5 text-[11px] text-gray-600 bg-gray-800/20">
                  {hiddenCount} conteneur{hiddenCount > 1 ? 's' : ''} masqué{hiddenCount > 1 ? 's' : ''} par la recherche
                </p>
              )}
              {visibleContainers.map(c => (
                <ContainerRow
                  key={c.id}
                  container={c}
                  onAction={(action) => onAction(vps.id, c.id, action)}
                  onLogs={() => onLogs(vps.id, c.id, `${vps.name} / ${c.name}`)}
                />
              ))}
            </>
          )}
        </div>
      )}

      {/* Footer stats */}
      {!collapsed && vps.online && total > 0 && (
        <div className="px-4 py-2 border-t border-gray-800/60 flex gap-4 text-xs text-gray-600">
          <span><span className="text-emerald-500">{running}</span> en cours</span>
          <span><span className="text-gray-400">{total - running}</span> arrêtés</span>
          <span><span className="text-gray-400">{total}</span> total</span>
        </div>
      )}
    </div>
  )
}
