'use client'

import { useState, useMemo, useEffect, useCallback, useRef } from 'react'
import Link from 'next/link'
import { useParams, useRouter } from 'next/navigation'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useQueryClient } from '@tanstack/react-query'
import { useOrder, useUpdateOrder, useTriggerProvisioning, useDeleteOrder } from '@/hooks/use-orders'
import { useProvisioningLogs, StreamedLog } from '@/hooks/use-provisioning-logs'
import { portainerKeys } from '@/hooks/use-portainer'
import { useDnsVerification, useTriggerDnsVerification, useSkipDnsVerification } from '@/hooks/use-dns'
import { useChangeAutomationMode } from '@/hooks/use-automation'
import { OrderStatus, SubscriptionTier, LogLevel, AutomationMode } from '@/types/api'
import { DnsVerificationPanel } from '@/components/admin/dns-verification-panel'
import { AutomationControls } from '@/components/admin/automation-controls'
import { ServerQuickActions } from '@/components/admin/server-quick-actions'
import { NetcupServerLink } from '@/components/admin/netcup-server-link'
import { ServerMetricsPanel } from '@/components/admin/server-metrics-panel'
import { PortainerCredentialsPanel } from '@/components/admin/portainer-credentials-panel'
import { ContainerList } from '@/components/admin/container-list'
import {
  ArrowLeft,
  ArrowDown,
  Globe,
  User,
  Server,
  Clock,
  CheckCircle,
  XCircle,
  AlertCircle,
  Loader2,
  Eye,
  EyeOff,
  RefreshCw,
  ExternalLink,
  Terminal,
  Zap,
  Wifi,
  WifiOff,
  Trash2,
} from 'lucide-react'
import { SliderConfirmDialog } from '@/components/ui/slider-confirm-dialog'
import { RefreshButton } from '@/components/ui/refresh-button'
import { ToolsEditor } from '@/components/admin/ToolsEditor'
import { OrderTimeline } from '@/components/admin/order-timeline'
import { ProvisioningConfigForm, ProvisioningConfig } from '@/components/admin/provisioning-config-form'
import { SSH_PORT_BEFORE_PROVISION, SSH_PORT_AFTER_PROVISION } from '@/lib/ssh/constants'

// Status badge component
function StatusBadge({ status }: { status: OrderStatus }) {
  const statusConfig: Record<OrderStatus, { label: string; className: string }> = {
    PAYMENT_CONFIRMED: { label: 'Payment Confirmed', className: 'bg-blue-100 text-blue-800' },
    AWAITING_SERVER: { label: 'Awaiting Server', className: 'bg-yellow-100 text-yellow-800' },
    SERVER_READY: { label: 'Server Ready', className: 'bg-purple-100 text-purple-800' },
    DNS_PENDING: { label: 'DNS Pending', className: 'bg-orange-100 text-orange-800' },
    DNS_READY: { label: 'DNS Ready', className: 'bg-cyan-100 text-cyan-800' },
    PROVISIONING: { label: 'Provisioning', className: 'bg-indigo-100 text-indigo-800' },
    FULFILLED: { label: 'Fulfilled', className: 'bg-green-100 text-green-800' },
    EMAIL_CONFIGURED: { label: 'Complete', className: 'bg-emerald-100 text-emerald-800' },
    FAILED: { label: 'Failed', className: 'bg-red-100 text-red-800' },
  }

  const config = statusConfig[status]

  return (
    <span className={`inline-flex items-center rounded-full px-3 py-1 text-sm font-medium ${config.className}`}>
      {config.label}
    </span>
  )
}

