"use client"

import React from "react"
import { useTranslations, useLocale } from "next-intl"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Badge } from "@/components/ui/badge"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Button } from "@/components/ui/button"
import { Copy, Check, Info, FileCode, Terminal, Database, ExternalLink } from "lucide-react"
import { toast } from "sonner"
import { getDateLocale } from "@/lib/date-utils"
import type { Vulnerability, VulnerabilitySeverity } from "@/types/vulnerability.types"

interface SeverityConfigItem {
  variant: "default" | "secondary" | "destructive" | "outline"
  color: string
  className: string
}

const severityConfig: Record<VulnerabilitySeverity, SeverityConfigItem> = {
  critical: { variant: "outline", color: "bg-[#da3633]", className: "bg-[#da3633]/10 text-[#da3633] border-[#da3633]/20 dark:text-[#f85149]" },
  high: { variant: "outline", color: "bg-[#d29922]", className: "bg-[#d29922]/10 text-[#d29922] border-[#d29922]/20" },
  medium: { variant: "outline", color: "bg-[#d4a72c]", className: "bg-[#d4a72c]/10 text-[#d4a72c] border-[#d4a72c]/20" },
  low: { variant: "outline", color: "bg-[#238636]", className: "bg-[#238636]/10 text-[#238636] border-[#238636]/20 dark:text-[#3fb950]" },
  info: { variant: "outline", color: "bg-[#848d97]", className: "bg-[#848d97]/10 text-[#848d97] border-[#848d97]/20" },
}

interface VulnerabilityDetailDialogProps {
  vulnerability: Vulnerability | null
  open: boolean
  onOpenChange: (open: boolean) => void
}

/**
 * Vulnerability detail dialog component - Tab-based layout
 */
