"use client"

import React, { useEffect, useState } from "react"
import { useParams, useRouter } from "next/navigation"
import { ArrowLeft, Zap, Loader2, AlertTriangle } from "lucide-react"
import { getOptimizationEventById } from "../action"
import { getUserIdAndUsername } from "@/app/utils/auth"
import { LineProfilerView } from "@/components/LineProfiler"
import { useViewMode } from "@/app/app/ViewModeContext"
import { toast } from "sonner"

// Error boundary to gracefully handle parsing failures or rendering issues
interface ErrorBoundaryState {
  hasError: boolean
  error?: Error
}

class ProfilerErrorBoundary extends React.Component<
  { children: React.ReactNode; onRetry?: () => void },
  ErrorBoundaryState
> {
  constructor(props: { children: React.ReactNode; onRetry?: () => void }) {
    super(props)
    this.state = { hasError: false }
  }

  static getDerivedStateFromError(error: Error): ErrorBoundaryState {
    return { hasError: true, error }
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error("ProfilerErrorBoundary caught an error:", error, errorInfo)
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="flex-1 flex items-center justify-center p-8">
          <div className="text-center">
            <AlertTriangle className="w-12 h-12 mx-auto mb-4 text-destructive" />
            <h2 className="text-xl font-semibold mb-2">Failed to load profiler data</h2>
            <p className="text-muted-foreground mb-4">
              There was an error parsing or rendering the profiler data.
            </p>
            {this.props.onRetry && (
              <button
                onClick={() => {
                  this.setState({ hasError: false, error: undefined })
                  this.props.onRetry?.()
                }}
                className="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90"
              >
                Try Again
              </button>
            )}
          </div>
        </div>
      )
    }
    return this.props.children
  }
}

interface EventMetadata {
  originalLineProfiler?: string
  optimizedLineProfiler?: string
  prCommentFields?: {
    original_runtime?: string
    best_runtime?: string
  }
}

interface OptimizationEvent {
  id: string
  trace_id: string
  function_name?: string | null
  file_path?: string | null
  speedup_x?: number | null
  speedup_pct?: number | null
  metadata: EventMetadata
}

export default function LineProfilerPage() {
  const params = useParams()
  const router = useRouter()
  const [event, setEvent] = useState<OptimizationEvent | null>(null)
  const [loading, setLoading] = useState(true)
  const { currentOrg } = useViewMode()
  const currentOrgId = currentOrg?.id

  useEffect(() => {
    async function loadEvent() {
      try {
        const userSession = (await getUserIdAndUsername()) ?? { userId: "", username: "" }

        const data = await getOptimizationEventById({
          payload: currentOrgId
            ? { orgId: currentOrgId }
            : { userId: userSession.userId, username: userSession.username },
          trace_id: params.traceId as string,
        })

        if (data) {
          const metadata = data.metadata as EventMetadata
          setEvent({
            id: data.id,
            trace_id: data.trace_id,
            function_name: data.function_name,
            file_path: data.file_path,
            speedup_x: data.speedup_x,
            speedup_pct: data.speedup_pct,
            metadata,
          })
        } else {
          setEvent(null)
        }
      } catch (error) {
        console.error("Failed to load optimization event:", error)
        toast.error("Failed to load profiler data")
      } finally {
        setLoading(false)
      }
    }

    loadEvent()
  }, [params.traceId, currentOrgId])

  const handleBack = () => {
    router.push(`/review-optimizations/${params.traceId}`)
  }

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Loader2 className="h-12 w-12 animate-spin text-primary" />
      </div>
    )
  }

  if (!event) {
    return (
      <div className="min-h-screen flex items-center justify-center p-4">
        <div className="text-center">
          <h2 className="text-2xl font-semibold mb-2">Event not found</h2>
          <p className="text-muted-foreground mb-4">
            The optimization event you&apos;re looking for doesn&apos;t exist.
          </p>
          <button
            onClick={handleBack}
            className="inline-flex items-center gap-2 px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90"
          >
            <ArrowLeft className="h-4 w-4" />
            Go Back
          </button>
        </div>
      </div>
    )
  }

  const metadata = event.metadata || {}
  const hasProfilerData = metadata.originalLineProfiler || metadata.optimizedLineProfiler

  if (!hasProfilerData) {
    return (
      <div className="min-h-screen flex items-center justify-center p-4">
        <div className="text-center">
          <h2 className="text-2xl font-semibold mb-2">No Profiler Data</h2>
          <p className="text-muted-foreground mb-4">
            This optimization doesn&apos;t have line profiler data available.
          </p>
          <button
            onClick={handleBack}
            className="inline-flex items-center gap-2 px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90"
          >
            <ArrowLeft className="h-4 w-4" />
            Go Back
          </button>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-background flex flex-col">
      {/* Header */}
      <div className="px-4 py-3 bg-muted/30 border-b border-border">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-4">
            <button
              onClick={handleBack}
              className="p-2 hover:bg-muted rounded-md transition-colors"
              title="Back to optimization details"
            >
              <ArrowLeft className="h-5 w-5" />
            </button>
            <div className="flex items-center gap-3">
              <Zap className="w-6 h-6 text-primary" />
              <h1 className="text-xl font-semibold">
                Line Profiler Report
                {event.function_name && (
                  <>
                    {" - "}
                    <code className="font-mono text-primary">{event.function_name}()</code>
                  </>
                )}
              </h1>
              {event.speedup_x && (
                <span className="flex items-center gap-2 rounded-md bg-gradient-to-r from-primary to-yellow-500 px-3 py-1 text-xs font-bold text-gray-900">
                  <svg className="h-3.5 w-3.5" fill="currentColor" viewBox="0 0 24 24">
                    <path d="M13 10V3L4 14h7v7l9-11h-7z" />
                  </svg>
                  {event.speedup_x.toFixed(2)}x faster
                </span>
              )}
            </div>
          </div>

          {event.file_path && (
            <span className="text-sm text-muted-foreground font-mono">
              {event.file_path}
            </span>
          )}
        </div>
      </div>

      {/* Line Profiler View */}
      <div className="flex-1 overflow-hidden">
        <ProfilerErrorBoundary>
          <LineProfilerView
            originalProfiler={metadata.originalLineProfiler}
            optimizedProfiler={metadata.optimizedLineProfiler}
            functionName={event.function_name || undefined}
            originalRuntime={metadata.prCommentFields?.original_runtime}
            optimizedRuntime={metadata.prCommentFields?.best_runtime}
          />
        </ProfilerErrorBoundary>
      </div>
    </div>
  )
}
