'use client'

import { useState } from 'react'
import Link from 'next/link'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import {
  Loader2,
  Server,
  Power,
  PowerOff,
  RefreshCw,
  CheckCircle,
  Wrench,
  HardDrive,
  Cpu,
  MemoryStick,
  ChevronDown,
  ChevronUp,
  Activity,
  Camera,
  Trash2,
  RotateCcw,
  Plus,
  Network,
  Download,
  Upload,
  Eye,
  Globe,
  Copy,
  Check,
  Clock,
  ServerCrash,
} from 'lucide-react'
import {
  useNetcupServers,
  useNetcupAuth,
  useNetcupPowerAction,
  useNetcupRescue,
  useServerMetrics,
  useServerSnapshots,
  useCreateSnapshot,
  useDeleteSnapshot,
  useRevertSnapshot,
  isServerReinstalling,
  PowerAction,
  NetcupServer,
} from '@/hooks/use-netcup'
import { NetcupAuthSetup } from '@/components/admin/netcup-auth-setup'

const stateConfig: Record<
  string,
  { label: string; bgColor: string; textColor: string; borderColor: string; dotColor: string; icon: typeof Power; animate?: boolean }
> = {
  ON: { label: 'Online', bgColor: 'bg-emerald-50', textColor: 'text-emerald-700', borderColor: 'border-emerald-200', dotColor: 'bg-emerald-500', icon: CheckCircle },
  OFF: { label: 'Offline', bgColor: 'bg-slate-50', textColor: 'text-slate-600', borderColor: 'border-slate-200', dotColor: 'bg-slate-400', icon: PowerOff },
  POWERCYCLE: { label: 'Restarting', bgColor: 'bg-amber-50', textColor: 'text-amber-700', borderColor: 'border-amber-200', dotColor: 'bg-amber-500', icon: RefreshCw, animate: true },
  RESET: { label: 'Hard Resetting', bgColor: 'bg-orange-50', textColor: 'text-orange-700', borderColor: 'border-orange-200', dotColor: 'bg-orange-500', icon: RefreshCw, animate: true },
  POWEROFF: { label: 'Shutting Down', bgColor: 'bg-orange-50', textColor: 'text-orange-700', borderColor: 'border-orange-200', dotColor: 'bg-orange-500', icon: PowerOff, animate: true },
  REINSTALLING: { label: 'Reinstalling', bgColor: 'bg-violet-50', textColor: 'text-violet-700', borderColor: 'border-violet-200', dotColor: 'bg-violet-500', icon: RefreshCw, animate: true },
  UNKNOWN: { label: 'Unknown', bgColor: 'bg-slate-50', textColor: 'text-slate-500', borderColor: 'border-slate-200', dotColor: 'bg-slate-300', icon: Server },
}

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(2)) + ' ' + sizes[i]
}

function formatBytesPerSec(bps: number): string {
  return formatBytes(bps) + '/s'
}

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

  const handleCopy = async (e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()
    await navigator.clipboard.writeText(text)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  return (
    <button
      onClick={handleCopy}
      className={`inline-flex items-center justify-center h-6 w-6 rounded-md transition-all ${
        copied
          ? 'bg-emerald-100 text-emerald-600 dark:bg-emerald-900/30 dark:text-emerald-400'
          : 'hover:bg-muted text-muted-foreground hover:text-foreground'
      }`}
      title={copied ? 'Copied!' : 'Copy to clipboard'}
    >
      {copied ? (
        <Check className="h-3 w-3" />
      ) : (
        <Copy className="h-3 w-3" />
      )}
    </button>
  )
}

function MetricsBar({ value, max = 100, label, gradient }: {
  value: number
  max?: number
  label: string
  gradient?: string
}) {
  const percentage = Math.min((value / max) * 100, 100)

  const getThresholdColor = () => {
    if (percentage > 90) return 'bg-gradient-to-r from-red-500 to-red-600'
    if (percentage > 75) return 'bg-gradient-to-r from-amber-500 to-orange-500'
    return gradient || 'bg-gradient-to-r from-blue-500 to-blue-600'
  }

  return (
    <div className="space-y-1.5">
      <div className="flex justify-between items-center">
        <span className="text-xs text-muted-foreground">{label}</span>
        <span className="text-xs font-semibold tabular-nums">{value.toFixed(1)}%</span>
      </div>
      <div className="h-1.5 bg-muted/60 rounded-full overflow-hidden ring-1 ring-inset ring-black/5">
        <div
          className={`h-full ${getThresholdColor()} transition-all duration-500 ease-out rounded-full`}
          style={{ width: `${percentage}%` }}
        />
      </div>
    </div>
  )
}

