import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { NetworkLog } from '@/types/monitor'
import { Globe } from 'lucide-react'

interface NetworkLogDetailDialogProps {
  log: NetworkLog | null
  isOpen: boolean
  onClose: () => void
  isLoading?: boolean
}

export function NetworkLogDetailDialog({
  log,
  isOpen,
  onClose,
  isLoading = false
}: NetworkLogDetailDialogProps) {
  const getMethodBadge = (method: string) => {
    const colors: Record<string, string> = {
      GET: 'bg-blue-100 text-blue-700',
      POST: 'bg-green-100 text-green-700',
      PUT: 'bg-yellow-100 text-yellow-700',
      DELETE: 'bg-red-100 text-red-700',
      PATCH: 'bg-purple-100 text-purple-700',
    }
    return colors[method] || 'bg-gray-100 text-gray-700'
  }

  const getStatusBadge = (status: number) => {
    if (status >= 200 && status < 300) {
      return 'bg-green-100 text-green-700'
    } else if (status >= 400 && status < 500) {
      return 'bg-yellow-100 text-yellow-700'
    } else if (status >= 500) {
      return 'bg-red-100 text-red-700'
    }
    return 'bg-gray-100 text-gray-700'
  }

  const formatBytes = (bytes: number) => {
    if (bytes < 1024) return `${bytes} B`
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`
    return `${(bytes / (1024 * 1024)).toFixed(2)} MB`
  }

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-3xl max-h-[80vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>
            <div className="flex items-center gap-2">
              <Globe className="w-5 h-5 text-green-600" />
              网络请求详情
            </div>
          </DialogTitle>
        </DialogHeader>

        {isLoading ? (
          <div className="space-y-4">
            {Array.from({ length: 8 }).map((_, index) => (
              <div key={index} className="animate-pulse">
                <div className="bg-gray-200 h-4 w-24 rounded mb-2"></div>
                <div className="bg-gray-200 h-6 w-40 rounded"></div>
              </div>
            ))}
          </div>
        ) : log ? (
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <p className="text-sm text-muted-foreground">请求时间</p>
                <p className="mt-1">{new Date(log.timestamp).toLocaleString('zh-CN')}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground">请求方法</p>
                <p className="mt-1">
                  <Badge className={getMethodBadge(log.method)}>
                    {log.method}
                  </Badge>
                </p>
              </div>
              <div className="col-span-2">
                <p className="text-sm text-muted-foreground">请求URL</p>
                <p className="mt-1">
                  <code className="text-xs bg-gray-100 px-2 py-1 rounded block break-all">
                    {log.url}
                  </code>
                </p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground">客户端IP</p>
                <p className="mt-1">
                  <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                    {log.clientIp}
                  </code>
                </p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground">用户</p>
                <p className="mt-1">{log.username || '未登录'}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground">响应状态</p>
                <p className="mt-1">
                  <Badge className={getStatusBadge(log.responseStatus)}>
                    {log.responseStatus}
                  </Badge>
                </p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground">响应时间</p>
                <p className="mt-1">{log.responseTime}ms</p>
              </div>
              {log.responseSize && (
                <div>
                  <p className="text-sm text-muted-foreground">响应大小</p>
                  <p className="mt-1">{formatBytes(log.responseSize)}</p>
                </div>
              )}
            </div>

            {log.requestParams && (
              <div>
                <p className="text-sm text-muted-foreground">请求参数</p>
                <pre className="mt-1 p-3 bg-gray-50 rounded text-xs overflow-x-auto">
                  {log.requestParams}
                </pre>
              </div>
            )}

            {log.requestHeaders && (
              <div>
                <p className="text-sm text-muted-foreground">请求头</p>
                <pre className="mt-1 p-3 bg-gray-50 rounded text-xs overflow-x-auto">
                  {(() => {
                    try {
                      return JSON.stringify(JSON.parse(log.requestHeaders), null, 2)
                    } catch {
                      return log.requestHeaders
                    }
                  })()}
                </pre>
              </div>
            )}

            {log.requestBody && (
              <div>
                <p className="text-sm text-muted-foreground">请求体</p>
                <pre className="mt-1 p-3 bg-gray-50 rounded text-xs overflow-x-auto">
                  {log.requestBody}
                </pre>
              </div>
            )}

            {log.responseBody && (
              <div>
                <p className="text-sm text-muted-foreground">响应体</p>
                <pre className="mt-1 p-3 bg-gray-50 rounded text-xs overflow-x-auto max-h-40 overflow-y-auto">
                  {(() => {
                    try {
                      return JSON.stringify(JSON.parse(log.responseBody), null, 2)
                    } catch {
                      return log.responseBody
                    }
                  })()}
                </pre>
              </div>
            )}

            {log.userAgent && (
              <div>
                <p className="text-sm text-muted-foreground">User Agent</p>
                <p className="mt-1 text-xs text-muted-foreground break-all">
                  {log.userAgent}
                </p>
              </div>
            )}
          </div>
        ) : null}

        <DialogFooter>
          <Button variant="outline" onClick={onClose}>
            关闭
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}