import { useMemo, useState } from 'react'
import { Play, Square, RotateCcw, FileText, Loader2, Heart } from 'lucide-react'
import StatusBadge from './StatusBadge'

const HEALTH_STYLES = {
  healthy:   { text: 'text-emerald-400', bg: 'bg-emerald-500/10 border-emerald-500/20', label: 'healthy' },
  unhealthy: { text: 'text-red-400',     bg: 'bg-red-500/10 border-red-500/20',         label: 'unhealthy' },
  starting:  { text: 'text-yellow-400',  bg: 'bg-yellow-500/10 border-yellow-500/20',   label: 'starting' },
}

function HealthBadge({ health }) {
  const s = HEALTH_STYLES[health]
  if (!s) return null
  return (
    <span className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full text-xs font-medium border ${s.bg} ${s.text}`}>
      <Heart size={9} className="flex-shrink-0" />
      {s.label}
    </span>
  )
}

/** Ports hôte exposés, dédoublonnés et triés. */
function hostPorts(ports) {
  const found = new Set()
  Object.values(ports ?? {}).forEach(bindings => {
    (bindings ?? []).forEach(b => { if (b?.HostPort) found.add(b.HostPort) })
  })
  return [...found].sort((a, b) => Number(a) - Number(b))
}

export default function ContainerRow({ container, onAction, onLogs }) {
  const [pending, setPending] = useState(null)
  const isRunning = container.status === 'running'
  const ports     = useMemo(() => hostPorts(container.ports), [container.ports])

  const handle = async (action) => {
    setPending(action)
    try { await onAction(action) } finally { setPending(null) }
  }

  const createdLabel = container.created
    ? `Créé le ${new Date(container.created).toLocaleString('fr-FR')}`
    : undefined

  return (
    <div className="flex items-center justify-between px-4 py-2.5 hover:bg-gray-800/40 transition-colors group">
      <div className="min-w-0 flex-1 pr-3">
        <div className="flex items-center gap-2 flex-wrap">
          <span className="text-sm font-medium truncate max-w-[160px]" title={createdLabel}>
            {container.name}
          </span>
          <StatusBadge status={container.status} />
          <HealthBadge health={container.health} />
          {container.compose_project && (
            <span className="hidden sm:inline text-xs text-gray-600 bg-gray-800 px-1.5 py-0.5 rounded">
              {container.compose_project}
            </span>
          )}
          {ports.slice(0, 3).map(port => (
            <span
              key={port}
              className="text-[10px] font-mono text-sky-300/80 bg-sky-500/10 border border-sky-500/20 px-1.5 py-0.5 rounded"
              title={`Port hôte ${port}`}
            >
              :{port}
            </span>
          ))}
          {ports.length > 3 && (
            <span className="text-[10px] text-gray-600" title={ports.join(', ')}>
              +{ports.length - 3}
            </span>
          )}
        </div>
        <p className="text-xs text-gray-500 truncate mt-0.5" title={container.image}>{container.image}</p>
      </div>

      {/* Toujours visibles sur mobile (pas de survol au tactile), révélées au
          survol ou au focus clavier sur grand écran. */}
      <div className="flex items-center gap-0.5 flex-shrink-0 transition-opacity
                      sm:opacity-0 sm:group-hover:opacity-100 sm:group-focus-within:opacity-100">
        {!isRunning && (
          <ActionBtn title={`Démarrer ${container.name}`} onClick={() => handle('start')} loading={pending === 'start'}>
            <Play size={13} />
          </ActionBtn>
        )}
        {isRunning && (
          <ActionBtn title={`Arrêter ${container.name}`} onClick={() => handle('stop')} loading={pending === 'stop'} danger>
            <Square size={13} />
          </ActionBtn>
        )}
        <ActionBtn title={`Redémarrer ${container.name}`} onClick={() => handle('restart')} loading={pending === 'restart'}>
          <RotateCcw size={13} />
        </ActionBtn>
        <ActionBtn title={`Logs de ${container.name}`} onClick={onLogs}>
          <FileText size={13} />
        </ActionBtn>
      </div>
    </div>
  )
}

function ActionBtn({ children, onClick, title, danger = false, loading = false }) {
  return (
    <button
      onClick={onClick}
      title={title}
      aria-label={title}
      disabled={loading}
      className={`p-1.5 rounded transition-colors disabled:opacity-40 ${
        danger
          ? 'hover:bg-red-500/20 text-gray-500 hover:text-red-400'
          : 'hover:bg-gray-700 text-gray-500 hover:text-gray-200'
      }`}
    >
      {loading ? <Loader2 size={13} className="animate-spin" /> : children}
    </button>
  )
}
