'use client'

import { useState } from 'react'
import { RefreshCw, Download, Loader2 } from 'lucide-react'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { useContainerLogs, type Container } from '@/hooks/use-portainer'

interface ContainerLogsDialogProps {
  orderId: string
  container: Container
  open: boolean
  onOpenChange: (open: boolean) => void
}

const TAIL_OPTIONS = [
  { value: 100, label: 'Last 100 lines' },
  { value: 500, label: 'Last 500 lines' },
  { value: 1000, label: 'Last 1000 lines' },
  { value: 2000, label: 'Last 2000 lines' },
]

export function ContainerLogsDialog({
  orderId,
  container,
  open,
  onOpenChange,
}: ContainerLogsDialogProps) {
  const [tail, setTail] = useState(100)
  const { data: logs, isLoading, refetch } = useContainerLogs(orderId, container.id, tail)

  const handleDownload = () => {
    if (!logs) return
    const blob = new Blob([logs], { type: 'text/plain' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${container.name}-logs.txt`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[80vh] flex flex-col">
        <DialogHeader>
          <DialogTitle>Container Logs: {container.name}</DialogTitle>
          <DialogDescription className="font-mono text-xs">
            ID: {container.shortId}
          </DialogDescription>
        </DialogHeader>

        <div className="flex items-center justify-between gap-4 py-2">
          <select
            value={tail}
            onChange={(e) => setTail(parseInt(e.target.value, 10))}
            className="h-9 px-3 rounded-md border border-input bg-background text-sm"
          >
            {TAIL_OPTIONS.map((option) => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>

          <div className="flex items-center gap-2">
            <Button variant="outline" size="sm" onClick={() => refetch()}>
              <RefreshCw className="h-4 w-4 mr-2" />
              Refresh
            </Button>
            <Button variant="outline" size="sm" onClick={handleDownload} disabled={!logs}>
              <Download className="h-4 w-4 mr-2" />
              Download
            </Button>
          </div>
        </div>

        <div className="flex-1 min-h-0">
          {isLoading ? (
            <div className="flex items-center justify-center h-64">
              <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
            </div>
          ) : logs ? (
            <div className="h-[50vh] overflow-auto rounded-md border bg-slate-950">
              <pre className="p-4 text-xs font-mono text-slate-200 whitespace-pre-wrap break-all">
                {logs || 'No logs available'}
              </pre>
            </div>
          ) : (
            <div className="flex items-center justify-center h-64 text-muted-foreground">
              No logs available
            </div>
          )}
        </div>
      </DialogContent>
    </Dialog>
  )
}
