"use client"

import React, { useState, useEffect, useRef, useCallback } from "react"
import { motion, AnimatePresence } from "framer-motion"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../ui/card"
import { Button } from "../ui/button"
import { MoonUIBadgePro as Badge } from "../ui/badge"
import { Progress } from "../ui/progress"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs"
import { cn } from "../../lib/utils"
import { 
  Activity, 
  Zap, 
  Clock, 
  Eye, 
  EyeOff, 
  Download, 
  RefreshCw,
  AlertTriangle,
  CheckCircle,
  TrendingUp,
  TrendingDown,
  Lock,
  Sparkles,
  Cpu,
  MemoryStick,
  Network,
  HardDrive
} from "lucide-react"
import { useSubscription } from "../../hooks/use-subscription"

interface PerformanceMetric {
  name: string
  value: number
  unit: string
  threshold?: {
    good: number
    needs_improvement: number
  }
  description?: string
}

interface PerformanceEntry {
  timestamp: number
  metrics: PerformanceMetric[]
  url: string
  userAgent: string
}

interface PerformanceDebuggerProps {
  autoCapture?: boolean
  captureInterval?: number
  maxEntries?: number
  showRealTime?: boolean
  showWebVitals?: boolean
  showResourceTiming?: boolean
  showNavigationTiming?: boolean
  onMetricChange?: (metrics: PerformanceMetric[]) => void
  className?: string
}