function MetricsPanel({ serverId }: { serverId: string }) {
  const [hours, setHours] = useState(24)
  const { data: metrics, isLoading, isFetching, error, refetch } = useServerMetrics(serverId, hours)

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-6">
        <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
      </div>
    )
  }

  if (error) {
    return (
      <div className="text-center py-4">
        <p className="text-xs text-muted-foreground mb-2">Failed to load metrics</p>
        <Button variant="outline" size="sm" onClick={() => refetch()} disabled={isFetching} className="h-7 text-xs">
          <RefreshCw className={`h-3 w-3 mr-1.5 ${isFetching ? 'animate-spin' : ''}`} />
          {isFetching ? 'Retrying...' : 'Retry'}
        </Button>
      </div>
    )
  }

  if (!metrics) {
    return (
      <div className="text-center py-4">
        <Activity className="h-6 w-6 mx-auto text-muted-foreground/40 mb-2" />
        <p className="text-xs text-muted-foreground">No metrics available</p>
      </div>
    )
  }

  return (
    <div className="space-y-4">
      {/* Period selector */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-1 p-0.5 bg-muted/50 rounded-md">
          {[1, 6, 24, 168].map((h) => (
            <Button
              key={h}
              variant={hours === h ? 'default' : 'ghost'}
              size="sm"
              className={`h-6 px-2 text-xs ${hours === h ? 'shadow-sm' : ''}`}
              onClick={() => setHours(h)}
              disabled={isFetching}
            >
              {h === 168 ? '7d' : `${h}h`}
            </Button>
          ))}
        </div>
        <Button
          variant="ghost"
          size="sm"
          className="h-6 w-6 p-0"
          onClick={() => refetch()}
          disabled={isFetching}
        >
          <RefreshCw className={`h-3 w-3 ${isFetching ? 'animate-spin' : ''}`} />
        </Button>
      </div>

      <div className={`space-y-4 transition-opacity duration-200 ${isFetching ? 'opacity-60' : ''}`}>
        {/* CPU */}
        <div className="space-y-2">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <div className="p-1.5 rounded-md bg-blue-100 dark:bg-blue-900/30">
                <Cpu className="h-3 w-3 text-blue-600 dark:text-blue-400" />
              </div>
              <span className="text-xs font-medium">CPU</span>
            </div>
            <span className="text-sm font-bold tabular-nums text-blue-600 dark:text-blue-400">
              {metrics.cpu.average}%
            </span>
          </div>
          <MetricsBar
            value={metrics.cpu.average}
            label={`Peak: ${metrics.cpu.max}%`}
            gradient="bg-gradient-to-r from-blue-500 to-blue-600"
          />
        </div>

        {/* Disk I/O */}
        {metrics.disk && (metrics.disk.readBps.length > 0 || metrics.disk.writeBps.length > 0) && (
          <div className="space-y-2">
            <div className="flex items-center gap-2">
              <div className="p-1.5 rounded-md bg-emerald-100 dark:bg-emerald-900/30">
                <HardDrive className="h-3 w-3 text-emerald-600 dark:text-emerald-400" />
              </div>
              <span className="text-xs font-medium">Disk I/O</span>
            </div>
            <div className="grid grid-cols-2 gap-3 text-xs">
              <div className="flex items-center gap-1.5 text-muted-foreground">
                <Download className="h-3 w-3" />
                <span className="font-medium text-foreground">
                  {metrics.disk.readBps.length > 0
                    ? formatBytesPerSec(metrics.disk.readBps[metrics.disk.readBps.length - 1]?.value || 0)
                    : 'N/A'}
                </span>
              </div>
              <div className="flex items-center gap-1.5 text-muted-foreground">
                <Upload className="h-3 w-3" />
                <span className="font-medium text-foreground">
                  {metrics.disk.writeBps.length > 0
                    ? formatBytesPerSec(metrics.disk.writeBps[metrics.disk.writeBps.length - 1]?.value || 0)
                    : 'N/A'}
                </span>
              </div>
            </div>
          </div>
        )}

        {/* Network */}
        {metrics.network && (metrics.network.rxBps.length > 0 || metrics.network.txBps.length > 0) && (
          <div className="space-y-2">
            <div className="flex items-center gap-2">
              <div className="p-1.5 rounded-md bg-violet-100 dark:bg-violet-900/30">
                <Network className="h-3 w-3 text-violet-600 dark:text-violet-400" />
              </div>
              <span className="text-xs font-medium">Network</span>
            </div>
            <div className="grid grid-cols-2 gap-3 text-xs">
              <div className="flex items-center gap-1.5 text-muted-foreground">
                <Download className="h-3 w-3" />
                <span className="font-medium text-foreground">
                  {metrics.network.rxBps.length > 0
                    ? formatBytesPerSec(metrics.network.rxBps[metrics.network.rxBps.length - 1]?.value || 0)
                    : 'N/A'}
                </span>
              </div>
              <div className="flex items-center gap-1.5 text-muted-foreground">
                <Upload className="h-3 w-3" />
                <span className="font-medium text-foreground">
                  {metrics.network.txBps.length > 0
                    ? formatBytesPerSec(metrics.network.txBps[metrics.network.txBps.length - 1]?.value || 0)
                    : 'N/A'}
                </span>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}

function SnapshotsPanel({ serverId }: { serverId: string }) {
  const [newSnapshotName, setNewSnapshotName] = useState('')
  const [confirmDelete, setConfirmDelete] = useState<string | null>(null)
  const [confirmRevert, setConfirmRevert] = useState<string | null>(null)

  const { data: snapshotsData, isLoading, isFetching, error, refetch } = useServerSnapshots(serverId)
  const createMutation = useCreateSnapshot()
  const deleteMutation = useDeleteSnapshot()
  const revertMutation = useRevertSnapshot()

  const handleCreateSnapshot = async () => {
    try {
      await createMutation.mutateAsync({
        serverId,
        name: newSnapshotName || undefined
      })
      setNewSnapshotName('')
    } catch (error) {
      console.error('Failed to create snapshot:', error)
    }
  }

  const handleDeleteSnapshot = async (name: string) => {
    try {
      await deleteMutation.mutateAsync({ serverId, name })
      setConfirmDelete(null)
    } catch (error) {
      console.error('Failed to delete snapshot:', error)
    }
  }

  const handleRevertSnapshot = async (name: string) => {
    try {
      await revertMutation.mutateAsync({ serverId, name })
      setConfirmRevert(null)
    } catch (error) {
      console.error('Failed to revert snapshot:', error)
    }
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-6">
        <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
      </div>
    )
  }

  if (error) {
    return (
      <div className="text-center py-4">
        <p className="text-xs text-muted-foreground mb-2">Failed to load snapshots</p>
        <Button variant="outline" size="sm" onClick={() => refetch()} disabled={isFetching} className="h-7 text-xs">
          <RefreshCw className={`h-3 w-3 mr-1.5 ${isFetching ? 'animate-spin' : ''}`} />
          {isFetching ? 'Retrying...' : 'Retry'}
        </Button>
      </div>
    )
  }

  const snapshots = snapshotsData?.snapshots || []

  return (
    <div className="space-y-3">
      {/* Create snapshot */}
      <div className="flex gap-2">
        <Input
          placeholder="Snapshot name (optional)"
          value={newSnapshotName}
          onChange={(e) => setNewSnapshotName(e.target.value)}
          className="h-8 text-xs bg-background"
        />
        <Button
          size="sm"
          className="h-8 shrink-0"
          onClick={handleCreateSnapshot}
          disabled={createMutation.isPending}
        >
          {createMutation.isPending ? (
            <Loader2 className="h-3.5 w-3.5 animate-spin" />
          ) : (
            <Plus className="h-3.5 w-3.5" />
          )}
          <span className="ml-1.5">Create</span>
        </Button>
      </div>

      {/* Snapshots list */}
      {snapshots.length === 0 ? (
        <div className="text-center py-4">
          <Camera className="h-6 w-6 mx-auto text-muted-foreground/40 mb-2" />
          <p className="text-xs text-muted-foreground">No snapshots</p>
        </div>
      ) : (
        <div className="space-y-2">
          {snapshots.map((snapshot) => (
            <div
              key={snapshot.name}
              className="group flex items-center justify-between p-2.5 bg-muted/30 rounded-lg border border-transparent hover:border-muted-foreground/10 transition-colors"
            >
              <div className="min-w-0">
                <p className="text-xs font-medium truncate">{snapshot.name}</p>
                <div className="flex items-center gap-2 text-[10px] text-muted-foreground mt-0.5">
                  <span className="flex items-center gap-1">
                    <Clock className="h-2.5 w-2.5" />
                    {new Date(snapshot.createdAt).toLocaleDateString()}
                  </span>
                  {snapshot.size && (
                    <span>{formatBytes(snapshot.size)}</span>
                  )}
                </div>
              </div>

              {confirmDelete === snapshot.name ? (
                <div className="flex gap-1">
                  <Button
                    size="sm"
                    variant="destructive"
                    className="h-6 px-2 text-xs"
                    onClick={() => handleDeleteSnapshot(snapshot.name)}
                    disabled={deleteMutation.isPending}
                  >
                    {deleteMutation.isPending ? (
                      <Loader2 className="h-3 w-3 animate-spin" />
                    ) : (
                      'Delete'
                    )}
                  </Button>
                  <Button
                    size="sm"
                    variant="ghost"
                    className="h-6 px-2 text-xs"
                    onClick={() => setConfirmDelete(null)}
                  >
                    Cancel
                  </Button>
                </div>
              ) : confirmRevert === snapshot.name ? (
                <div className="flex gap-1">
                  <Button
                    size="sm"
                    variant="destructive"
                    className="h-6 px-2 text-xs"
                    onClick={() => handleRevertSnapshot(snapshot.name)}
                    disabled={revertMutation.isPending}
                  >
                    {revertMutation.isPending ? (
                      <Loader2 className="h-3 w-3 animate-spin" />
                    ) : (
                      'Revert'
                    )}
                  </Button>
                  <Button
                    size="sm"
                    variant="ghost"
                    className="h-6 px-2 text-xs"
                    onClick={() => setConfirmRevert(null)}
                  >
                    Cancel
                  </Button>
                </div>
              ) : (
                <div className="flex gap-1 opacity-60 group-hover:opacity-100 transition-opacity">
                  <Button
                    size="sm"
                    variant="ghost"
                    className="h-6 w-6 p-0"
                    onClick={() => setConfirmRevert(snapshot.name)}
                    title="Revert to this snapshot"
                  >
                    <RotateCcw className="h-3 w-3" />
                  </Button>
                  <Button
                    size="sm"
                    variant="ghost"
                    className="h-6 w-6 p-0 text-muted-foreground hover:text-destructive"
                    onClick={() => setConfirmDelete(snapshot.name)}
                    title="Delete snapshot"
                  >
                    <Trash2 className="h-3 w-3" />
                  </Button>
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  )
}

function ServerCard({ server }: { server: NetcupServer }) {
  const [confirmAction, setConfirmAction] = useState<PowerAction | 'rescue' | null>(null)
  const [expandedSection, setExpandedSection] = useState<'metrics' | 'snapshots' | null>(null)

  const powerMutation = useNetcupPowerAction()
  const rescueMutation = useNetcupRescue()

  // Check if this server is being reinstalled (centralized tracking)
  const isReinstalling = isServerReinstalling(server.id)
  const effectiveState = isReinstalling ? 'REINSTALLING' : server.state

  const config = stateConfig[effectiveState] || stateConfig.UNKNOWN
  const StateIcon = config.icon
  const isOn = effectiveState === 'ON'
  const isPending = powerMutation.isPending || rescueMutation.isPending

  const handlePowerAction = async (action: PowerAction) => {
    try {
      await powerMutation.mutateAsync({ serverId: server.id, action })
      setConfirmAction(null)
    } catch (error) {
      console.error('Power action failed:', error)
    }
  }

  const handleRescue = async (activate: boolean) => {
    try {
      await rescueMutation.mutateAsync({ serverId: server.id, activate })
      setConfirmAction(null)
    } catch (error) {
      console.error('Rescue action failed:', error)
    }
  }

  const toggleSection = (section: 'metrics' | 'snapshots') => {
    setExpandedSection(expandedSection === section ? null : section)
  }

  return (
    <Card className="group overflow-hidden hover:shadow-lg hover:shadow-primary/5 transition-all duration-300 border-transparent hover:border-primary/10">
      {/* Card gradient background */}
      <div className="relative">
        <div className="absolute inset-0 bg-gradient-to-br from-card via-card to-muted/20" />

        {/* Decorative gradient blob */}
        <div className={`absolute top-0 right-0 -mt-8 -mr-8 h-32 w-32 rounded-full blur-3xl opacity-30 transition-opacity group-hover:opacity-50 ${
          isOn ? 'bg-emerald-500' : server.state === 'OFF' ? 'bg-slate-400' : 'bg-amber-500'
        }`} />

        <Link href={`/admin/servers/netcup/${server.id}`}>
          <CardHeader className="relative pb-4 cursor-pointer transition-colors">
            <div className="flex items-start justify-between gap-3">
              <div className="flex items-center gap-3 min-w-0">
                <div className={`p-3 rounded-xl ${config.bgColor} ${config.borderColor} border shrink-0`}>
                  <Server className={`h-5 w-5 ${config.textColor}`} />
                </div>
                <div className="min-w-0">
                  <CardTitle className="text-base font-semibold truncate group-hover:text-primary transition-colors">
                    {server.nickname || server.name}
                  </CardTitle>
                  <p className="text-sm text-muted-foreground truncate font-mono">
                    {server.nickname ? server.name : null}
                  </p>
                </div>
              </div>

              {/* Status badge with dot indicator */}
              <div className={`inline-flex items-center gap-2 px-2.5 py-1.5 rounded-full text-xs font-medium shrink-0 ${config.bgColor} ${config.textColor} border ${config.borderColor}`}>
                <span className={`h-2 w-2 rounded-full ${config.dotColor} ${isOn ? 'animate-pulse' : ''}`} />
                {config.label}
              </div>
            </div>
          </CardHeader>
        </Link>

        <CardContent className="relative space-y-4">
          {/* Server specs - card style with colored icons */}
          <div className="grid grid-cols-3 gap-2">
            {server.cpuCores && (
              <div className="flex items-center gap-2 p-2 rounded-lg bg-blue-50/50 dark:bg-blue-950/20">
                <div className="p-1.5 rounded-md bg-blue-100 dark:bg-blue-900/30">
                  <Cpu className="h-3 w-3 text-blue-600 dark:text-blue-400" />
                </div>
                <div className="min-w-0">
                  <p className="text-sm font-bold tabular-nums">{server.cpuCores}</p>
                  <p className="text-[10px] text-muted-foreground">Cores</p>
                </div>
              </div>
            )}
            {server.ramGb && (
              <div className="flex items-center gap-2 p-2 rounded-lg bg-purple-50/50 dark:bg-purple-950/20">
                <div className="p-1.5 rounded-md bg-purple-100 dark:bg-purple-900/30">
                  <MemoryStick className="h-3 w-3 text-purple-600 dark:text-purple-400" />
                </div>
                <div className="min-w-0">
                  <p className="text-sm font-bold tabular-nums">{server.ramGb}</p>
                  <p className="text-[10px] text-muted-foreground">GB RAM</p>
                </div>
              </div>
            )}
            {server.diskGb && (
              <div className="flex items-center gap-2 p-2 rounded-lg bg-emerald-50/50 dark:bg-emerald-950/20">
                <div className="p-1.5 rounded-md bg-emerald-100 dark:bg-emerald-900/30">
                  <HardDrive className="h-3 w-3 text-emerald-600 dark:text-emerald-400" />
                </div>
                <div className="min-w-0">
                  <p className="text-sm font-bold tabular-nums">{server.diskGb}</p>
                  <p className="text-[10px] text-muted-foreground">GB SSD</p>
                </div>
              </div>
            )}
          </div>

          {/* Network info - improved styling */}
          <div className="rounded-lg bg-muted/30 p-3 space-y-2">
            {server.hostname && (
              <div className="flex items-center justify-between gap-2">
                <div className="flex items-center gap-2 text-xs text-muted-foreground">
                  <Globe className="h-3 w-3" />
                  <span>Hostname</span>
                </div>
                <div className="flex items-center gap-1">
                  <code className="text-xs font-mono font-medium truncate max-w-[140px]">{server.hostname}</code>
                  <CopyButton text={server.hostname} />
                </div>
              </div>
            )}
            <div className="flex items-center justify-between gap-2">
              <div className="flex items-center gap-2 text-xs text-muted-foreground">
                <Network className="h-3 w-3" />
                <span>IPv4</span>
              </div>
              <div className="flex items-center gap-1">
                {server.primaryIpv4 ? (
                  <>
                    <code className="text-xs font-mono font-medium">{server.primaryIpv4}</code>
                    <CopyButton text={server.primaryIpv4} />
                  </>
                ) : (
                  <span className="text-xs text-muted-foreground italic">Not available</span>
                )}
              </div>
            </div>
          </div>

          {/* Confirm dialog - improved styling */}
          {confirmAction && (
            <div className="rounded-xl bg-gradient-to-br from-amber-50 to-orange-50 dark:from-amber-950/30 dark:to-orange-950/20 border border-amber-200 dark:border-amber-900 p-4 space-y-3">
              <p className="text-sm font-medium text-amber-800 dark:text-amber-200">
                {confirmAction === 'rescue'
                  ? 'Enable rescue mode?'
                  : `Confirm ${confirmAction.toLowerCase()} action?`}
              </p>
              <p className="text-xs text-amber-700/80 dark:text-amber-300/70">
                {confirmAction === 'POWEROFF' && 'Server will be forcefully powered off.'}
                {confirmAction === 'RESET' && 'Server will be hard reset (may cause data loss).'}
                {confirmAction === 'POWERCYCLE' && 'Server will be power cycled.'}
                {confirmAction === 'rescue' && 'Server will boot into rescue mode on next restart.'}
              </p>
              <div className="flex gap-2">
                <Button
                  variant="destructive"
                  size="sm"
                  className="h-8"
                  onClick={() =>
                    confirmAction === 'rescue'
                      ? handleRescue(true)
                      : handlePowerAction(confirmAction as PowerAction)
                  }
                  disabled={isPending}
                >
                  {isPending && <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />}
                  Confirm
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  className="h-8"
                  onClick={() => setConfirmAction(null)}
                  disabled={isPending}
                >
                  Cancel
                </Button>
              </div>
            </div>
          )}

          {/* Power control buttons - card style with hover effects */}
          {!confirmAction && (
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
              {effectiveState === 'UNKNOWN' || effectiveState === 'REINSTALLING' ? (
                <>
                  <button
                    onClick={() => setConfirmAction('POWERCYCLE')}
                    disabled={isPending}
                    className="flex flex-col items-center justify-center gap-1.5 p-3 rounded-lg border bg-card hover:bg-muted/50 hover:border-muted-foreground/20 transition-all disabled:opacity-50"
                  >
                    <RefreshCw className="h-4 w-4 text-muted-foreground" />
                    <span className="text-xs font-medium">Restart</span>
                  </button>
                  <button
                    onClick={() => setConfirmAction('POWEROFF')}
                    disabled={isPending}
                    className="flex flex-col items-center justify-center gap-1.5 p-3 rounded-lg border bg-card hover:bg-red-50 hover:border-red-200 dark:hover:bg-red-950/30 dark:hover:border-red-900 transition-all disabled:opacity-50"
                  >
                    <PowerOff className="h-4 w-4 text-muted-foreground" />
                    <span className="text-xs font-medium">Shutdown</span>
                  </button>
                </>
              ) : !isOn ? (
                <button
                  onClick={() => handlePowerAction('ON')}
                  disabled={isPending}
                  className="col-span-2 flex flex-col items-center justify-center gap-1.5 p-3 rounded-lg border-2 border-emerald-200 bg-gradient-to-br from-emerald-50 to-emerald-100/50 hover:border-emerald-300 hover:shadow-lg hover:shadow-emerald-100 dark:border-emerald-900 dark:from-emerald-950/50 dark:to-emerald-900/30 transition-all disabled:opacity-50"
                >
                  {isPending ? (
                    <Loader2 className="h-4 w-4 animate-spin text-emerald-600" />
                  ) : (
                    <Power className="h-4 w-4 text-emerald-600 dark:text-emerald-400" />
                  )}
                  <span className="text-xs font-medium text-emerald-700 dark:text-emerald-400">Power On</span>
                </button>
              ) : (
                <>
                  <button
                    onClick={() => setConfirmAction('POWERCYCLE')}
                    disabled={isPending}
                    className="flex flex-col items-center justify-center gap-1.5 p-3 rounded-lg border bg-card hover:bg-blue-50 hover:border-blue-200 dark:hover:bg-blue-950/30 dark:hover:border-blue-900 transition-all disabled:opacity-50"
                  >
                    <RefreshCw className="h-4 w-4 text-muted-foreground group-hover:text-blue-600" />
                    <span className="text-xs font-medium">Restart</span>
                  </button>
                  <button
                    onClick={() => setConfirmAction('POWEROFF')}
                    disabled={isPending}
                    className="flex flex-col items-center justify-center gap-1.5 p-3 rounded-lg border bg-card hover:bg-red-50 hover:border-red-200 dark:hover:bg-red-950/30 dark:hover:border-red-900 transition-all disabled:opacity-50"
                  >
                    <PowerOff className="h-4 w-4 text-muted-foreground" />
                    <span className="text-xs font-medium">Power Off</span>
                  </button>
                </>
              )}
              <button
                onClick={() => setConfirmAction('rescue')}
                disabled={isPending}
                className="flex flex-col items-center justify-center gap-1.5 p-3 rounded-lg border bg-card hover:bg-amber-50 hover:border-amber-200 dark:hover:bg-amber-950/30 dark:hover:border-amber-900 transition-all disabled:opacity-50"
              >
                <Wrench className="h-4 w-4 text-muted-foreground" />
                <span className="text-xs font-medium">Rescue</span>
              </button>
              <Link href={`/admin/servers/netcup/${server.id}`} className="contents">
                <button className="flex flex-col items-center justify-center gap-1.5 p-3 rounded-lg border bg-card hover:bg-primary/5 hover:border-primary/20 transition-all">
                  <Eye className="h-4 w-4 text-muted-foreground" />
                  <span className="text-xs font-medium">Details</span>
                </button>
              </Link>
            </div>
          )}

          {/* Expandable sections - improved styling */}
          <div className="border-t border-border/50 pt-3 space-y-1">
            {/* Metrics toggle */}
            <button
              onClick={() => toggleSection('metrics')}
              className={`flex items-center justify-between w-full px-3 py-2 rounded-lg text-sm font-medium transition-all ${
                expandedSection === 'metrics'
                  ? 'bg-primary/5 text-primary'
                  : 'hover:bg-muted/50 text-muted-foreground hover:text-foreground'
              }`}
            >
              <div className="flex items-center gap-2">
                <Activity className="h-4 w-4" />
                Performance Metrics
              </div>
              {expandedSection === 'metrics' ? (
                <ChevronUp className="h-4 w-4" />
              ) : (
                <ChevronDown className="h-4 w-4" />
              )}
            </button>
            {expandedSection === 'metrics' && (
              <div className="px-3 py-3 bg-muted/20 rounded-lg mt-1 mb-2">
                <MetricsPanel serverId={server.id} />
              </div>
            )}

            {/* Snapshots toggle */}
            <button
              onClick={() => toggleSection('snapshots')}
              className={`flex items-center justify-between w-full px-3 py-2 rounded-lg text-sm font-medium transition-all ${
                expandedSection === 'snapshots'
                  ? 'bg-primary/5 text-primary'
                  : 'hover:bg-muted/50 text-muted-foreground hover:text-foreground'
              }`}
            >
              <div className="flex items-center gap-2">
                <Camera className="h-4 w-4" />
                Snapshots
              </div>
              {expandedSection === 'snapshots' ? (
                <ChevronUp className="h-4 w-4" />
              ) : (
                <ChevronDown className="h-4 w-4" />
              )}
            </button>
            {expandedSection === 'snapshots' && (
              <div className="px-3 py-3 bg-muted/20 rounded-lg mt-1">
                <SnapshotsPanel serverId={server.id} />
              </div>
            )}
          </div>
        </CardContent>
      </div>
    </Card>
  )
}

function LoadingSkeleton() {
  return (
    <div className="grid gap-6 md:grid-cols-2 xl:grid-cols-3">
      {[1, 2, 3].map((i) => (
        <Card key={i} className="overflow-hidden">
          <CardHeader className="pb-4">
            <div className="flex items-start justify-between gap-3">
              <div className="flex items-center gap-3">
                <div className="h-11 w-11 rounded-xl bg-muted animate-pulse" />
                <div className="space-y-2">
                  <div className="h-4 w-32 bg-muted animate-pulse rounded" />
                  <div className="h-3 w-24 bg-muted animate-pulse rounded" />
                </div>
              </div>
              <div className="h-7 w-20 bg-muted animate-pulse rounded-full" />
            </div>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-3 gap-2">
              {[1, 2, 3].map((j) => (
                <div key={j} className="h-16 bg-muted/50 animate-pulse rounded-lg" />
              ))}
            </div>
            <div className="h-20 bg-muted/30 animate-pulse rounded-lg" />
            <div className="grid grid-cols-4 gap-2">
              {[1, 2, 3, 4].map((j) => (
                <div key={j} className="h-16 bg-muted/50 animate-pulse rounded-lg" />
              ))}
            </div>
          </CardContent>
        </Card>
      ))}
    </div>
  )
}

function EmptyState() {
  return (
    <div className="rounded-2xl border-2 border-dashed border-muted-foreground/20 bg-gradient-to-br from-muted/20 to-muted/40 py-16 text-center">
      <div className="mx-auto w-fit p-5 rounded-2xl bg-muted/60 mb-5">
        <ServerCrash className="h-12 w-12 text-muted-foreground/50" />
      </div>
      <h3 className="font-semibold text-lg">No servers found</h3>
      <p className="text-sm text-muted-foreground mt-2 max-w-sm mx-auto">
        Your Netcup account does not have any servers yet. Servers will appear here once they are provisioned.
      </p>
    </div>
  )
}

export default function NetcupServersPage() {
  const { data: authStatus, isLoading: isLoadingAuth } = useNetcupAuth()
  const { data: serversData, isLoading: isLoadingServers, refetch } = useNetcupServers()

  const isAuthenticated = authStatus?.authenticated

  return (
    <div className="space-y-8">
      {/* Hero Header */}
      <div className="relative overflow-hidden rounded-2xl border bg-gradient-to-br from-card via-card to-muted/30 p-6 md:p-8">
        {/* Background decorations */}
        <div className="absolute top-0 right-0 -mt-20 -mr-20 h-72 w-72 rounded-full bg-gradient-to-br from-violet-500/10 to-purple-500/10 blur-3xl" />
        <div className="absolute bottom-0 left-0 -mb-20 -ml-20 h-56 w-56 rounded-full bg-gradient-to-tr from-blue-500/10 to-cyan-500/5 blur-2xl" />

        <div className="relative flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <div className="flex items-center gap-4">
            <div className="p-3.5 rounded-2xl bg-gradient-to-br from-violet-100 to-purple-100 dark:from-violet-900/30 dark:to-purple-900/30 border border-violet-200/50 dark:border-violet-800/50">
              <Server className="h-7 w-7 text-violet-600 dark:text-violet-400" />
            </div>
            <div>
              <h1 className="text-2xl md:text-3xl font-bold tracking-tight">Netcup Servers</h1>
              <p className="text-muted-foreground mt-0.5">
                Manage your Netcup servers via SCP API
              </p>
            </div>
          </div>
          {isAuthenticated && (
            <Button
              variant="outline"
              onClick={() => refetch()}
              disabled={isLoadingServers}
              className="gap-2 shrink-0"
            >
              <RefreshCw className={`h-4 w-4 ${isLoadingServers ? 'animate-spin' : ''}`} />
              Refresh Servers
            </Button>
          )}
        </div>
      </div>

      {/* Auth setup card */}
      <NetcupAuthSetup />

      {/* Loading state - initial auth check */}
      {isLoadingAuth && (
        <div className="flex flex-col items-center justify-center py-16 gap-4">
          <div className="relative">
            <div className="absolute inset-0 bg-primary/20 rounded-full blur-xl animate-pulse" />
            <div className="relative p-4 rounded-full bg-muted">
              <Loader2 className="h-8 w-8 animate-spin text-primary" />
            </div>
          </div>
          <p className="text-sm text-muted-foreground">Checking authentication...</p>
        </div>
      )}

      {/* Servers grid - only show if authenticated */}
      {isAuthenticated && (
        <>
          {isLoadingServers ? (
            <LoadingSkeleton />
          ) : serversData?.servers && serversData.servers.length > 0 ? (
            <div className="grid gap-6 md:grid-cols-2 xl:grid-cols-3">
              {serversData.servers.map((server) => (
                <ServerCard key={server.id} server={server} />
              ))}
            </div>
          ) : (
            <EmptyState />
          )}
        </>
      )}
    </div>
  )
}