// Server card component with SSH test
function ServerCard({
  orderId,
  serverIp,
  sshPort,
  showTestButton,
}: {
  orderId: string
  serverIp: string | null
  sshPort: number | null
  showTestButton: boolean
}) {
  const [testing, setTesting] = useState(false)
  const [testResult, setTestResult] = useState<{ success: boolean; message: string; latency?: number } | null>(null)

  const handleTestSSH = async () => {
    if (!serverIp) return
    setTesting(true)
    setTestResult(null)
    try {
      const response = await fetch(`/api/v1/admin/orders/${orderId}/test-ssh`, {
        method: 'POST',
      })
      const data = await response.json()
      if (data.success) {
        setTestResult({
          success: true,
          message: `SSH connection successful!`,
          latency: data.latency,
        })
      } else {
        setTestResult({
          success: false,
          message: data.error || 'Connection failed',
        })
      }
    } catch (err) {
      setTestResult({
        success: false,
        message: err instanceof Error ? err.message : 'Connection test failed',
      })
    } finally {
      setTesting(false)
    }
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Server className="h-5 w-5" />
          Server
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        {serverIp ? (
          <>
            <div className="space-y-2">
              <p className="font-mono font-medium">{serverIp}</p>
              <p className="text-sm text-muted-foreground">SSH Port: {sshPort || 22}</p>
            </div>

            {showTestButton && (
              <div className="space-y-3">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={handleTestSSH}
                  disabled={testing}
                  className="w-full"
                >
                  {testing ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      Testing SSH...
                    </>
                  ) : (
                    <>
                      <Terminal className="mr-2 h-4 w-4" />
                      Test SSH Connection
                    </>
                  )}
                </Button>

                {testResult && (
                  <div
                    className={`flex items-center gap-2 rounded-md p-3 text-sm ${
                      testResult.success
                        ? 'bg-green-50 text-green-800'
                        : 'bg-red-50 text-red-800'
                    }`}
                  >
                    {testResult.success ? (
                      <CheckCircle className="h-4 w-4 flex-shrink-0" />
                    ) : (
                      <AlertCircle className="h-4 w-4 flex-shrink-0" />
                    )}
                    <div>
                      <p>{testResult.message}</p>
                      {testResult.latency && (
                        <p className="text-xs opacity-75">Latency: {testResult.latency}ms</p>
                      )}
                    </div>
                  </div>
                )}
              </div>
            )}
          </>
        ) : (
          <p className="text-sm text-muted-foreground">Not configured</p>
        )}
      </CardContent>
    </Card>
  )
}

