'use client'

import { useState } from 'react'
import { useRouter, usePathname } from 'next/navigation'
import {
  Play,
  Square,
  RefreshCw,
  Trash2,
  FileText,
  Loader2,
  Box,
  AlertCircle,
  ExternalLink,
} from 'lucide-react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import {
  useContainers,
  useContainerAction,
  useRemoveContainer,
  usePortainerCredentials,
  useContainerStats,
  type Container,
  type ContainerStats,
} from '@/hooks/use-portainer'
import { ContainerLogsDialog } from './container-logs-dialog'

interface ContainerListProps {
  orderId: string
}

function getStateColor(state: string): string {
  switch (state.toLowerCase()) {
    case 'running':
      return 'bg-green-100 text-green-800 border-green-200'
    case 'exited':
      return 'bg-red-100 text-red-800 border-red-200'
    case 'paused':
      return 'bg-yellow-100 text-yellow-800 border-yellow-200'
    case 'restarting':
      return 'bg-blue-100 text-blue-800 border-blue-200'
    case 'created':
      return 'bg-gray-100 text-gray-800 border-gray-200'
    default:
      return 'bg-gray-100 text-gray-800 border-gray-200'
  }
}

function formatRelativeTime(timestamp: number): string {
  const now = Date.now()
  const diff = now - timestamp * 1000
  const seconds = Math.floor(diff / 1000)
  const minutes = Math.floor(seconds / 60)
  const hours = Math.floor(minutes / 60)
  const days = Math.floor(hours / 24)

  if (days > 0) return `${days}d ago`
  if (hours > 0) return `${hours}h ago`
  if (minutes > 0) return `${minutes}m ago`
  return 'just now'
}

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]}`
}

export function ContainerList({ orderId }: ContainerListProps) {
  const router = useRouter()
  const pathname = usePathname()
  const { data: credentials } = usePortainerCredentials(orderId)
  const {
    data: containers,
    isLoading,
    error,
    refetch,
  } = useContainers(orderId, credentials?.isConfigured)
  const { data: stats } = useContainerStats(orderId, credentials?.isConfigured)
  const containerAction = useContainerAction()
  const removeContainer = useRemoveContainer()

  const [selectedContainer, setSelectedContainer] = useState<Container | null>(null)
  const [showLogsFor, setShowLogsFor] = useState<Container | null>(null)
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
  const [actionInProgress, setActionInProgress] = useState<string | null>(null)

  // Determine the base path for container detail page
  const basePath = pathname.includes('/admin/servers/')
    ? `/admin/servers/${orderId}`
    : `/admin/orders/${orderId}`

  const navigateToContainer = (containerId: string) => {
    router.push(`${basePath}/containers/${containerId}`)
  }

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

  const handleDelete = async () => {
    if (!selectedContainer) return
    setActionInProgress(selectedContainer.id)
    try {
      await removeContainer.mutateAsync({
        orderId,
        containerId: selectedContainer.id,
        force: true,
      })
      setShowDeleteConfirm(false)
      setSelectedContainer(null)
    } catch (err) {
      console.error('Failed to remove container:', err)
    } finally {
      setActionInProgress(null)
    }
  }

  if (!credentials?.isConfigured) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Box className="h-5 w-5" />
            Containers
          </CardTitle>
          <CardDescription>
            Configure Portainer credentials to view containers
          </CardDescription>
        </CardHeader>
      </Card>
    )
  }

  if (isLoading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Box className="h-5 w-5" />
            Containers
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center py-8">
            <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
          </div>
        </CardContent>
      </Card>
    )
  }

  if (error) {
    return (
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Box className="h-5 w-5" />
            Containers
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center gap-2 text-destructive">
            <AlertCircle className="h-4 w-4" />
            <span>Failed to load containers: {error.message}</span>
          </div>
        </CardContent>
      </Card>
    )
  }

  return (
    <>
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="flex items-center gap-2">
                <Box className="h-5 w-5" />
                Containers
              </CardTitle>
              <CardDescription>
                {containers?.length || 0} containers found
              </CardDescription>
            </div>
            <Button variant="outline" size="sm" onClick={() => refetch()}>
              <RefreshCw className="h-4 w-4 mr-2" />
              Refresh
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          {containers && containers.length > 0 ? (
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead>
                  <tr className="border-b">
                    <th className="text-left py-3 px-2 font-medium">Name</th>
                    <th className="text-left py-3 px-2 font-medium">Image</th>
                    <th className="text-left py-3 px-2 font-medium">State</th>
                    <th className="text-left py-3 px-2 font-medium">CPU</th>
                    <th className="text-left py-3 px-2 font-medium">Memory</th>
                    <th className="text-left py-3 px-2 font-medium">Created</th>
                    <th className="text-right py-3 px-2 font-medium">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {containers.map((container) => (
                    <tr
                      key={container.id}
                      className="border-b last:border-0 hover:bg-muted/50 transition-colors"
                    >
                      <td className="py-3 px-2">
                        <button
                          onClick={() => navigateToContainer(container.id)}
                          className="flex flex-col text-left hover:text-primary transition-colors group"
                        >
                          <span className="font-medium group-hover:underline flex items-center gap-1">
                            {container.name}
                            <ExternalLink className="h-3 w-3 opacity-0 group-hover:opacity-100 transition-opacity" />
                          </span>
                          <span className="text-xs text-muted-foreground font-mono">
                            {container.shortId}
                          </span>
                        </button>
                      </td>
                      <td className="py-3 px-2">
                        <span className="text-sm font-mono text-muted-foreground">
                          {container.image.length > 40
                            ? container.image.substring(0, 40) + '...'
                            : container.image}
                        </span>
                      </td>
                      <td className="py-3 px-2">
                        <Badge variant="outline" className={getStateColor(container.state)}>
                          {container.state}
                        </Badge>
                      </td>
                      <td className="py-3 px-2">
                        {container.state === 'running' && stats?.[container.id] ? (
                          <span className="text-sm font-mono">
                            {stats[container.id].cpuPercent.toFixed(1)}%
                          </span>
                        ) : (
                          <span className="text-sm text-muted-foreground">—</span>
                        )}
                      </td>
                      <td className="py-3 px-2">
                        {container.state === 'running' && stats?.[container.id] ? (
                          <div className="text-sm">
                            <span className="font-mono">
                              {formatBytes(stats[container.id].memoryUsage)}
                            </span>
                            <span className="text-muted-foreground">
                              {' '}/ {formatBytes(stats[container.id].memoryLimit)}
                            </span>
                            <span className="text-xs text-muted-foreground ml-1">
                              ({stats[container.id].memoryPercent.toFixed(1)}%)
                            </span>
                          </div>
                        ) : (
                          <span className="text-sm text-muted-foreground">—</span>
                        )}
                      </td>
                      <td className="py-3 px-2">
                        <span className="text-sm text-muted-foreground">
                          {formatRelativeTime(container.created)}
                        </span>
                      </td>
                      <td className="py-3 px-2 text-right">
                        <div className="flex items-center justify-end gap-1">
                          {actionInProgress === container.id ? (
                            <Loader2 className="h-4 w-4 animate-spin" />
                          ) : (
                            <>
                              {container.state === 'running' ? (
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  className="h-8 w-8 p-0"
                                  onClick={() => handleAction(container, 'stop')}
                                  title="Stop"
                                >
                                  <Square className="h-4 w-4" />
                                </Button>
                              ) : (
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  className="h-8 w-8 p-0"
                                  onClick={() => handleAction(container, 'start')}
                                  title="Start"
                                >
                                  <Play className="h-4 w-4" />
                                </Button>
                              )}
                              <Button
                                variant="ghost"
                                size="sm"
                                className="h-8 w-8 p-0"
                                onClick={() => handleAction(container, 'restart')}
                                title="Restart"
                              >
                                <RefreshCw className="h-4 w-4" />
                              </Button>
                              <Button
                                variant="ghost"
                                size="sm"
                                className="h-8 w-8 p-0"
                                onClick={() => setShowLogsFor(container)}
                                title="View Logs"
                              >
                                <FileText className="h-4 w-4" />
                              </Button>
                              <Button
                                variant="ghost"
                                size="sm"
                                className="h-8 w-8 p-0 text-destructive hover:text-destructive"
                                onClick={() => {
                                  setSelectedContainer(container)
                                  setShowDeleteConfirm(true)
                                }}
                                title="Remove"
                              >
                                <Trash2 className="h-4 w-4" />
                              </Button>
                            </>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          ) : (
            <div className="text-center py-8 text-muted-foreground">
              No containers found
            </div>
          )}
        </CardContent>
      </Card>

      {/* Logs Dialog */}
      {showLogsFor && (
        <ContainerLogsDialog
          orderId={orderId}
          container={showLogsFor}
          open={!!showLogsFor}
          onOpenChange={(open) => !open && setShowLogsFor(null)}
        />
      )}

      {/* Delete Confirmation Dialog */}
      <Dialog open={showDeleteConfirm} onOpenChange={setShowDeleteConfirm}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Remove Container</DialogTitle>
            <DialogDescription>
              Are you sure you want to remove container &quot;{selectedContainer?.name}&quot;? This action
              cannot be undone.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDeleteConfirm(false)}>
              Cancel
            </Button>
            <Button
              variant="destructive"
              onClick={handleDelete}
              disabled={actionInProgress === selectedContainer?.id}
            >
              {actionInProgress === selectedContainer?.id ? (
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              ) : null}
              Remove
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  )
}
