'use client'

import { useState, useMemo, useCallback } from 'react'
import { Copy, Check, Clock, Database, WarningCircle, Lightning, Bug, Lightbulb } from '@phosphor-icons/react'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
import { CodeViewer, SupportedLanguage } from '../code-editor'
import type { ResponseMeta } from './types'

interface ResponseBodyCardProps {
  meta: ResponseMeta
  body: string
  headers: Record<string, string>
  contentType: string | null
  isError?: boolean
  errorMessage?: string
  onDebug?: () => void
  onExplain?: () => void
}

// Detect language from content type
function detectLanguage(contentType: string | null, body?: string): SupportedLanguage {
  if (!contentType) return 'plaintext'
  
  if (contentType.includes('json')) return 'json'
  if (contentType.includes('xml')) return 'xml'
  if (contentType.includes('html')) return 'html'
  if (contentType.includes('javascript')) return 'javascript'
  if (contentType.includes('typescript')) return 'typescript'
  if (contentType.includes('event-stream')) return 'json'
  if (body && body.trim().startsWith('{')) return 'json'
  
  return 'plaintext'
}

function formatSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`
  return `${(bytes / (1024 * 1024)).toFixed(2)} MB`
}

// Format response body - handles both SSE and regular JSON
function formatBody(body: string, contentType: string | null, isSSE: boolean): string {
  if (!body) return ''
  
  // Check if this is SSE format
  if (isSSE || body.includes('data: ')) {
    const lines = body.split(/\r?\n/).filter(line => line.trim())
    const events: string[] = []
    
    for (const line of lines) {
      if (line.startsWith('data: ')) {
        const data = line.slice(6)
        try {
          const parsed = JSON.parse(data)
          events.push(JSON.stringify(parsed, null, 2))
        } catch {
          events.push(data)
        }
      } else {
        events.push(line)
      }
    }
    
    return events.join('\n')
  }
  
  // Regular JSON - try to parse and format
  if (contentType?.includes('json')) {
    try {
      const parsed = JSON.parse(body)
      return JSON.stringify(parsed, null, 2)
    } catch {
      return body
    }
  }
  
  return body
}

export function ResponseBodyCard({ 
  meta, 
  body, 
  headers, 
  contentType, 
  isError = false,
  errorMessage,
  onDebug,
  onExplain
}: ResponseBodyCardProps) {
  const [copied, setCopied] = useState(false)
  
  const isSSE = contentType?.includes('event-stream')
  const detectedLanguage = useMemo(() => detectLanguage(contentType, body), [contentType, body])
  const formattedBody = useMemo(() => formatBody(body, contentType, !!isSSE), [body, contentType, isSSE])
  const headersCount = Object.keys(headers).length
  
  const copyToClipboard = useCallback((text: string) => {
    navigator.clipboard.writeText(text)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }, [])
  
  const statusVariant = isError ? 'destructive' : 'default'

  return (
    <TooltipProvider>
      <div className="flex flex-col h-full">
        {/* Response Meta */}
        <div className="sticky top-0 z-10 flex items-center justify-between bg-muted/50 px-4 py-3 border-b border-border">
          <div className="flex items-center gap-4 text-sm">
            {/* Status */}
            <Badge variant={statusVariant} className="font-semibold">
              {meta.status} {meta.statusText}
            </Badge>

            {/* Time */}
            <span className="flex items-center gap-1.5 text-muted-foreground">
              <Clock className="h-4 w-4" weight="bold" />
              <span>{meta.responseTime}ms</span>
            </span>

            {/* Size */}
            <span className="flex items-center gap-1.5 text-muted-foreground">
              <Database className="h-4 w-4" weight="bold" />
              <span>{formatSize(meta.size)}</span>
            </span>

            {/* Streaming indicator */}
            {meta.isStreaming && (
              <span className="flex items-center gap-1.5 text-amber-600 dark:text-amber-400">
                <Lightning className="h-4 w-4 animate-pulse" weight="fill" />
                <span>SSE</span>
              </span>
            )}
          </div>

          <div className="flex items-center gap-2">
            {errorMessage && (
              <span className="flex items-center gap-1.5 text-red-500 text-sm">
                <WarningCircle className="h-4 w-4" weight="fill" />
                Error
              </span>
            )}
            
            {/* Copy button */}
            {formattedBody && (
              <Tooltip>
                <TooltipTrigger asChild>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-8 w-8"
                    onClick={() => copyToClipboard(formattedBody)}
                  >
                    {copied ? (
                      <Check className="h-4 w-4 text-green-500" weight="bold" />
                    ) : (
                      <Copy className="h-4 w-4" weight="bold" />
                    )}
                  </Button>
                </TooltipTrigger>
                <TooltipContent>{copied ? 'Copied!' : 'Copy response'}</TooltipContent>
              </Tooltip>
            )}
          </div>
        </div>

        {/* Tabs */}
        <Tabs defaultValue="body" className="flex flex-col flex-1 gap-0">
          <TabsList className="w-full justify-start rounded-none border-b bg-background h-auto p-0">
            <TabsTrigger
              value="body"
              className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary px-4 py-3"
            >
              Body
            </TabsTrigger>
            <TabsTrigger
              value="headers"
              className="rounded-none border-b-2 border-transparent data-[state=active]:border-primary px-4 py-3"
            >
              Headers
              <Badge variant="secondary" className="ml-2 h-5 px-1.5">
                {headersCount}
              </Badge>
            </TabsTrigger>
          </TabsList>

          <TabsContent value="body" className="flex-1 m-0 overflow-hidden relative">
            {formattedBody ? (
              <CodeViewer
                value={formattedBody}
                language={detectedLanguage}
                height="100%"
                minHeight={200}
                theme="dark"
                showLineNumbers={false}
                showBorder={false}
                rounded={false}
              />
            ) : (
              <div className="flex items-center justify-center h-full text-muted-foreground">
                No response body
              </div>
            )}
            
            {/* Action buttons - overlay on code viewer */}
            <div className="absolute top-2.5 right-3 z-20 flex items-center gap-2">
              {/* Explain button - for success responses */}
              {!isError && onExplain && (
                <Tooltip>
                  <TooltipTrigger asChild>
                    <button
                      className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium text-white/70 bg-white/10 hover:bg-white/20 hover:text-white transition-colors rounded-md backdrop-blur-sm"
                      onClick={onExplain}
                    >
                      <Lightbulb className="h-3.5 w-3.5" weight="bold" />
                      <span>Explain</span>
                    </button>
                  </TooltipTrigger>
                  <TooltipContent side="left">Ask AI to explain this response</TooltipContent>
                </Tooltip>
              )}
              
              {/* Debug button - for error responses */}
              {isError && onDebug && (
                <Tooltip>
                  <TooltipTrigger asChild>
                    <button
                      className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium text-white/70 bg-white/10 hover:bg-white/20 hover:text-white transition-colors rounded-md backdrop-blur-sm"
                      onClick={onDebug}
                    >
                      <Bug className="h-3.5 w-3.5" weight="bold" />
                      <span>Debug</span>
                    </button>
                  </TooltipTrigger>
                  <TooltipContent side="left">Ask AI to help debug this error</TooltipContent>
                </Tooltip>
              )}
            </div>
          </TabsContent>

          <TabsContent value="headers" className="flex-1 m-0 overflow-auto">
            <div className="divide-y divide-border">
              {Object.entries(headers).map(([key, value]) => (
                <div key={key} className="flex items-start gap-4 px-4 py-3">
                  <span className="font-mono text-sm font-semibold text-foreground min-w-[180px]">
                    {key}
                  </span>
                  <span className="font-mono text-sm text-muted-foreground break-all">
                    {value}
                  </span>
                </div>
              ))}
              {headersCount === 0 && (
                <div className="flex items-center justify-center p-8 text-muted-foreground">
                  No response headers
                </div>
              )}
            </div>
          </TabsContent>
        </Tabs>
      </div>
    </TooltipProvider>
  )
}