// Server credentials form component
function ServerCredentialsForm({
  orderId,
  initialIp,
  initialPort,
  hasCredentials,
  onSubmit,
  isLoading,
}: {
  orderId: string
  initialIp?: string
  initialPort?: number
  hasCredentials: boolean
  onSubmit: (ip: string, password: string, port: number) => void
  isLoading: boolean
}) {
  const [ip, setIp] = useState(initialIp || '')
  const [password, setPassword] = useState('')
  const [port, setPort] = useState(String(initialPort || SSH_PORT_BEFORE_PROVISION))
  const [showPassword, setShowPassword] = useState(false)
  const [testing, setTesting] = useState(false)
  const [testResult, setTestResult] = useState<{ success: boolean; message: string } | null>(null)

  const handleTestConnection = async () => {
    setTesting(true)
    setTestResult(null)
    try {
      const response = await fetch(`/api/v1/admin/orders/${orderId}/test-ssh`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          serverIp: ip,
          password: password,
          sshPort: parseInt(port),
        }),
      })
      const data = await response.json()
      if (data.success) {
        setTestResult({
          success: true,
          message: `Connection successful! Latency: ${data.latency}ms`,
        })
      } else {
        setTestResult({
          success: false,
          message: data.error || 'Connection failed',
        })
      }
    } catch (err) {
      setTestResult({
        success: false,
        message: err instanceof Error ? err.message : 'Connection test failed',
      })
    } finally {
      setTesting(false)
    }
  }

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    onSubmit(ip, password, parseInt(port))
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Server className="h-5 w-5" />
          Server Credentials
        </CardTitle>
        <CardDescription>
          {hasCredentials
            ? 'Server credentials have been entered. You can update them if needed.'
            : 'Enter the server credentials received from the hosting provider.'}
        </CardDescription>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="ip">Server IP Address</Label>
              <Input
                id="ip"
                type="text"
                placeholder="123.45.67.89"
                value={ip}
                onChange={(e) => setIp(e.target.value)}
                required
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="port">SSH Port</Label>
              <Input
                id="port"
                type="number"
                placeholder={String(SSH_PORT_BEFORE_PROVISION)}
                value={port}
                onChange={(e) => setPort(e.target.value)}
                required
              />
              <p className="text-xs text-muted-foreground">
                Default: {SSH_PORT_BEFORE_PROVISION} (changes to {SSH_PORT_AFTER_PROVISION} after provisioning)
              </p>
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="password">Root Password</Label>
            <div className="relative">
              <Input
                id="password"
                type={showPassword ? 'text' : 'password'}
                placeholder="Enter root password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                required={!hasCredentials}
                className="pr-10"
              />
              <Button
                type="button"
                variant="ghost"
                size="icon"
                className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                onClick={() => setShowPassword(!showPassword)}
              >
                {showPassword ? (
                  <EyeOff className="h-4 w-4 text-muted-foreground" />
                ) : (
                  <Eye className="h-4 w-4 text-muted-foreground" />
                )}
              </Button>
            </div>
            <p className="text-xs text-muted-foreground">
              Password will be encrypted and deleted after provisioning completes.
            </p>
          </div>

          {testResult && (
            <div
              className={`flex items-center gap-2 rounded-md p-3 ${
                testResult.success ? 'bg-green-50 text-green-800' : 'bg-red-50 text-red-800'
              }`}
            >
              {testResult.success ? (
                <CheckCircle className="h-4 w-4" />
              ) : (
                <AlertCircle className="h-4 w-4" />
              )}
              <span className="text-sm">{testResult.message}</span>
            </div>
          )}

          <div className="flex gap-3">
            <Button
              type="button"
              variant="outline"
              onClick={handleTestConnection}
              disabled={!ip || !password || testing}
            >
              {testing ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Testing...
                </>
              ) : (
                <>
                  <RefreshCw className="mr-2 h-4 w-4" />
                  Test Connection
                </>
              )}
            </Button>
            <Button type="submit" disabled={isLoading || !ip}>
              {isLoading ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Saving...
                </>
              ) : (
                'Save & Mark Ready'
              )}
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  )
}

