'use client'

import { useState, useEffect, useRef } from 'react'
import {
  X,
  RefreshCw,
  Download,
  Loader2,
  AlertCircle
} from 'lucide-react'
import { useContainerLogs } from '@/hooks/use-enterprise-clients'
import type { ContainerSummary } from '@/lib/api/admin'

interface EnterpriseContainerLogsDialogProps {
  clientId: string
  serverId: string
  container: ContainerSummary
  open: boolean
  onClose: () => void
}

const TAIL_OPTIONS = [100, 500, 1000, 5000]

export function EnterpriseContainerLogsDialog({
  clientId,
  serverId,
  container,
  open,
  onClose,
}: EnterpriseContainerLogsDialogProps) {
  const [tail, setTail] = useState(500)
  const [autoScroll, setAutoScroll] = useState(true)
  const logsContainerRef = useRef<HTMLPreElement>(null)

  const { data, isLoading, error, refetch } = useContainerLogs(
    clientId,
    serverId,
    container.id,
    tail
  )

  // Auto-scroll to bottom when logs update
  useEffect(() => {
    if (autoScroll && logsContainerRef.current) {
      logsContainerRef.current.scrollTop = logsContainerRef.current.scrollHeight
    }
  }, [data?.logs, autoScroll])

  const handleDownload = () => {
    if (!data?.logs) return

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

  if (!open) return null

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/50"
        onClick={onClose}
      />

      {/* Dialog */}
      <div className="relative bg-white rounded-lg shadow-xl w-full max-w-5xl max-h-[90vh] flex flex-col mx-4">
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b">
          <div>
            <h2 className="text-lg font-semibold text-gray-900">
              Container Logs
            </h2>
            <p className="text-sm text-gray-500 mt-1">
              {container.names[0] || container.id.slice(0, 12)}
            </p>
          </div>
          <button
            onClick={onClose}
            className="p-2 text-gray-400 hover:text-gray-600 rounded"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Toolbar */}
        <div className="flex items-center justify-between px-6 py-3 bg-gray-50 border-b">
          <div className="flex items-center gap-4">
            {/* Tail selector */}
            <div className="flex items-center gap-2">
              <label className="text-sm text-gray-600">Lines:</label>
              <select
                value={tail}
                onChange={(e) => setTail(Number(e.target.value))}
                className="border border-gray-300 rounded px-2 py-1 text-sm"
              >
                {TAIL_OPTIONS.map((opt) => (
                  <option key={opt} value={opt}>
                    {opt}
                  </option>
                ))}
              </select>
            </div>

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

          <div className="flex items-center gap-2">
            <button
              onClick={() => refetch()}
              disabled={isLoading}
              className="inline-flex items-center px-3 py-1.5 border border-gray-300 rounded text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50"
            >
              {isLoading ? (
                <Loader2 className="h-4 w-4 mr-1 animate-spin" />
              ) : (
                <RefreshCw className="h-4 w-4 mr-1" />
              )}
              Refresh
            </button>
            <button
              onClick={handleDownload}
              disabled={!data?.logs}
              className="inline-flex items-center px-3 py-1.5 border border-gray-300 rounded text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50"
            >
              <Download className="h-4 w-4 mr-1" />
              Download
            </button>
          </div>
        </div>

        {/* Logs Content */}
        <div className="flex-1 overflow-hidden">
          {error ? (
            <div className="flex items-center justify-center h-full text-red-500">
              <AlertCircle className="h-5 w-5 mr-2" />
              {error instanceof Error ? error.message : 'Failed to load logs'}
            </div>
          ) : isLoading && !data ? (
            <div className="flex items-center justify-center h-full">
              <Loader2 className="h-6 w-6 animate-spin text-gray-400" />
            </div>
          ) : (
            <pre
              ref={logsContainerRef}
              className="h-full overflow-auto p-4 bg-gray-900 text-gray-100 font-mono text-xs leading-relaxed"
              style={{ maxHeight: 'calc(90vh - 180px)' }}
            >
              {data?.logs || 'No logs available'}
            </pre>
          )}
        </div>

        {/* Footer */}
        {data && (
          <div className="px-6 py-2 bg-gray-50 border-t text-xs text-gray-500">
            Last updated: {new Date(data.timestamp).toLocaleString()}
          </div>
        )}
      </div>
    </div>
  )
}
