'use client'

import { useState, useEffect, useRef } from 'react'
import { useParams, useRouter } from 'next/navigation'
import Link from 'next/link'
import {
  ArrowLeft,
  Box,
  Play,
  Square,
  RefreshCw,
  Trash2,
  Loader2,
  Clock,
  HardDrive,
  Cpu,
  MemoryStick,
  Network,
  Download,
  AlertTriangle
} from 'lucide-react'
import {
  useEnterpriseClient,
  useClientServer,
  useContainer,
  useContainerLogs,
  useContainerAction,
  useRemoveContainer
} from '@/hooks/use-enterprise-clients'

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(dateString: string): string {
  return new Date(dateString).toLocaleString()
}

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

  const [tail, setTail] = useState(500)
  const [autoScroll, setAutoScroll] = useState(true)
  const [actionLoading, setActionLoading] = useState<string | null>(null)
  const logsEndRef = useRef<HTMLDivElement>(null)

  const { data: client, isLoading: clientLoading } = useEnterpriseClient(clientId)
  const { data: server, isLoading: serverLoading } = useClientServer(clientId, serverId)
  const { data: container, isLoading: containerLoading, refetch: refetchContainer } = useContainer(clientId, serverId, containerId)
  const { data: logsData, isLoading: logsLoading, refetch: refetchLogs } = useContainerLogs(clientId, serverId, containerId, tail)
  const containerAction = useContainerAction()
  const removeContainer = useRemoveContainer()

  const isLoading = clientLoading || serverLoading || containerLoading

  // Auto-scroll to bottom when logs update
  useEffect(() => {
    if (autoScroll && logsEndRef.current) {
      logsEndRef.current.scrollIntoView({ behavior: 'smooth' })
    }
  }, [logsData, autoScroll])

  // Auto-refresh logs every 5 seconds
  useEffect(() => {
    const interval = setInterval(() => {
      refetchLogs()
      refetchContainer()
    }, 5000)
    return () => clearInterval(interval)
  }, [refetchLogs, refetchContainer])

  const handleAction = async (action: 'start' | 'stop' | 'restart') => {
    setActionLoading(action)
    try {
      await containerAction.mutateAsync({
        clientId,
        serverId,
        containerId,
        action,
      })
      // Refetch container data after action
      setTimeout(() => refetchContainer(), 1000)
    } catch (err) {
      console.error(`Failed to ${action} container:`, err)
    } finally {
      setActionLoading(null)
    }
  }

  const handleRemove = async () => {
    if (!confirm('Are you sure you want to remove this container? This action cannot be undone.')) return

    setActionLoading('remove')
    try {
      await removeContainer.mutateAsync({
        clientId,
        serverId,
        containerId,
        force: true,
      })
      router.push(`/admin/enterprise-clients/${clientId}/servers/${serverId}`)
    } catch (err) {
      console.error('Failed to remove container:', err)
    } finally {
      setActionLoading(null)
    }
  }

  const handleDownloadLogs = () => {
    if (!logsData?.logs || !container) return

    const blob = new Blob([logsData.logs], { type: 'text/plain' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${container.name || container.id.slice(0, 12)}-logs.txt`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="h-8 w-8 animate-spin text-gray-400" />
      </div>
    )
  }

  if (!client || !server || !container) {
    return (
      <div className="text-center py-12">
        <h2 className="text-lg font-medium text-gray-900">Container not found</h2>
        <p className="mt-1 text-sm text-gray-500">
          The container you&apos;re looking for doesn&apos;t exist or has been removed.
        </p>
        <Link
          href={`/admin/enterprise-clients/${clientId}/servers/${serverId}`}
          className="mt-4 inline-flex items-center text-blue-600 hover:underline"
        >
          <ArrowLeft className="h-4 w-4 mr-1" />
          Back to server
        </Link>
      </div>
    )
  }

  const isRunning = container.state.Running
  const name = container.name || container.id.slice(0, 12)
  const stateStatus = container.state.Status

  const statusColor = isRunning
    ? 'bg-green-100 text-green-800'
    : stateStatus === 'exited'
    ? 'bg-red-100 text-red-800'
    : 'bg-yellow-100 text-yellow-800'

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Link
            href={`/admin/enterprise-clients/${clientId}/servers/${serverId}`}
            className="text-gray-500 hover:text-gray-700"
          >
            <ArrowLeft className="h-5 w-5" />
          </Link>
          <div>
            <div className="flex items-center gap-2">
              <Box className={`h-5 w-5 ${isRunning ? 'text-green-500' : 'text-gray-400'}`} />
              <h1 className="text-2xl font-bold text-gray-900">{name}</h1>
              <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${statusColor}`}>
                {stateStatus}
              </span>
            </div>
            <p className="text-sm text-gray-500 mt-1">
              {server.nickname || server.netcupServerId} &bull; {container.image}
            </p>
          </div>
        </div>

        {/* Actions */}
        <div className="flex items-center gap-2">
          {isRunning ? (
            <button
              onClick={() => handleAction('stop')}
              disabled={actionLoading !== null}
              className="inline-flex items-center px-3 py-1.5 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50"
            >
              {actionLoading === 'stop' ? (
                <Loader2 className="h-4 w-4 mr-1 animate-spin" />
              ) : (
                <Square className="h-4 w-4 mr-1 text-red-600" />
              )}
              Stop
            </button>
          ) : (
            <button
              onClick={() => handleAction('start')}
              disabled={actionLoading !== null}
              className="inline-flex items-center px-3 py-1.5 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50"
            >
              {actionLoading === 'start' ? (
                <Loader2 className="h-4 w-4 mr-1 animate-spin" />
              ) : (
                <Play className="h-4 w-4 mr-1 text-green-600" />
              )}
              Start
            </button>
          )}
          <button
            onClick={() => handleAction('restart')}
            disabled={actionLoading !== null || !isRunning}
            className="inline-flex items-center px-3 py-1.5 border border-gray-300 rounded-md text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50"
          >
            {actionLoading === 'restart' ? (
              <Loader2 className="h-4 w-4 mr-1 animate-spin" />
            ) : (
              <RefreshCw className="h-4 w-4 mr-1" />
            )}
            Restart
          </button>
          <button
            onClick={handleRemove}
            disabled={actionLoading !== null}
            className="inline-flex items-center px-3 py-1.5 border border-red-300 rounded-md text-sm font-medium text-red-700 bg-white hover:bg-red-50 disabled:opacity-50"
          >
            {actionLoading === 'remove' ? (
              <Loader2 className="h-4 w-4 mr-1 animate-spin" />
            ) : (
              <Trash2 className="h-4 w-4 mr-1" />
            )}
            Remove
          </button>
        </div>
      </div>

      {/* Container Info */}
      <div className="bg-white rounded-lg border border-gray-200 p-6">
        <h2 className="text-lg font-medium text-gray-900 mb-4">Container Information</h2>
        <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
          <div>
            <div className="flex items-center gap-2 text-sm text-gray-500 mb-1">
              <HardDrive className="h-4 w-4" />
              Container ID
            </div>
            <code className="text-sm bg-gray-100 px-2 py-0.5 rounded">{container.id.slice(0, 12)}</code>
          </div>
          <div>
            <div className="flex items-center gap-2 text-sm text-gray-500 mb-1">
              <Clock className="h-4 w-4" />
              Created
            </div>
            <span className="text-sm font-medium">{formatDate(container.created)}</span>
          </div>
          {container.stats && (
            <>
              <div>
                <div className="flex items-center gap-2 text-sm text-gray-500 mb-1">
                  <Cpu className="h-4 w-4" />
                  CPU Usage
                </div>
                <span className="text-sm font-medium">{container.stats.cpuPercent.toFixed(2)}%</span>
              </div>
              <div>
                <div className="flex items-center gap-2 text-sm text-gray-500 mb-1">
                  <MemoryStick className="h-4 w-4" />
                  Memory
                </div>
                <span className="text-sm font-medium">
                  {formatBytes(container.stats.memoryUsage)} / {formatBytes(container.stats.memoryLimit)}
                </span>
              </div>
            </>
          )}
        </div>

        {/* Ports */}
        {container.networkSettings?.ports && Object.keys(container.networkSettings.ports).length > 0 && (
          <div className="mt-6">
            <div className="flex items-center gap-2 text-sm text-gray-500 mb-2">
              <Network className="h-4 w-4" />
              Ports
            </div>
            <div className="flex flex-wrap gap-2">
              {Object.entries(container.networkSettings.ports).map(([containerPort, hostBindings]) => (
                <span
                  key={containerPort}
                  className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800"
                >
                  {containerPort}
                  {hostBindings && hostBindings.length > 0 && ` -> ${hostBindings[0].HostPort}`}
                </span>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Logs */}
      <div className="bg-white rounded-lg border border-gray-200 p-6">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-medium text-gray-900">Logs</h2>
          <div className="flex items-center gap-4">
            {/* Tail selector */}
            <div className="flex items-center gap-2">
              <span className="text-sm text-gray-500">Lines:</span>
              <select
                value={tail}
                onChange={(e) => setTail(Number(e.target.value))}
                className="text-sm border border-gray-300 rounded-md px-2 py-1"
              >
                <option value={100}>100</option>
                <option value={500}>500</option>
                <option value={1000}>1000</option>
                <option value={5000}>5000</option>
              </select>
            </div>

            {/* Auto-scroll toggle */}
            <label className="flex items-center gap-2 text-sm">
              <input
                type="checkbox"
                checked={autoScroll}
                onChange={(e) => setAutoScroll(e.target.checked)}
                className="rounded border-gray-300"
              />
              Auto-scroll
            </label>

            {/* Refresh button */}
            <button
              onClick={() => refetchLogs()}
              disabled={logsLoading}
              className="inline-flex items-center text-sm text-blue-600 hover:text-blue-800 disabled:opacity-50"
            >
              {logsLoading ? (
                <Loader2 className="h-4 w-4 mr-1 animate-spin" />
              ) : (
                <RefreshCw className="h-4 w-4 mr-1" />
              )}
              Refresh
            </button>

            {/* Download button */}
            <button
              onClick={handleDownloadLogs}
              disabled={!logsData?.logs}
              className="inline-flex items-center text-sm text-blue-600 hover:text-blue-800 disabled:opacity-50"
            >
              <Download className="h-4 w-4 mr-1" />
              Download
            </button>
          </div>
        </div>

        {/* Log output */}
        <div className="bg-gray-900 rounded-lg p-4 h-[500px] overflow-auto font-mono text-sm">
          {logsLoading && !logsData ? (
            <div className="flex items-center justify-center h-full text-gray-400">
              <Loader2 className="h-6 w-6 animate-spin mr-2" />
              Loading logs...
            </div>
          ) : logsData?.logs ? (
            <pre className="text-gray-100 whitespace-pre-wrap break-words">
              {logsData.logs}
            </pre>
          ) : (
            <div className="flex items-center justify-center h-full text-gray-400">
              No logs available
            </div>
          )}
          <div ref={logsEndRef} />
        </div>
      </div>

      {/* Warning for stopped containers */}
      {!isRunning && (
        <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
          <div className="flex items-start">
            <AlertTriangle className="h-5 w-5 text-yellow-600 mt-0.5" />
            <div className="ml-3">
              <h3 className="text-sm font-medium text-yellow-800">Container is not running</h3>
              <p className="text-sm text-yellow-700 mt-1">
                This container is currently stopped. Start it to see live logs and resource usage.
              </p>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
