'use client'

import { useState, useEffect, useRef } from 'react'
import { useParams, useRouter } from 'next/navigation'
import Link from 'next/link'
import {
  RadialBarChart,
  RadialBar,
  AreaChart,
  Area,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts'
import {
  ArrowLeft,
  Play,
  Square,
  RefreshCw,
  Trash2,
  Cpu,
  MemoryStick,
  Network,
  Clock,
  Container,
  Loader2,
  AlertCircle,
  Terminal,
  Info,
  Activity,
  Gauge,
  ArrowDownToLine,
  ArrowUpFromLine,
  Server,
  Globe,
  Key,
  Layers,
  RotateCcw,
  Copy,
  Check,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import {
  useContainerDetails,
  useSingleContainerStats,
  useContainerLogs,
  useContainerAction,
  useRemoveContainer,
  type ContainerStats,
} from '@/hooks/use-portainer'

const MAX_HISTORY_POINTS = 60

interface StatsHistory {
  timestamp: number
  cpu: number
  memory: number
  memoryPercent: number
  networkRx: number
  networkTx: number
}

function formatBytes(bytes: number): string {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`
}

function formatDate(dateStr: string | number): string {
  const date = typeof dateStr === 'number' ? new Date(dateStr * 1000) : new Date(dateStr)
  return date.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  })
}

// Gauge Chart Component using Recharts
function GaugeChart({
  value,
  color = '#3b82f6',
  bgColor = '#e2e8f0',
  size = 100,
}: {
  value: number
  color?: string
  bgColor?: string
  size?: number
}) {
  const data = [
    { name: 'value', value: Math.min(value, 100), fill: color },
    { name: 'background', value: 100 - Math.min(value, 100), fill: bgColor },
  ]

  return (
    <div style={{ width: size, height: size }}>
      <ResponsiveContainer width="100%" height="100%">
        <RadialBarChart
          cx="50%"
          cy="50%"
          innerRadius="70%"
          outerRadius="100%"
          barSize={10}
          data={data}
          startAngle={90}
          endAngle={-270}
        >
          <RadialBar
            background={false}
            dataKey="value"
            cornerRadius={10}
          />
        </RadialBarChart>
      </ResponsiveContainer>
    </div>
  )
}

// Sparkline Area Chart Component using Recharts
function SparklineChart({
  data,
  color = '#3b82f6',
  gradientId,
}: {
  data: number[]
  color?: string
  gradientId: string
}) {
  if (data.length < 2) {
    return (
      <div className="h-full flex items-center justify-center text-muted-foreground text-xs">
        Collecting data...
      </div>
    )
  }

  // Convert number array to chart data format
  const chartData = data.map((value, index) => ({
    index,
    value,
  }))

  return (
    <ResponsiveContainer width="100%" height="100%">
      <AreaChart data={chartData} margin={{ top: 0, right: 0, left: 0, bottom: 0 }}>
        <defs>
          <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={color} stopOpacity={0.4} />
            <stop offset="100%" stopColor={color} stopOpacity={0.05} />
          </linearGradient>
        </defs>
        <Area
          type="monotone"
          dataKey="value"
          stroke={color}
          strokeWidth={2}
          fill={`url(#${gradientId})`}
          isAnimationActive={false}
        />
      </AreaChart>
    </ResponsiveContainer>
  )
}

// Status indicator dot
function StatusDot({ status }: { status: string }) {
  const colors: Record<string, string> = {
    running: 'bg-emerald-500',
    exited: 'bg-red-500',
    paused: 'bg-amber-500',
    restarting: 'bg-blue-500',
    created: 'bg-slate-400',
  }
  const pulseColors: Record<string, string> = {
    running: 'bg-emerald-400',
    restarting: 'bg-blue-400',
  }
  const shouldPulse = status === 'running' || status === 'restarting'

  return (
    <span className="relative flex h-3 w-3">
      {shouldPulse && (
        <span className={`animate-ping absolute inline-flex h-full w-full rounded-full ${pulseColors[status] || ''} opacity-75`} />
      )}
      <span className={`relative inline-flex rounded-full h-3 w-3 ${colors[status.toLowerCase()] || 'bg-slate-400'}`} />
    </span>
  )
}

// Copy button component
function CopyButton({ text }: { text: string }) {
  const [copied, setCopied] = useState(false)

  const handleCopy = async () => {
    await navigator.clipboard.writeText(text)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  return (
    <button
      onClick={handleCopy}
      className="p-1 rounded hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors"
      title="Copy to clipboard"
    >
      {copied ? <Check className="h-3.5 w-3.5 text-emerald-500" /> : <Copy className="h-3.5 w-3.5 text-muted-foreground" />}
    </button>
  )
}

export default function ContainerDetailPage() {
  const params = useParams()
  const router = useRouter()
  const orderId = params.id as string
  const containerId = params.containerId as string

  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
  const [actionInProgress, setActionInProgress] = useState(false)
  const [activeTab, setActiveTab] = useState<'overview' | 'logs' | 'env'>('overview')
  const [logTail, setLogTail] = useState(500)
  const [statsHistory, setStatsHistory] = useState<StatsHistory[]>([])
  const lastStatsRef = useRef<ContainerStats | null>(null)

  const { data: container, isLoading, error } = useContainerDetails(orderId, containerId)
  const { data: stats } = useSingleContainerStats(orderId, containerId, container?.state === 'running')
  const { data: logs, refetch: refetchLogs } = useContainerLogs(orderId, containerId, logTail)
  const containerAction = useContainerAction()
  const removeContainer = useRemoveContainer()

  // Track stats history
  useEffect(() => {
    if (stats && stats !== lastStatsRef.current) {
      lastStatsRef.current = stats
      setStatsHistory(prev => {
        const newHistory = [...prev, {
          timestamp: Date.now(),
          cpu: stats.cpuPercent,
          memory: stats.memoryUsage,
          memoryPercent: stats.memoryPercent,
          networkRx: stats.networkRx,
          networkTx: stats.networkTx,
        }]
        if (newHistory.length > MAX_HISTORY_POINTS) {
          return newHistory.slice(-MAX_HISTORY_POINTS)
        }
        return newHistory
      })
    }
  }, [stats])

  const handleAction = async (action: 'start' | 'stop' | 'restart') => {
    setActionInProgress(true)
    try {
      await containerAction.mutateAsync({ orderId, containerId, action })
    } catch (err) {
      console.error(`Failed to ${action} container:`, err)
    } finally {
      setActionInProgress(false)
    }
  }

  const handleDelete = async () => {
    setActionInProgress(true)
    try {
      await removeContainer.mutateAsync({ orderId, containerId, force: true })
      router.push(`/admin/orders/${orderId}`)
    } catch (err) {
      console.error('Failed to remove container:', err)
    } finally {
      setActionInProgress(false)
      setShowDeleteConfirm(false)
    }
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-slate-50 dark:bg-slate-900">
        <div className="text-center">
          <Loader2 className="h-10 w-10 animate-spin text-blue-500 mx-auto" />
          <p className="mt-4 text-muted-foreground">Loading container...</p>
        </div>
      </div>
    )
  }

  if (error || !container) {
    return (
      <div className="min-h-screen bg-slate-50 dark:bg-slate-900 p-6">
        <div className="max-w-lg mx-auto mt-20">
          <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-lg p-8 text-center">
            <div className="w-16 h-16 bg-red-100 dark:bg-red-900/30 rounded-full flex items-center justify-center mx-auto">
              <AlertCircle className="h-8 w-8 text-red-500" />
            </div>
            <h2 className="mt-4 text-xl font-semibold">Failed to load container</h2>
            <p className="mt-2 text-muted-foreground">{error?.message || 'Container not found'}</p>
            <Button variant="outline" className="mt-6" onClick={() => router.back()}>
              <ArrowLeft className="h-4 w-4 mr-2" />
              Go Back
            </Button>
          </div>
        </div>
      </div>
    )
  }

  const cpuHistory = statsHistory.map(s => s.cpu)
  const memoryHistory = statsHistory.map(s => s.memoryPercent)
  const isRunning = container.state === 'running'

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 dark:from-slate-900 dark:to-slate-800">
      {/* Header */}
      <div className="bg-white dark:bg-slate-800 border-b border-slate-200 dark:border-slate-700 sticky top-0 z-10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="py-4">
            <Link href={`/admin/orders/${orderId}`} className="inline-flex items-center text-sm text-muted-foreground hover:text-foreground transition-colors">
              <ArrowLeft className="h-4 w-4 mr-1" />
              Back to Order
            </Link>
          </div>
          <div className="pb-6 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
            <div className="flex items-center gap-4">
              <div className="w-14 h-14 rounded-2xl bg-gradient-to-br from-blue-500 to-indigo-600 flex items-center justify-center shadow-lg shadow-blue-500/25">
                <Container className="h-7 w-7 text-white" />
              </div>
              <div>
                <div className="flex items-center gap-3">
                  <h1 className="text-2xl font-bold text-slate-900 dark:text-white">{container.name}</h1>
                  <div className="flex items-center gap-2 px-3 py-1 rounded-full bg-slate-100 dark:bg-slate-700">
                    <StatusDot status={container.state} />
                    <span className="text-sm font-medium capitalize">{container.state}</span>
                  </div>
                </div>
                <p className="mt-1 text-sm text-muted-foreground font-mono">{container.shortId}</p>
              </div>
            </div>
            <div className="flex items-center gap-2">
              {actionInProgress ? (
                <div className="flex items-center gap-2 px-4 py-2 bg-slate-100 dark:bg-slate-700 rounded-lg">
                  <Loader2 className="h-4 w-4 animate-spin" />
                  <span className="text-sm">Processing...</span>
                </div>
              ) : (
                <>
                  {isRunning ? (
                    <Button variant="outline" size="sm" onClick={() => handleAction('stop')} className="gap-2">
                      <Square className="h-4 w-4" />
                      Stop
                    </Button>
                  ) : (
                    <Button size="sm" onClick={() => handleAction('start')} className="gap-2 bg-emerald-600 hover:bg-emerald-700">
                      <Play className="h-4 w-4" />
                      Start
                    </Button>
                  )}
                  <Button variant="outline" size="sm" onClick={() => handleAction('restart')} className="gap-2">
                    <RotateCcw className="h-4 w-4" />
                    Restart
                  </Button>
                  <Button variant="outline" size="sm" onClick={() => setShowDeleteConfirm(true)} className="gap-2 text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-950">
                    <Trash2 className="h-4 w-4" />
                    Remove
                  </Button>
                </>
              )}
            </div>
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Stats Cards */}
        {isRunning && stats && (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            {/* CPU Card */}
            <div className="bg-white dark:bg-slate-800 rounded-2xl p-6 shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden">
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-xl bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center">
                    <Cpu className="h-5 w-5 text-blue-600" />
                  </div>
                  <div>
                    <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">CPU Usage</p>
                    <p className="text-2xl font-bold text-slate-900 dark:text-white">
                      {stats.cpuPercent < 0.1 && stats.cpuPercent > 0
                        ? stats.cpuPercent.toFixed(2)
                        : stats.cpuPercent.toFixed(1)}%
                    </p>
                  </div>
                </div>
              </div>
              <div className="relative">
                <div className="flex items-center justify-center mb-4">
                  <GaugeChart value={stats.cpuPercent} color="#3b82f6" bgColor="#e2e8f0" size={100} />
                </div>
                <div className="h-16">
                  <SparklineChart data={cpuHistory} color="#3b82f6" gradientId="cpu-gradient-order" />
                </div>
              </div>
            </div>

            {/* Memory Card */}
            <div className="bg-white dark:bg-slate-800 rounded-2xl p-6 shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden">
              <div className="flex items-center justify-between mb-4">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-xl bg-emerald-100 dark:bg-emerald-900/30 flex items-center justify-center">
                    <MemoryStick className="h-5 w-5 text-emerald-600" />
                  </div>
                  <div>
                    <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Memory</p>
                    <p className="text-2xl font-bold text-slate-900 dark:text-white">{stats.memoryPercent.toFixed(1)}%</p>
                  </div>
                </div>
              </div>
              <div className="relative">
                <div className="flex items-center justify-center mb-4">
                  <GaugeChart value={stats.memoryPercent} color="#10b981" bgColor="#e2e8f0" size={100} />
                </div>
                <p className="text-xs text-center text-muted-foreground mb-2">
                  {formatBytes(stats.memoryUsage)} / {formatBytes(stats.memoryLimit)}
                </p>
                <div className="h-16">
                  <SparklineChart data={memoryHistory} color="#10b981" gradientId="memory-gradient-order" />
                </div>
              </div>
            </div>

            {/* Network RX Card */}
            <div className="bg-white dark:bg-slate-800 rounded-2xl p-6 shadow-sm border border-slate-200 dark:border-slate-700">
              <div className="flex items-center gap-3 mb-4">
                <div className="w-10 h-10 rounded-xl bg-violet-100 dark:bg-violet-900/30 flex items-center justify-center">
                  <ArrowDownToLine className="h-5 w-5 text-violet-600" />
                </div>
                <div>
                  <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Network In</p>
                  <p className="text-2xl font-bold text-slate-900 dark:text-white">{formatBytes(stats.networkRx)}</p>
                </div>
              </div>
              <div className="flex items-center justify-center py-6">
                <div className="relative">
                  <div className="w-20 h-20 rounded-full border-4 border-violet-100 dark:border-violet-900/30 flex items-center justify-center">
                    <ArrowDownToLine className="h-8 w-8 text-violet-500 animate-pulse" />
                  </div>
                  <div className="absolute -right-1 -bottom-1 w-8 h-8 rounded-full bg-violet-500 flex items-center justify-center">
                    <Activity className="h-4 w-4 text-white" />
                  </div>
                </div>
              </div>
            </div>

            {/* Network TX Card */}
            <div className="bg-white dark:bg-slate-800 rounded-2xl p-6 shadow-sm border border-slate-200 dark:border-slate-700">
              <div className="flex items-center gap-3 mb-4">
                <div className="w-10 h-10 rounded-xl bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center">
                  <ArrowUpFromLine className="h-5 w-5 text-amber-600" />
                </div>
                <div>
                  <p className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Network Out</p>
                  <p className="text-2xl font-bold text-slate-900 dark:text-white">{formatBytes(stats.networkTx)}</p>
                </div>
              </div>
              <div className="flex items-center justify-center py-6">
                <div className="relative">
                  <div className="w-20 h-20 rounded-full border-4 border-amber-100 dark:border-amber-900/30 flex items-center justify-center">
                    <ArrowUpFromLine className="h-8 w-8 text-amber-500 animate-pulse" />
                  </div>
                  <div className="absolute -right-1 -bottom-1 w-8 h-8 rounded-full bg-amber-500 flex items-center justify-center">
                    <Activity className="h-4 w-4 text-white" />
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Not Running State */}
        {!isRunning && (
          <div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-2xl p-6 mb-8">
            <div className="flex items-center gap-4">
              <div className="w-12 h-12 rounded-xl bg-amber-100 dark:bg-amber-900/30 flex items-center justify-center">
                <AlertCircle className="h-6 w-6 text-amber-600" />
              </div>
              <div>
                <h3 className="font-semibold text-amber-800 dark:text-amber-200">Container is not running</h3>
                <p className="text-sm text-amber-600 dark:text-amber-400">Start the container to view live resource metrics</p>
              </div>
              <Button size="sm" onClick={() => handleAction('start')} className="ml-auto gap-2 bg-amber-600 hover:bg-amber-700">
                <Play className="h-4 w-4" />
                Start Container
              </Button>
            </div>
          </div>
        )}

        {/* Tabs */}
        <div className="bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden">
          <div className="border-b border-slate-200 dark:border-slate-700">
            <nav className="flex">
              {[
                { id: 'overview', label: 'Overview', icon: Info },
                { id: 'logs', label: 'Logs', icon: Terminal },
                { id: 'env', label: 'Environment', icon: Key },
              ].map((tab) => (
                <button
                  key={tab.id}
                  onClick={() => setActiveTab(tab.id as typeof activeTab)}
                  className={`flex items-center gap-2 px-6 py-4 text-sm font-medium border-b-2 transition-colors ${
                    activeTab === tab.id
                      ? 'border-blue-500 text-blue-600 dark:text-blue-400'
                      : 'border-transparent text-muted-foreground hover:text-foreground hover:border-slate-300'
                  }`}
                >
                  <tab.icon className="h-4 w-4" />
                  {tab.label}
                </button>
              ))}
            </nav>
          </div>

          {/* Overview Tab */}
          {activeTab === 'overview' && (
            <div className="p-6">
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {/* Container Info */}
                <div className="space-y-6">
                  <div>
                    <h3 className="text-lg font-semibold mb-4 flex items-center gap-2">
                      <Server className="h-5 w-5 text-muted-foreground" />
                      Container Details
                    </h3>
                    <div className="space-y-4">
                      <div className="flex items-start justify-between py-3 border-b border-slate-100 dark:border-slate-700">
                        <span className="text-sm text-muted-foreground">Image</span>
                        <div className="flex items-center gap-2">
                          <span className="text-sm font-mono text-right max-w-xs truncate">{container.image}</span>
                          <CopyButton text={container.image} />
                        </div>
                      </div>
                      <div className="flex items-center justify-between py-3 border-b border-slate-100 dark:border-slate-700">
                        <span className="text-sm text-muted-foreground">Container ID</span>
                        <div className="flex items-center gap-2">
                          <span className="text-sm font-mono">{container.id.substring(0, 24)}...</span>
                          <CopyButton text={container.id} />
                        </div>
                      </div>
                      <div className="flex items-center justify-between py-3 border-b border-slate-100 dark:border-slate-700">
                        <span className="text-sm text-muted-foreground">Created</span>
                        <span className="text-sm">{formatDate(container.created)}</span>
                      </div>
                      <div className="flex items-center justify-between py-3 border-b border-slate-100 dark:border-slate-700">
                        <span className="text-sm text-muted-foreground">Hostname</span>
                        <span className="text-sm font-mono">{container.config?.hostname || '-'}</span>
                      </div>
                      <div className="flex items-center justify-between py-3 border-b border-slate-100 dark:border-slate-700">
                        <span className="text-sm text-muted-foreground">Working Dir</span>
                        <span className="text-sm font-mono">{container.config?.workingDir || '/'}</span>
                      </div>
                      <div className="flex items-center justify-between py-3">
                        <span className="text-sm text-muted-foreground">Restart Policy</span>
                        <Badge variant="secondary" className="font-mono">
                          {container.hostConfig?.restartPolicy?.Name || 'no'}
                        </Badge>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Networking */}
                <div className="space-y-6">
                  {/* Ports */}
                  <div>
                    <h3 className="text-lg font-semibold mb-4 flex items-center gap-2">
                      <Globe className="h-5 w-5 text-muted-foreground" />
                      Port Mappings
                    </h3>
                    {container.ports && container.ports.length > 0 ? (
                      <div className="space-y-2">
                        {container.ports.map((port, idx) => (
                          <div key={idx} className="flex items-center gap-3 p-3 bg-slate-50 dark:bg-slate-700/50 rounded-lg">
                            <div className="w-8 h-8 rounded-lg bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center">
                              <Network className="h-4 w-4 text-blue-600" />
                            </div>
                            <div className="flex items-center gap-2 font-mono text-sm">
                              {port.public ? (
                                <>
                                  <span className="text-emerald-600 font-semibold">{port.public}</span>
                                  <span className="text-muted-foreground">:</span>
                                  <span>{port.private}</span>
                                </>
                              ) : (
                                <span className="text-muted-foreground">{port.private} (not published)</span>
                              )}
                              <Badge variant="outline" className="ml-2 text-xs">
                                {port.type}
                              </Badge>
                            </div>
                          </div>
                        ))}
                      </div>
                    ) : (
                      <div className="text-sm text-muted-foreground p-4 bg-slate-50 dark:bg-slate-700/50 rounded-lg text-center">
                        No ports exposed
                      </div>
                    )}
                  </div>

                  {/* Networks */}
                  <div>
                    <h3 className="text-lg font-semibold mb-4 flex items-center gap-2">
                      <Layers className="h-5 w-5 text-muted-foreground" />
                      Networks
                    </h3>
                    {container.networks && Object.keys(container.networks).length > 0 ? (
                      <div className="space-y-2">
                        {Object.entries(container.networks).map(([name, network]) => (
                          <div key={name} className="flex items-center justify-between p-3 bg-slate-50 dark:bg-slate-700/50 rounded-lg">
                            <span className="font-medium text-sm">{name}</span>
                            <div className="flex items-center gap-2">
                              <span className="text-sm font-mono text-muted-foreground">
                                {network.IPAddress || 'No IP assigned'}
                              </span>
                              {network.IPAddress && <CopyButton text={network.IPAddress} />}
                            </div>
                          </div>
                        ))}
                      </div>
                    ) : (
                      <div className="text-sm text-muted-foreground p-4 bg-slate-50 dark:bg-slate-700/50 rounded-lg text-center">
                        No networks attached
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Logs Tab */}
          {activeTab === 'logs' && (
            <div className="p-6">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-lg font-semibold flex items-center gap-2">
                  <Terminal className="h-5 w-5 text-muted-foreground" />
                  Container Logs
                </h3>
                <div className="flex items-center gap-3">
                  <select
                    value={logTail}
                    onChange={(e) => setLogTail(parseInt(e.target.value, 10))}
                    className="h-9 px-3 rounded-lg border border-slate-200 dark:border-slate-600 bg-white dark:bg-slate-700 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value={100}>Last 100 lines</option>
                    <option value={500}>Last 500 lines</option>
                    <option value={1000}>Last 1000 lines</option>
                    <option value={2000}>Last 2000 lines</option>
                  </select>
                  <Button variant="outline" size="sm" onClick={() => refetchLogs()} className="gap-2">
                    <RefreshCw className="h-4 w-4" />
                    Refresh
                  </Button>
                </div>
              </div>
              <div className="relative rounded-xl overflow-hidden border border-slate-200 dark:border-slate-700">
                <div className="absolute top-0 left-0 right-0 h-8 bg-gradient-to-b from-slate-900 to-transparent z-10 pointer-events-none" />
                <div className="h-[600px] overflow-auto bg-slate-900">
                  <pre className="p-6 text-sm font-mono text-slate-300 whitespace-pre-wrap break-all leading-relaxed">
                    {logs || 'No logs available'}
                  </pre>
                </div>
                <div className="absolute bottom-0 left-0 right-0 h-8 bg-gradient-to-t from-slate-900 to-transparent pointer-events-none" />
              </div>
            </div>
          )}

          {/* Environment Tab */}
          {activeTab === 'env' && (
            <div className="p-6">
              <h3 className="text-lg font-semibold mb-4 flex items-center gap-2">
                <Key className="h-5 w-5 text-muted-foreground" />
                Environment Variables
                <Badge variant="secondary" className="ml-2">
                  {container.config?.env?.length || 0}
                </Badge>
              </h3>
              {container.config?.env && container.config.env.length > 0 ? (
                <div className="rounded-xl border border-slate-200 dark:border-slate-700 overflow-hidden">
                  <div className="max-h-[600px] overflow-auto">
                    <table className="w-full">
                      <thead className="bg-slate-50 dark:bg-slate-700/50 sticky top-0">
                        <tr>
                          <th className="text-left text-xs font-semibold text-muted-foreground uppercase tracking-wider px-4 py-3">Key</th>
                          <th className="text-left text-xs font-semibold text-muted-foreground uppercase tracking-wider px-4 py-3">Value</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-slate-100 dark:divide-slate-700">
                        {container.config.env.map((env, idx) => {
                          const [key, ...valueParts] = env.split('=')
                          const value = valueParts.join('=')
                          const isSecret = key.toLowerCase().includes('password') ||
                                          key.toLowerCase().includes('secret') ||
                                          key.toLowerCase().includes('key') ||
                                          key.toLowerCase().includes('token')
                          return (
                            <tr key={idx} className="hover:bg-slate-50 dark:hover:bg-slate-700/30">
                              <td className="px-4 py-3">
                                <code className="text-sm text-blue-600 dark:text-blue-400">{key}</code>
                              </td>
                              <td className="px-4 py-3">
                                <div className="flex items-center gap-2">
                                  <code className="text-sm text-slate-600 dark:text-slate-300 break-all">
                                    {isSecret ? '••••••••' : value || <span className="text-muted-foreground italic">empty</span>}
                                  </code>
                                  {!isSecret && value && <CopyButton text={value} />}
                                </div>
                              </td>
                            </tr>
                          )
                        })}
                      </tbody>
                    </table>
                  </div>
                </div>
              ) : (
                <div className="text-sm text-muted-foreground p-8 bg-slate-50 dark:bg-slate-700/50 rounded-xl text-center">
                  No environment variables configured
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {/* Delete Confirmation Dialog */}
      <Dialog open={showDeleteConfirm} onOpenChange={setShowDeleteConfirm}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <div className="w-12 h-12 rounded-full bg-red-100 dark:bg-red-900/30 flex items-center justify-center mx-auto mb-4">
              <Trash2 className="h-6 w-6 text-red-600" />
            </div>
            <DialogTitle className="text-center">Remove Container</DialogTitle>
            <DialogDescription className="text-center">
              Are you sure you want to remove <span className="font-semibold">{container.name}</span>? This action cannot be undone.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="sm:justify-center gap-2 mt-4">
            <Button variant="outline" onClick={() => setShowDeleteConfirm(false)}>
              Cancel
            </Button>
            <Button variant="destructive" onClick={handleDelete} disabled={actionInProgress}>
              {actionInProgress && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Remove Container
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