// Provisioning logs component
function ProvisioningLogs({ logs, isLive, isConnected, isComplete, finalStatus, onReconnect }: {
  logs: Array<{
    id: string
    timestamp: Date
    level: LogLevel
    step: string | null
    message: string
  }>
  isLive: boolean
  isConnected?: boolean
  isComplete?: boolean
  finalStatus?: 'FULFILLED' | 'FAILED' | null
  onReconnect?: () => void
}) {
  const logContainerRef = useRef<HTMLDivElement>(null)
  const [autoScroll, setAutoScroll] = useState(true)
  const userScrolledRef = useRef(false)
  const lastScrollTopRef = useRef(0)

  const levelColors: Record<LogLevel, string> = {
    INFO: 'text-blue-400',
    WARN: 'text-yellow-400',
    ERROR: 'text-red-400',
    DEBUG: 'text-gray-400',
  }

  const formatTime = (date: Date) => {
    const d = new Date(date)
    return d.toLocaleTimeString('en-US', { hour12: false })
  }

  // Handle scroll to detect if user manually scrolled up
  const handleScroll = () => {
    if (!logContainerRef.current) return
    const { scrollTop, scrollHeight, clientHeight } = logContainerRef.current
    const isAtBottom = scrollHeight - scrollTop - clientHeight < 100

    // Detect if user scrolled UP manually (not programmatic scroll down)
    if (scrollTop < lastScrollTopRef.current && !isAtBottom) {
      userScrolledRef.current = true
      setAutoScroll(false)
    } else if (isAtBottom) {
      // User scrolled back to bottom
      userScrolledRef.current = false
      setAutoScroll(true)
    }

    lastScrollTopRef.current = scrollTop
  }

  // Auto-scroll to bottom when new logs arrive
  useEffect(() => {
    if (autoScroll && logContainerRef.current) {
      // Use requestAnimationFrame for smooth scrolling
      requestAnimationFrame(() => {
        if (logContainerRef.current) {
          logContainerRef.current.scrollTop = logContainerRef.current.scrollHeight
          lastScrollTopRef.current = logContainerRef.current.scrollTop
        }
      })
    }
  }, [logs.length, autoScroll])

  return (
    <Card className={isComplete ? (finalStatus === 'FULFILLED' ? 'border-green-500/50' : 'border-red-500/50') : ''}>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle className="flex items-center gap-2">
              <Terminal className="h-5 w-5" />
              Provisioning Logs
            </CardTitle>
            <CardDescription>Real-time output from the provisioning process</CardDescription>
          </div>
          <div className="flex items-center gap-3">
            {/* Completion status */}
            {isComplete && (
              <div className={`flex items-center gap-2 rounded-full px-3 py-1 text-sm font-medium ${
                finalStatus === 'FULFILLED'
                  ? 'bg-green-500/10 text-green-600'
                  : 'bg-red-500/10 text-red-600'
              }`}>
                {finalStatus === 'FULFILLED' ? (
                  <>
                    <CheckCircle className="h-4 w-4" />
                    Completed Successfully
                  </>
                ) : (
                  <>
                    <XCircle className="h-4 w-4" />
                    Provisioning Failed
                  </>
                )}
              </div>
            )}
            {/* Live status */}
            {isLive && !isComplete && (
              <>
                {isConnected ? (
                  <div className="flex items-center gap-2">
                    <span className="relative flex h-3 w-3">
                      <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-green-400 opacity-75"></span>
                      <span className="relative inline-flex h-3 w-3 rounded-full bg-green-500"></span>
                    </span>
                    <span className="text-sm text-muted-foreground">Live</span>
                    <Wifi className="h-4 w-4 text-green-500" />
                  </div>
                ) : (
                  <div className="flex items-center gap-2">
                    <WifiOff className="h-4 w-4 text-red-500" />
                    <span className="text-sm text-red-500">Disconnected</span>
                    {onReconnect && (
                      <RefreshButton
                        variant="ghost"
                        size="sm"
                        onClick={onReconnect}
                        showLabel={false}
                      />
                    )}
                  </div>
                )}
              </>
            )}
            {!isLive && !isComplete && logs.length > 0 && (
              <span className="text-sm text-muted-foreground">
                {logs.length} log{logs.length !== 1 ? 's' : ''}
              </span>
            )}
            {/* Auto-scroll indicator */}
            {!autoScroll && isLive && !isComplete && (
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  userScrolledRef.current = false
                  setAutoScroll(true)
                  if (logContainerRef.current) {
                    logContainerRef.current.scrollTop = logContainerRef.current.scrollHeight
                    lastScrollTopRef.current = logContainerRef.current.scrollTop
                  }
                }}
              >
                <ArrowDown className="h-4 w-4 mr-1" />
                Resume auto-scroll
              </Button>
            )}
          </div>
        </div>
      </CardHeader>
      <CardContent>
        <div
          ref={logContainerRef}
          onScroll={handleScroll}
          className="h-96 overflow-y-auto rounded-lg bg-gray-900 p-4 font-mono text-sm"
        >
          {logs.length === 0 ? (
            <p className="text-gray-500">
              {isLive && isConnected ? 'Waiting for logs...' : 'No logs available yet.'}
            </p>
          ) : (
            logs.map((log) => (
              <div key={log.id} className="mb-2">
                <span className="text-gray-500">[{formatTime(log.timestamp)}]</span>{' '}
                <span className={levelColors[log.level]}>[{log.level}]</span>{' '}
                {log.step && <span className="text-purple-400">[{log.step}]</span>}{' '}
                <span className="text-gray-300">{log.message}</span>
              </div>
            ))
          )}
        </div>
      </CardContent>
    </Card>
  )
}