export function VulnerabilityDetailDialog({
  vulnerability,
  open,
  onOpenChange,
}: VulnerabilityDetailDialogProps) {
  const [copiedField, setCopiedField] = React.useState<string | null>(null)
  const dialogRef = React.useRef<HTMLDivElement>(null)
  const tToast = useTranslations("toast")
  const tVuln = useTranslations("vulnerabilities.detail")
  const tSeverity = useTranslations("vulnerabilities.severity")
  const locale = useLocale()

  // HTTP-compatible copy implementation (solves Dialog focus trap issue)
  const copyToClipboard = React.useCallback(async (text: string): Promise<boolean> => {
    const value = text ?? ""
    // 1) Try Clipboard API first (unconditionally, some browsers allow it on HTTP)
    if (navigator.clipboard?.writeText) {
      try {
        await navigator.clipboard.writeText(value)
        return true
      } catch {
        // Continue to fallback
      }
    }

    // 2) HTTP-compatible textarea fallback
    // Key: Add textarea inside Dialog to avoid focus trap blocking focus
    try {
      const container = dialogRef.current || document.body
      const textArea = document.createElement("textarea")
      textArea.value = value
      textArea.style.position = "fixed"
      textArea.style.left = "-9999px"
      textArea.style.top = "-9999px"
      textArea.style.opacity = "0"
      container.appendChild(textArea)
      textArea.focus()
      textArea.select()
      textArea.setSelectionRange(0, textArea.value.length)
      const success = document.execCommand("copy")
      container.removeChild(textArea)
      return success
    } catch {
      return false
    }
  }, [])

  // Handle copy (HTTP-compatible) - must be declared before conditional return
  const handleCopy = React.useCallback(async (text: string, field: string) => {
    const success = await copyToClipboard(text)
    if (success) {
      setCopiedField(field)
      setTimeout(() => setCopiedField(null), 2000)
      toast.success(tToast("copied"))
    } else {
      toast.error(tToast("copyFailed"))
    }
  }, [copyToClipboard, tToast])

  if (!vulnerability) return null

  const raw = vulnerability.rawOutput || {}

  const severityConf = severityConfig[vulnerability.severity] || severityConfig.info

  const formatDate = (dateString: string): string => {
    return new Date(dateString).toLocaleString(getDateLocale(locale), {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
      hour12: false,
    })
  }

  // Extract info from rawOutput
  const curlCommand = raw["curl-command"] as string | undefined
  const request = raw.request as string | undefined
  const response = raw.response as string | undefined
  const cweId = raw.cwe || raw.info?.classification?.["cwe-id"]?.join(", ")
  const cveId = raw.info?.classification?.["cve-id"]
  const references = raw.info?.reference as string[] | undefined
  const payload = raw.payload as string | undefined
  const param = raw.param as string | undefined
  const evidence = raw.evidence as string | undefined
  const method = raw.method as string | undefined
  const infoDesc = raw.info?.description as string | undefined

  // Determine source
  const isNuclei = vulnerability.source === "nuclei"
  const isDalfox = vulnerability.source === "dalfox"

  // Code block component (hover to show copy icon button)
  const CodeBlock = ({ content, field, maxHeight = "max-h-64" }: { content: string; field: string; maxHeight?: string }) => (
    <div className="relative group">
      <Button
        variant="ghost"
        size="icon"
        className={`absolute right-2 top-2 z-10 h-6 w-6 hover:bg-accent transition-opacity ${
          copiedField === field ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
        }`}
        onClick={() => handleCopy(content, field)}
      >
        {copiedField === field ? (
          <Check className="h-3.5 w-3.5 text-green-600 dark:text-green-400" />
        ) : (
          <Copy className="h-3.5 w-3.5 text-muted-foreground" />
        )}
      </Button>
      <div className={`bg-muted p-4 rounded-lg overflow-auto ${maxHeight}`}>
        <pre className="text-xs font-mono whitespace-pre-wrap break-all">{content}</pre>
      </div>
    </div>
  )

  // Content box component (hover to show copy icon button)
  const ContentBox = ({ title, content, field }: { title: string; content: string; field: string }) => (
    <div className="p-4 rounded-lg border bg-card relative group">
      <Button
        variant="ghost"
        size="icon"
        className={`absolute right-3 top-3 z-10 h-6 w-6 hover:bg-accent transition-opacity ${
          copiedField === field ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
        }`}
        onClick={() => handleCopy(content, field)}
      >
        {copiedField === field ? (
          <Check className="h-3.5 w-3.5 text-green-600 dark:text-green-400" />
        ) : (
          <Copy className="h-3.5 w-3.5 text-muted-foreground" />
        )}
      </Button>
      <h3 className="font-semibold text-sm mb-2">{title}</h3>
      <p className="text-sm text-muted-foreground break-all">{content}</p>
    </div>
  )

  // Get translated severity label
  const getSeverityLabel = (severity: VulnerabilitySeverity): string => {
    return tSeverity(severity)
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent ref={dialogRef} className="max-w-4xl max-h-[85vh] p-0 gap-0 overflow-hidden">
        {/* Header - pr-10 to leave space for close button */}
        <div className="px-6 py-4 border-b bg-muted/30 pr-12">
          <DialogHeader>
            <div className="flex items-center gap-3">
              <Badge variant={severityConf.variant} className={`text-sm px-3 py-1 ${severityConf.className}`}>
                {getSeverityLabel(vulnerability.severity)}
              </Badge>
              <DialogTitle className="flex-1 text-lg font-semibold truncate">
                {vulnerability.vulnType}
              </DialogTitle>
              <Badge variant="outline" className="text-xs shrink-0">
                {vulnerability.source.toUpperCase()}
              </Badge>
            </div>
            {vulnerability.description && (
              <p className="text-sm text-muted-foreground mt-2">{vulnerability.description}</p>
            )}
          </DialogHeader>
        </div>

        {/* Tab content */}
        <Tabs defaultValue="overview" className="flex-1 flex flex-col">
          <div className="px-6 pt-2 border-b">
            <TabsList className="h-10">
              <TabsTrigger value="overview" className="gap-2">
                <Info className="h-4 w-4" />
                {tVuln("tabs.overview")}
              </TabsTrigger>
              <TabsTrigger value="evidence" className="gap-2">
                <FileCode className="h-4 w-4" />
                {isNuclei ? tVuln("tabs.requestResponse") : tVuln("tabs.evidence")}
              </TabsTrigger>
              {curlCommand && (
                <TabsTrigger value="reproduce" className="gap-2">
                  <Terminal className="h-4 w-4" />
                  {tVuln("tabs.reproduce")}
                </TabsTrigger>
              )}
              <TabsTrigger value="raw" className="gap-2">
                <Database className="h-4 w-4" />
                {tVuln("tabs.rawData")}
              </TabsTrigger>
            </TabsList>
          </div>

          <ScrollArea className="flex-1 px-6 py-4">
            {/* Overview Tab */}
            <TabsContent value="overview" className="mt-0 space-y-6">
              {/* Basic info card */}
              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-4 p-4 rounded-lg border bg-card">
                  <h3 className="font-semibold text-sm flex items-center gap-2">
                    <Info className="h-4 w-4" />
                    {tVuln("basicInfo")}
                  </h3>
                  <div className="space-y-3 text-sm">
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">ID</span>
                      <span className="font-mono">{vulnerability.id}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">{tVuln("createdAt")}</span>
                      <span>{formatDate(vulnerability.createdAt)}</span>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">{tVuln("severity")}</span>
                      <Badge variant={severityConf.variant} className={severityConf.className}>{getSeverityLabel(vulnerability.severity)}</Badge>
                    </div>
                    <div className="flex justify-between">
                      <span className="text-muted-foreground">{tVuln("source")}</span>
                      <Badge variant="outline">{vulnerability.source.toUpperCase()}</Badge>
                    </div>
                    {method && (
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">{tVuln("httpMethod")}</span>
                        <Badge variant="outline">{method}</Badge>
                      </div>
                    )}
                    {param && (
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">{tVuln("param")}</span>
                        <code className="text-xs bg-muted px-2 py-1 rounded">{param}</code>
                      </div>
                    )}
                  </div>
                </div>

                <div className="space-y-4 p-4 rounded-lg border bg-card">
                  <h3 className="font-semibold text-sm">{tVuln("classification")}</h3>
                  <div className="space-y-3 text-sm">
                    {cweId && (
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">CWE</span>
                        <code className="text-xs bg-muted px-2 py-1 rounded">{cweId}</code>
                      </div>
                    )}
                    {cveId && (
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">CVE</span>
                        <code className="text-xs bg-muted px-2 py-1 rounded">{cveId}</code>
                      </div>
                    )}
                    {vulnerability.cvssScore && (
                      <div className="flex justify-between">
                        <span className="text-muted-foreground">CVSS</span>
                        <Badge variant="destructive">{vulnerability.cvssScore}</Badge>
                      </div>
                    )}
                    {!cweId && !cveId && !vulnerability.cvssScore && (
                      <p className="text-muted-foreground text-xs">{tVuln("noClassification")}</p>
                    )}
                  </div>
                </div>
              </div>

              {/* URL */}
              <ContentBox title={tVuln("vulnUrl")} content={vulnerability.url} field="url" />

              {/* Detailed description */}
              {infoDesc && (
                <div className="p-4 rounded-lg border bg-card">
                  <h3 className="font-semibold text-sm mb-2">{tVuln("detailedDesc")}</h3>
                  <p className="text-sm text-muted-foreground">{infoDesc}</p>
                </div>
              )}

              {/* References */}
              {references && references.length > 0 && (
                <div className="p-4 rounded-lg border bg-card">
                  <h3 className="font-semibold text-sm mb-3">{tVuln("references")}</h3>
                  <ul className="space-y-2">
                    {references.map((ref: string, index: number) => (
                      <li key={index}>
                        <a 
                          href={ref} 
                          target="_blank" 
                          rel="noopener noreferrer"
                          className="text-sm text-blue-600 hover:underline break-all flex items-center gap-1"
                        >
                          {ref}
                          <ExternalLink className="h-3 w-3 flex-shrink-0" />
                        </a>
                      </li>
                    ))}
                  </ul>
                </div>
              )}
            </TabsContent>

            {/* Evidence/Request-Response Tab */}
            <TabsContent value="evidence" className="mt-0 space-y-4">
              {isDalfox && (
                <>
                  {payload && (
                    <div>
                      <h3 className="font-semibold text-sm mb-2">{tVuln("evidence.payload")}</h3>
                      <CodeBlock content={payload} field="payload" />
                    </div>
                  )}
                  {evidence && (
                    <div>
                      <h3 className="font-semibold text-sm mb-2">{tVuln("evidence.evidence")}</h3>
                      <CodeBlock content={evidence} field="evidence" />
                    </div>
                  )}
                </>
              )}

              {isNuclei && (
                <>
                  {request && (
                    <div>
                      <h3 className="font-semibold text-sm mb-2">{tVuln("evidence.httpRequest")}</h3>
                      <CodeBlock content={request} field="request" maxHeight="max-h-80" />
                    </div>
                  )}
                  {response && (
                    <div>
                      <h3 className="font-semibold text-sm mb-2">{tVuln("evidence.httpResponse")}</h3>
                      <CodeBlock content={response} field="response" maxHeight="max-h-80" />
                    </div>
                  )}
                </>
              )}

              {!payload && !evidence && !request && !response && (
                <p className="text-muted-foreground text-sm">{tVuln("noEvidence")}</p>
              )}
            </TabsContent>

            {/* Reproduce Tab */}
            {curlCommand && (
              <TabsContent value="reproduce" className="mt-0 space-y-4">
                <div>
                  <h3 className="font-semibold text-sm mb-2">{tVuln("curlCommand")}</h3>
                  <p className="text-xs text-muted-foreground mb-3">
                    {tVuln("curlHint")}
                  </p>
                  <CodeBlock content={curlCommand} field="curl" maxHeight="max-h-40" />
                </div>
              </TabsContent>
            )}

            {/* Raw data Tab */}
            <TabsContent value="raw" className="mt-0">
              <div>
                <h3 className="font-semibold text-sm mb-2">{tVuln("rawOutput")}</h3>
                <p className="text-xs text-muted-foreground mb-3">
                  {tVuln("rawOutputHint")}
                </p>
                <CodeBlock 
                  content={JSON.stringify(raw, null, 2)} 
                  field="raw" 
                  maxHeight="max-h-[50vh]" 
                />
              </div>
            </TabsContent>
          </ScrollArea>
        </Tabs>
      </DialogContent>
    </Dialog>
  )
}