const PerformanceDebuggerInternal: React.FC<PerformanceDebuggerProps> = ({
  autoCapture = true,
  captureInterval = 5000,
  maxEntries = 50,
  showRealTime = true,
  showWebVitals = true,
  showResourceTiming = true,
  showNavigationTiming = true,
  onMetricChange,
  className
}) => {
  const [entries, setEntries] = useState<PerformanceEntry[]>([])
  const [currentMetrics, setCurrentMetrics] = useState<PerformanceMetric[]>([])
  const [isCapturing, setIsCapturing] = useState(autoCapture)
  const [isVisible, setIsVisible] = useState(true)
  const intervalRef = useRef<NodeJS.Timeout | undefined>(undefined)

  // Core Web Vitals thresholds
  const webVitalsThresholds = {
    FCP: { good: 1800, needs_improvement: 3000 },
    LCP: { good: 2500, needs_improvement: 4000 },
    FID: { good: 100, needs_improvement: 300 },
    CLS: { good: 0.1, needs_improvement: 0.25 },
    INP: { good: 200, needs_improvement: 500 },
    TTFB: { good: 800, needs_improvement: 1800 }
  }

  // Get performance metrics
  const captureMetrics = useCallback(() => {
    const metrics: PerformanceMetric[] = []

    // Navigation Timing
    if (showNavigationTiming && 'performance' in window) {
      const nav = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming
      if (nav) {
        metrics.push(
          {
            name: 'DNS Lookup',
            value: nav.domainLookupEnd - nav.domainLookupStart,
            unit: 'ms',
            description: 'Time to resolve domain name'
          },
          {
            name: 'TCP Connection',
            value: nav.connectEnd - nav.connectStart,
            unit: 'ms',
            description: 'Time to establish TCP connection'
          },
          {
            name: 'Request/Response',
            value: nav.responseEnd - nav.requestStart,
            unit: 'ms',
            description: 'Time to get first byte and complete response'
          },
          {
            name: 'DOM Processing',
            value: nav.domComplete - (nav.domInteractive || nav.fetchStart),
            unit: 'ms',
            description: 'Time to process DOM'
          },
          {
            name: 'Load Complete',
            value: nav.loadEventEnd - nav.loadEventStart,
            unit: 'ms',
            description: 'Time to fire load event'
          }
        )
      }
    }

    // Web Vitals (simulated - in real app you'd use web-vitals library)
    if (showWebVitals) {
      const paintEntries = performance.getEntriesByType('paint')
      const fcpEntry = paintEntries.find(entry => entry.name === 'first-contentful-paint')
      
      if (fcpEntry) {
        metrics.push({
          name: 'FCP',
          value: fcpEntry.startTime,
          unit: 'ms',
          threshold: webVitalsThresholds.FCP,
          description: 'First Contentful Paint'
        })
      }

      // Simulated LCP (in real app, use PerformanceObserver)
      metrics.push({
        name: 'LCP',
        value: Math.random() * 4000 + 1000,
        unit: 'ms',
        threshold: webVitalsThresholds.LCP,
        description: 'Largest Contentful Paint'
      })

      // Simulated CLS
      metrics.push({
        name: 'CLS',
        value: Math.random() * 0.3,
        unit: '',
        threshold: webVitalsThresholds.CLS,
        description: 'Cumulative Layout Shift'
      })
    }

    // Memory usage (if available)
    if ('memory' in performance) {
      const memory = (performance as any).memory
      metrics.push(
        {
          name: 'JS Heap Used',
          value: memory.usedJSHeapSize / 1024 / 1024,
          unit: 'MB',
          description: 'JavaScript heap memory in use'
        },
        {
          name: 'JS Heap Total',
          value: memory.totalJSHeapSize / 1024 / 1024,
          unit: 'MB',
          description: 'Total JavaScript heap memory'
        },
        {
          name: 'JS Heap Limit',
          value: memory.jsHeapSizeLimit / 1024 / 1024,
          unit: 'MB',
          description: 'JavaScript heap memory limit'
        }
      )
    }

    // Resource timing
    if (showResourceTiming) {
      const resources = performance.getEntriesByType('resource')
      const totalSize = resources.reduce((acc, resource) => {
        return acc + ((resource as any).transferSize || 0)
      }, 0)

      metrics.push({
        name: 'Resources Loaded',
        value: resources.length,
        unit: 'count',
        description: 'Total number of resources loaded'
      })

      if (totalSize > 0) {
        metrics.push({
          name: 'Total Transfer Size',
          value: totalSize / 1024,
          unit: 'KB',
          description: 'Total size of transferred resources'
        })
      }
    }

    // Current performance scores (simulated)
    metrics.push(
      {
        name: 'Performance Score',
        value: Math.random() * 40 + 60,
        unit: '/100',
        threshold: { good: 90, needs_improvement: 50 },
        description: 'Overall performance score'
      },
      {
        name: 'CPU Usage',
        value: Math.random() * 50 + 20,
        unit: '%',
        threshold: { good: 30, needs_improvement: 70 },
        description: 'Current CPU usage'
      }
    )

    return metrics
  }, [showNavigationTiming, showWebVitals, showResourceTiming])

  // Capture performance data
  const capture = useCallback(() => {
    const metrics = captureMetrics()
    const entry: PerformanceEntry = {
      timestamp: Date.now(),
      metrics,
      url: window.location.href,
      userAgent: navigator.userAgent
    }

    setEntries(prev => [entry, ...prev.slice(0, maxEntries - 1)])
    setCurrentMetrics(metrics)
    onMetricChange?.(metrics)
  }, [captureMetrics, maxEntries, onMetricChange])

  // Auto capture
  useEffect(() => {
    if (isCapturing && showRealTime) {
      capture() // Initial capture
      intervalRef.current = setInterval(capture, captureInterval)
    } else {
      if (intervalRef.current) {
        clearInterval(intervalRef.current)
      }
    }

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current)
      }
    }
  }, [isCapturing, showRealTime, capture, captureInterval])

  // Initial capture on mount
  useEffect(() => {
    capture()
  }, [])

  const getMetricStatus = (metric: PerformanceMetric): 'good' | 'needs_improvement' | 'poor' => {
    if (!metric.threshold) return 'good'
    
    if (metric.value <= metric.threshold.good) return 'good'
    if (metric.value <= metric.threshold.needs_improvement) return 'needs_improvement'
    return 'poor'
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'good': return 'text-green-500'
      case 'needs_improvement': return 'text-yellow-500'
      case 'poor': return 'text-red-500'
      default: return 'text-muted-foreground'
    }
  }

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'good': return <CheckCircle className="h-4 w-4 text-green-500" />
      case 'needs_improvement': return <AlertTriangle className="h-4 w-4 text-yellow-500" />
      case 'poor': return <AlertTriangle className="h-4 w-4 text-red-500" />
      default: return <Activity className="h-4 w-4 text-muted-foreground" />
    }
  }

  const exportData = () => {
    const data = {
      timestamp: new Date().toISOString(),
      entries,
      currentMetrics
    }
    
    const blob = new Blob([JSON.stringify(data, null, 2)], { 
      type: 'application/json' 
    })
    
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `performance-debug-${Date.now()}.json`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
  }

  const clearData = () => {
    setEntries([])
    setCurrentMetrics([])
  }

  const formatValue = (value: number, unit: string) => {
    const formatted = unit === 'ms' || unit === 'MB' || unit === 'KB' 
      ? value.toFixed(1) 
      : unit === '%' || unit === '/100'
      ? Math.round(value)
      : value.toString()
    
    return `${formatted}${unit}`
  }

  if (!isVisible) {
    return (
      <Button
        variant="outline"
        size="sm"
        onClick={() => setIsVisible(true)}
        className="fixed bottom-4 right-4 z-50"
      >
        <Activity className="h-4 w-4 mr-2" />
        Performance
      </Button>
    )
  }

  return (
    <Card className={cn("w-full max-w-4xl", className)}>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle className="flex items-center gap-2">
              <Zap className="h-5 w-5" />
              Performance Debugger
            </CardTitle>
            <CardDescription>
              Real-time performance monitoring and web vitals tracking
            </CardDescription>
          </div>
          
          <div className="flex items-center gap-2">
            <Badge variant={isCapturing ? "secondary" : "secondary"} className="gap-1">
              {isCapturing ? <Activity className="h-3 w-3 animate-pulse" /> : <Clock className="h-3 w-3" />}
              {isCapturing ? "Live" : "Paused"}
            </Badge>
            
            <Button
              variant="outline"
              size="sm"
              onClick={() => setIsCapturing(!isCapturing)}
            >
              {isCapturing ? "Pause" : "Start"}
            </Button>
            
            <Button
              variant="outline"
              size="sm"
              onClick={capture}
            >
              <RefreshCw className="h-4 w-4" />
            </Button>
            
            <Button
              variant="outline"
              size="sm"
              onClick={exportData}
            >
              <Download className="h-4 w-4" />
            </Button>
            
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setIsVisible(false)}
            >
              <EyeOff className="h-4 w-4" />
            </Button>
          </div>
        </div>
      </CardHeader>

      <CardContent>
        <Tabs defaultValue="current" className="w-full">
          <TabsList className="grid w-full grid-cols-3">
            <TabsTrigger value="current">Current Metrics</TabsTrigger>
            <TabsTrigger value="history">History</TabsTrigger>
            <TabsTrigger value="vitals">Web Vitals</TabsTrigger>
          </TabsList>

          <TabsContent value="current" className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              <AnimatePresence>
                {currentMetrics.map((metric, index) => {
                  const status = getMetricStatus(metric)
                  return (
                    <motion.div
                      key={metric.name}
                      initial={{ opacity: 0, y: 20 }}
                      animate={{ opacity: 1, y: 0 }}
                      exit={{ opacity: 0, y: -20 }}
                      transition={{ delay: index * 0.05 }}
                    >
                      <Card>
                        <CardContent className="p-4">
                          <div className="flex items-center justify-between mb-2">
                            <div className="flex items-center gap-2">
                              {getStatusIcon(status)}
                              <span className="font-medium text-sm">{metric.name}</span>
                            </div>
                            <span className={cn("font-bold", getStatusColor(status))}>
                              {formatValue(metric.value, metric.unit)}
                            </span>
                          </div>
                          
                          {metric.threshold && (
                            <div className="space-y-1">
                              <Progress 
                                value={Math.min((metric.value / (metric.threshold.needs_improvement * 2)) * 100, 100)}
                                className="h-2"
                              />
                              <div className="text-xs text-muted-foreground">
                                Good: &lt;{metric.threshold.good}{metric.unit} | 
                                Needs improvement: &lt;{metric.threshold.needs_improvement}{metric.unit}
                              </div>
                            </div>
                          )}
                          
                          {metric.description && (
                            <p className="text-xs text-muted-foreground mt-2">
                              {metric.description}
                            </p>
                          )}
                        </CardContent>
                      </Card>
                    </motion.div>
                  )
                })}
              </AnimatePresence>
            </div>
          </TabsContent>

          <TabsContent value="history" className="space-y-4">
            <div className="flex items-center justify-between">
              <div className="text-sm text-muted-foreground">
                {entries.length} entries captured
              </div>
              <Button variant="outline" size="sm" onClick={clearData}>
                Clear History
              </Button>
            </div>
            
            <div className="space-y-2 max-h-96 overflow-y-auto">
              {entries.map((entry, index) => (
                <Card key={entry.timestamp}>
                  <CardContent className="p-4">
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-sm font-medium">
                        {new Date(entry.timestamp).toLocaleTimeString()}
                      </span>
                      <Badge variant="outline" className="text-xs">
                        {entry.metrics.length} metrics
                      </Badge>
                    </div>
                    
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-2 text-xs">
                      {entry.metrics.slice(0, 4).map((metric) => (
                        <div key={metric.name} className="flex justify-between">
                          <span className="text-muted-foreground">{metric.name}:</span>
                          <span className={getStatusColor(getMetricStatus(metric))}>
                            {formatValue(metric.value, metric.unit)}
                          </span>
                        </div>
                      ))}
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          </TabsContent>

          <TabsContent value="vitals" className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {currentMetrics
                .filter(metric => ['FCP', 'LCP', 'CLS', 'FID', 'INP', 'TTFB'].includes(metric.name))
                .map((metric) => {
                  const status = getMetricStatus(metric)
                  return (
                    <Card key={metric.name}>
                      <CardContent className="p-6">
                        <div className="flex items-center justify-between mb-4">
                          <div>
                            <h3 className="font-semibold">{metric.name}</h3>
                            <p className="text-sm text-muted-foreground">
                              {metric.description}
                            </p>
                          </div>
                          {getStatusIcon(status)}
                        </div>
                        
                        <div className="text-2xl font-bold mb-2 text-center">
                          <span className={getStatusColor(status)}>
                            {formatValue(metric.value, metric.unit)}
                          </span>
                        </div>
                        
                        {metric.threshold && (
                          <div className="space-y-2">
                            <Progress 
                              value={Math.min((metric.value / (metric.threshold.needs_improvement * 2)) * 100, 100)}
                              className="h-3"
                            />
                            <div className="flex justify-between text-xs text-muted-foreground">
                              <span>Good: &lt;{metric.threshold.good}{metric.unit}</span>
                              <span>Poor: &gt;{metric.threshold.needs_improvement}{metric.unit}</span>
                            </div>
                          </div>
                        )}
                      </CardContent>
                    </Card>
                  )
                })}
            </div>
          </TabsContent>
        </Tabs>
      </CardContent>
    </Card>
  )
}

export const PerformanceDebugger: React.FC<PerformanceDebuggerProps> = ({ className, ...props }) => {
  // Check if we're in docs mode or have pro access
  const { hasProAccess, isLoading } = useSubscription()
  
  // In docs mode, always show the component
  
  // If not in docs mode and no pro access, show upgrade prompt
  if (!isLoading && !hasProAccess) {
    return (
      <Card className={cn("w-fit", className)}>
        <CardContent className="py-6 text-center">
          <div className="space-y-4">
            <div className="rounded-full bg-purple-100 dark:bg-purple-900/30 p-3 w-fit mx-auto">
              <Lock className="h-6 w-6 text-purple-600 dark:text-purple-400" />
            </div>
            <div>
              <h3 className="font-semibold text-sm mb-2">Pro Feature</h3>
              <p className="text-muted-foreground text-xs mb-4">
                Performance Debugger is available exclusively to MoonUI Pro subscribers.
              </p>
              <a href="/pricing">
                <Button size="sm">
                  <Sparkles className="mr-2 h-4 w-4" />
                  Upgrade to Pro
                </Button>
              </a>
            </div>
          </div>
        </CardContent>
      </Card>
    )
  }

  return <PerformanceDebuggerInternal className={className} {...props} />
}

export type { PerformanceMetric, PerformanceEntry, PerformanceDebuggerProps }