export default function OrderDetailPage() {
  const params = useParams()
  const router = useRouter()
  const queryClient = useQueryClient()
  const orderId = params.id as string

  // Fetch order data
  const {
    data: order,
    isLoading,
    isError,
    error,
    refetch,
    isFetching,
  } = useOrder(orderId)

  // Mutations
  const updateOrder = useUpdateOrder()
  const triggerProvision = useTriggerProvisioning()
  const changeAutomationMode = useChangeAutomationMode()

  // DNS hooks
  const { data: dnsData } = useDnsVerification(orderId)
  const triggerDnsVerification = useTriggerDnsVerification()
  const skipDnsVerification = useSkipDnsVerification()

  // Delete hook
  const deleteOrder = useDeleteOrder()
  const [showDeleteDialog, setShowDeleteDialog] = useState(false)

  // Check if we should enable SSE streaming
  const isProvisioning = order?.status === OrderStatus.PROVISIONING

  // SSE for live log streaming
  const {
    logs: streamedLogs,
    isConnected,
    isComplete,
    reconnect,
  } = useProvisioningLogs({
    orderId,
    enabled: isProvisioning,
    onStatusChange: useCallback((newStatus: OrderStatus) => {
      // Refetch order data when status changes
      refetch()
    }, [refetch]),
    onComplete: useCallback((success: boolean) => {
      // Refetch order data when provisioning completes
      refetch()
      // Also invalidate Portainer credentials to pick up any synced credentials
      queryClient.invalidateQueries({ queryKey: portainerKeys.credentials(orderId) })
      queryClient.invalidateQueries({ queryKey: portainerKeys.containers(orderId) })
    }, [refetch, queryClient, orderId]),
  })

  // Computed values
  const tierLabel = useMemo(() => {
    if (!order) return ''
    return order.tier === SubscriptionTier.HUB_DASHBOARD ? 'Hub Dashboard' : 'Control Panel'
  }, [order?.tier])

  // Merge historical logs with streamed logs, avoiding duplicates
  const allLogs = useMemo(() => {
    const historicalLogs = order?.provisioningLogs || []
    const historicalLogIds = new Set(historicalLogs.map(l => l.id))

    // Add only new streamed logs that aren't in historical
    const newStreamedLogs = streamedLogs.filter(l => !historicalLogIds.has(l.id))

    // Combine and sort by timestamp
    const combined = [
      ...historicalLogs.map(l => ({
        id: l.id,
        level: l.level,
        step: l.step,
        message: l.message,
        timestamp: new Date(l.timestamp),
      })),
      ...newStreamedLogs,
    ]

    return combined.sort(
      (a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
    )
  }, [order?.provisioningLogs, streamedLogs])

  // Note: Auto-scroll is handled inside ProvisioningLogs component via logContainerRef

  const handleCredentialsSubmit = async (ip: string, password: string, port: number) => {
    await updateOrder.mutateAsync({
      id: orderId,
      data: {
        serverIp: ip,
        serverPassword: password,
        sshPort: port,
        status: OrderStatus.SERVER_READY, // Mark as ready after saving credentials
      },
    })
  }

  const handleProvisioningConfigSave = async (config: ProvisioningConfig) => {
    await updateOrder.mutateAsync({
      id: orderId,
      data: {
        customer: config.customer,
        companyName: config.companyName,
        licenseKey: config.licenseKey,
      },
    })
  }

  const handleTriggerProvisioning = async () => {
    try {
      await triggerProvision.mutateAsync(orderId)
    } catch (err) {
      console.error('Failed to trigger provisioning:', err)
      const message = err instanceof Error ? err.message : 'Failed to start provisioning'
      alert(message)
    }
  }

  const handleAutomationModeChange = async (action: 'auto' | 'manual' | 'pause' | 'resume') => {
    await changeAutomationMode.mutateAsync({ orderId, action })
  }

  const handleDnsVerify = async () => {
    await triggerDnsVerification.mutateAsync(orderId)
  }

  const handleDnsSkip = async () => {
    await skipDnsVerification.mutateAsync(orderId)
  }

  const handleDeleteOrder = async () => {
    await deleteOrder.mutateAsync(orderId)
    router.push('/admin/orders')
  }

  // Loading state
  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-[50vh]">
        <div className="flex flex-col items-center gap-4">
          <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
          <p className="text-muted-foreground">Loading order details...</p>
        </div>
      </div>
    )
  }

  // Error state
  if (isError || !order) {
    return (
      <div className="flex items-center justify-center h-[50vh]">
        <div className="flex flex-col items-center gap-4 text-center">
          <AlertCircle className="h-8 w-8 text-destructive" />
          <div>
            <p className="font-medium text-destructive">Failed to load order</p>
            <p className="text-sm text-muted-foreground">
              {error instanceof Error ? error.message : 'Order not found'}
            </p>
          </div>
          <div className="flex gap-2">
            <Button variant="outline" onClick={() => router.back()}>
              <ArrowLeft className="h-4 w-4 mr-2" />
              Go Back
            </Button>
            <RefreshButton
              variant="outline"
              onClick={() => refetch()}
              isRefreshing={isFetching}
              label="Retry"
            />
          </div>
        </div>
      </div>
    )
  }

  // Always show credentials form - allows entering/updating server details at any stage
  const showCredentialsForm = order.status !== OrderStatus.FULFILLED && order.status !== OrderStatus.EMAIL_CONFIGURED
  const showProvisionButton = order.status === OrderStatus.SERVER_READY || order.status === OrderStatus.DNS_READY || order.status === OrderStatus.FAILED
  // Provisioning config is editable before provisioning starts
  const isProvisioningConfigEditable = !([OrderStatus.PROVISIONING, OrderStatus.FULFILLED, OrderStatus.EMAIL_CONFIGURED] as OrderStatus[]).includes(order.status)
  const showLogs = order.status === OrderStatus.PROVISIONING ||
                   order.status === OrderStatus.FULFILLED ||
                   order.status === OrderStatus.EMAIL_CONFIGURED ||
                   order.status === OrderStatus.FAILED

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Link href="/admin/orders">
          <Button variant="ghost" size="icon">
            <ArrowLeft className="h-5 w-5" />
          </Button>
        </Link>
        <div className="flex-1">
          <div className="flex items-center gap-3">
            <h1 className="text-2xl font-bold">{order.domain}</h1>
            <StatusBadge status={order.status} />
          </div>
          <p className="text-muted-foreground">Order #{orderId.slice(0, 8)}...</p>
        </div>
        <div className="flex gap-2">
          <RefreshButton
            onClick={() => refetch()}
            isRefreshing={isFetching}
          />
          {showProvisionButton && (
            <Button
              onClick={handleTriggerProvisioning}
              disabled={triggerProvision.isPending}
            >
              {triggerProvision.isPending ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Starting...
                </>
              ) : (
                <>
                  <Zap className="mr-2 h-4 w-4" />
                  {order.status === OrderStatus.FAILED ? 'Retry Provisioning' : 'Start Provisioning'}
                </>
              )}
            </Button>
          )}
          {order.portainerUrl && (
            <Button variant="outline" asChild>
              <a href={order.portainerUrl} target="_blank" rel="noopener noreferrer">
                <ExternalLink className="mr-2 h-4 w-4" />
                Portainer
              </a>
            </Button>
          )}
          {order.dashboardUrl && (
            <Button variant="outline" asChild>
              <a href={order.dashboardUrl} target="_blank" rel="noopener noreferrer">
                <ExternalLink className="mr-2 h-4 w-4" />
                Dashboard
              </a>
            </Button>
          )}
          <Button
            variant="outline"
            size="sm"
            onClick={() => setShowDeleteDialog(true)}
            className="text-destructive hover:text-destructive hover:bg-destructive/10"
          >
            <Trash2 className="h-4 w-4 mr-2" />
            Delete
          </Button>
        </div>
      </div>

      {/* Delete confirmation dialog */}
      <SliderConfirmDialog
        open={showDeleteDialog}
        onOpenChange={setShowDeleteDialog}
        title="Delete Order"
        description={`This will permanently delete order "${order.domain}" and all related records (logs, jobs, DNS verification). This action cannot be undone. The actual server will NOT be affected.`}
        confirmText="Delete Order"
        variant="destructive"
        onConfirm={handleDeleteOrder}
        isLoading={deleteOrder.isPending}
      />

      {/* Order Timeline - Horizontal progress bar at top */}
      <div className="rounded-lg border bg-card p-4">
        <OrderTimeline
          status={order.status}
          timestamps={{
            createdAt: order.createdAt,
            serverReadyAt: order.serverReadyAt,
            provisioningStartedAt: order.provisioningStartedAt,
            completedAt: order.completedAt,
          }}
        />
      </div>

      {/* Failure reason banner */}
      {order.status === OrderStatus.FAILED && order.failureReason && (
        <div className="flex items-start gap-3 rounded-lg border border-red-200 bg-red-50 p-4">
          <AlertCircle className="h-5 w-5 text-red-500 mt-0.5" />
          <div>
            <p className="font-medium text-red-800">Provisioning Failed</p>
            <p className="text-sm text-red-700">{order.failureReason}</p>
          </div>
        </div>
      )}

      {/* Provisioning Logs - Prominent display at top when active */}
      {showLogs && (
        <ProvisioningLogs
          logs={allLogs}
          isLive={isProvisioning}
          isConnected={isConnected}
          isComplete={isComplete}
          finalStatus={order.status === OrderStatus.FULFILLED ? 'FULFILLED' : order.status === OrderStatus.FAILED ? 'FAILED' : null}
          onReconnect={reconnect}
        />
      )}

      {/* Automation Controls */}
      <AutomationControls
        orderId={orderId}
        mode={order.automationMode}
        pausedAt={order.automationPausedAt}
        pausedReason={order.automationPausedReason}
        source={order.source}
        status={order.status}
        onModeChange={handleAutomationModeChange}
      />

      {/* Order info cards */}
      <div className="grid gap-6 lg:grid-cols-3">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <User className="h-5 w-5" />
              Customer
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-2">
            <p className="font-medium">{order.user.name || order.user.company || 'N/A'}</p>
            <p className="text-sm text-muted-foreground">{order.user.email}</p>
            {order.user.company && order.user.name && (
              <p className="text-sm text-muted-foreground">{order.user.company}</p>
            )}
            <Link href={`/admin/customers/${order.user.id}`}>
              <Button variant="link" className="px-0 h-auto">
                View Customer Profile
              </Button>
            </Link>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Globe className="h-5 w-5" />
              Domain & Tier
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-2">
            <p className="font-medium">{order.domain}</p>
            <span className="inline-flex items-center rounded-full bg-primary/10 px-2 py-1 text-xs font-medium text-primary">
              {tierLabel}
            </span>
          </CardContent>
        </Card>

        <ServerCard
          orderId={orderId}
          serverIp={order.serverIp}
          sshPort={order.sshPort}
          showTestButton={showProvisionButton}
        />
      </div>

      {/* Tools list - editable before provisioning */}
      <ToolsEditor
        tools={order.tools}
        onSave={async (tools) => {
          await updateOrder.mutateAsync({ id: orderId, data: { tools } })
        }}
        isEditable={!([OrderStatus.PROVISIONING, OrderStatus.FULFILLED, OrderStatus.EMAIL_CONFIGURED] as OrderStatus[]).includes(order.status)}
        isSaving={updateOrder.isPending}
      />

      {/* Provisioning config form - customer/license info */}
      <ProvisioningConfigForm
        order={order}
        onSave={handleProvisioningConfigSave}
        isEditable={isProvisioningConfigEditable}
        isSaving={updateOrder.isPending}
      />

      {/* Server credentials form (show for AWAITING_SERVER or SERVER_READY status) */}
      {showCredentialsForm && (
        <ServerCredentialsForm
          orderId={orderId}
          initialIp={order.serverIp || undefined}
          initialPort={order.sshPort}
          hasCredentials={!!order.serverIp}
          onSubmit={handleCredentialsSubmit}
          isLoading={updateOrder.isPending}
        />
      )}

      {/* Netcup Server Linking & Quick Actions */}
      {order.serverIp && (
        <Card className="rounded-xl">
          <CardHeader>
            <div className="flex items-center gap-3">
              <div className="p-2 rounded-lg bg-violet-100 dark:bg-violet-900/30">
                <Server className="h-4 w-4 text-violet-600 dark:text-violet-400" />
              </div>
              <div>
                <CardTitle className="text-lg">Netcup Server</CardTitle>
                <CardDescription>Link this order to a Netcup server for management</CardDescription>
              </div>
            </div>
          </CardHeader>
          <CardContent className="space-y-4">
            <NetcupServerLink
              orderId={orderId}
              currentNetcupServerId={order.netcupServerId}
              serverIp={order.serverIp}
              onLinked={() => refetch()}
            />
            {order.netcupServerId && (
              <ServerQuickActions
                netcupServerId={order.netcupServerId}
                serverIp={order.serverIp}
              />
            )}
          </CardContent>
        </Card>
      )}

      {/* Server Metrics (show when Netcup server is linked) */}
      {order.netcupServerId && (
        <ServerMetricsPanel
          netcupServerId={order.netcupServerId}
          serverName={order.domain}
        />
      )}

      {/* DNS Verification Panel (show when server is configured) */}
      {order.serverIp && (
        <DnsVerificationPanel
          orderId={orderId}
          domain={order.domain}
          serverIp={order.serverIp}
          requiredSubdomains={dnsData?.requiredSubdomains || []}
          verification={dnsData?.verification || null}
          onVerify={handleDnsVerify}
          onSkip={handleDnsSkip}
          isVerifying={triggerDnsVerification.isPending}
          isSkipping={skipDnsVerification.isPending}
        />
      )}

      {/* Portainer & Container Management (show for provisioned/completed orders) */}
      {(order.status === OrderStatus.FULFILLED ||
        order.status === OrderStatus.EMAIL_CONFIGURED ||
        order.status === OrderStatus.PROVISIONING) && (
        <div className="space-y-6">
          <PortainerCredentialsPanel orderId={orderId} />
          <ContainerList orderId={orderId} />
        </div>
      )}

      {/* Jobs history */}
      {order.jobs && order.jobs.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>Job History</CardTitle>
            <CardDescription>Recent provisioning job attempts</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {order.jobs.map((job) => (
                <div
                  key={job.id}
                  className="flex items-center justify-between rounded-lg border p-3"
                >
                  <div className="flex items-center gap-3">
                    <div
                      className={`h-2 w-2 rounded-full ${
                        job.status === 'COMPLETED'
                          ? 'bg-green-500'
                          : job.status === 'FAILED'
                          ? 'bg-red-500'
                          : job.status === 'RUNNING'
                          ? 'bg-blue-500'
                          : 'bg-gray-400'
                      }`}
                    />
                    <div>
                      <p className="text-sm font-medium">
                        Attempt {job.attempt} of {job.maxAttempts}
                      </p>
                      <p className="text-xs text-muted-foreground">
                        {new Date(job.createdAt).toLocaleString()}
                      </p>
                    </div>
                  </div>
                  <div className="text-right">
                    <span
                      className={`text-xs font-medium ${
                        job.status === 'COMPLETED'
                          ? 'text-green-600'
                          : job.status === 'FAILED'
                          ? 'text-red-600'
                          : job.status === 'RUNNING'
                          ? 'text-blue-600'
                          : 'text-gray-600'
                      }`}
                    >
                      {job.status}
                    </span>
                    {job.error && (
                      <p className="text-xs text-red-500 max-w-xs truncate">{job.error}</p>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  )
}
