"use client"

import { useEffect, useState, useCallback, useRef } from "react"
import { useRouter } from "next/navigation"
import Image from "next/image"
import {
  Zap,
  CheckCircle,
  XCircle,
  MessageSquare,
  Loader2,
  GitCommit,
  BarChart3,
} from "lucide-react"
import {
  createPullRequest,
  saveOptimizationChanges,
  setApprovalStatus,
  addComment,
  getCommentsByEvent,
  commitStagingCode,
  getReviewPageInitData,
  type StagingCodeResponse,
} from "./action"
import dynamic from "next/dynamic"

const MonacoDiffEditorGithub = dynamic(
  () => import("@/components/Editor/monaco-diff-editor-github"),
  { ssr: false },
)
import { toast } from "sonner"
import { MarkdownEditor } from "@/components/markdwon/markdown-editor"
import { MarkdownViewer } from "@/components/markdwon/markdown-viewer"
import { BaseBranchDialog } from "@/components/ui/base-branch-dialog"
import { useViewMode } from "@/app/app/ViewModeContext"

// Interfaces
interface Comment {
  id: string
  optimization_event_id: string
  author_user_id: string
  content: string
  created_at: Date
  author?: {
    user_id: string
    email: string
    name?: string
    github_username?: string
  }
}

interface TestResults {
  passed: number
  failed: number
}

interface ReportTable {
  [key: string]: TestResults
}

interface PRCommentFields {
  original_runtime?: string
  best_runtime?: string
  loop_count?: number
  optimization_explanation?: string
  report_table?: ReportTable
}

interface EventMetadata {
  diffContents?: Record<string, DiffContent>
  prCommentFields?: PRCommentFields
  generatedTests?: string
  existingTests?: string
  lastModified?: string
  coverage_message?: string
  staging_storage_type?: "plain_text" | "git_branch"
  staging_branch_name?: string
  originalLineProfiler?: string
  optimizedLineProfiler?: string
}

interface Repository {
  id: string
  name: string
  owner: string
  full_name: string
  installation_id?: number
}

interface OptimizationEvent {
  id: string
  event_type: string
  user_id: string | null
  repository_id: string | null
  trace_id: string
  pr_id: string | null
  pr_url: string | null
  api_key_id: number | null
  metadata: EventMetadata
  is_optimization_found: boolean | null
  current_username: string | null
  function_name?: string | null
  file_path?: string | null
  speedup_x?: number | null
  speedup_pct?: number | null
  created_at: Date
  baseBranch?: string | null
  repository?: Repository | null
  status?: "approved" | "rejected" | null
  review_quality?: string | null
  review_explanation?: string | null
  staging_storage_type?: "plain_text" | "git_branch" | null
}

interface RawOptimizationEvent {
  id: string
  event_type: string
  user_id: string | null
  repository_id: string | null
  trace_id: string
  pr_id: string | null
  pr_url: string | null
  api_key_id: number | null
  metadata: unknown
  is_optimization_found: boolean | null
  current_username: string | null
  function_name?: string | null
  file_path?: string | null
  speedup_x?: number | null
  speedup_pct?: number | null
  created_at: Date
  baseBranch?: string | null
  repository?: Repository | null
  status?: "approved" | "rejected" | null
  review_quality?: string | null
  review_explanation?: string | null
  staging_storage_type?: "plain_text" | "git_branch" | null
}

interface DiffContent {
  oldContent: string
  newContent: string
}

interface SaveOptimizationResult {
  success: boolean
  error?: string
  event?: RawOptimizationEvent
}

export interface ReviewClientProps {
  traceId: string
  initialEvent: RawOptimizationEvent | null
  initialComments: Comment[]
  initialStagingCode: StagingCodeResponse | null
}

function transformEvent(
  rawData: RawOptimizationEvent,
  stagingCode: StagingCodeResponse | null,
): OptimizationEvent {
  let metadata = rawData.metadata as EventMetadata

  // Merge staging code into metadata if available
  if (stagingCode && rawData.staging_storage_type === "git_branch") {
    const isDiffEmpty =
      !stagingCode.diffContents || Object.keys(stagingCode.diffContents).length === 0
    if (!isDiffEmpty) {
      metadata = {
        ...metadata,
        diffContents: stagingCode.diffContents,
        staging_storage_type: "git_branch",
        staging_branch_name: stagingCode.stagingBranchName,
      }
    }
  }

  return {
    ...rawData,
    metadata,
    function_name: rawData.function_name || null,
    file_path: rawData.file_path || null,
    speedup_x: rawData.speedup_x || null,
    speedup_pct: rawData.speedup_pct || null,
    baseBranch: rawData.baseBranch || undefined,
    repository: rawData.repository || null,
    status: rawData.status || null,
    review_quality: rawData.review_quality || null,
    review_explanation: rawData.review_explanation || null,
    staging_storage_type: rawData.staging_storage_type || null,
  }
}

export function OptimizationReviewClient({
  traceId,
  initialEvent,
  initialComments,
  initialStagingCode,
}: ReviewClientProps) {
  const router = useRouter()
  const [event, setEvent] = useState<OptimizationEvent | null>(
    initialEvent ? transformEvent(initialEvent, initialStagingCode) : null,
  )
  const [loading, setLoading] = useState(!initialEvent)
  const [creatingPR, setCreatingPR] = useState(false)
  const [isUpdatingStatus, setIsUpdatingStatus] = useState(false)
  const [isCommitting, setIsCommitting] = useState(false)
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false)
  const saveQueueRef = useRef<Map<string, NodeJS.Timeout>>(new Map())
  const isLoadingRef = useRef(false)
  const pendingChangesRef = useRef<Record<string, string>>({})

  // State for comments
  const [comments, setComments] = useState<Comment[]>(initialComments)
  const [newComment, setNewComment] = useState("")
  const [isSubmittingComment, setIsSubmittingComment] = useState(false)
  const [loadingComments, setLoadingComments] = useState(false)
  const [showCommentsSection, setShowCommentsSection] = useState(false)
  const { currentOrg } = useViewMode()

  // State for base branch dialog
  const [showBaseBranchDialog, setShowBaseBranchDialog] = useState(false)

  const currentOrgId = currentOrg?.id ?? null
  // Track the org ID used for the server-prefetched data
  const initialOrgIdRef = useRef(currentOrgId)

  // Only refetch when the org changes from the initial server-fetched state
  useEffect(() => {
    // Skip if this is the initial render with server data
    if (currentOrgId === initialOrgIdRef.current) {
      return
    }
    initialOrgIdRef.current = currentOrgId
    // Prevent concurrent calls
    if (isLoadingRef.current) {
      return
    }

    async function refetchEvent() {
      isLoadingRef.current = true
      setLoading(true)
      try {
        const data = await getReviewPageInitData(traceId)
        if (data?.event) {
          setComments((data.comments as Comment[]) ?? [])
          setEvent(
            transformEvent(
              data.event as unknown as RawOptimizationEvent,
              (data.stagingCode as StagingCodeResponse | null | undefined) ?? null,
            ),
          )
        } else {
          setEvent(null)
          setComments([])
        }
      } catch (error) {
        console.error("Failed to load optimization event:", error)
        toast.error("Failed to load optimization event")
      } finally {
        setLoading(false)
        isLoadingRef.current = false
      }
    }
    refetchEvent()
  }, [currentOrgId, traceId])

  const loadComments = async (eventId: string) => {
    setLoadingComments(true)
    try {
      const result = await getCommentsByEvent(eventId)
      if (result.success && result.comments) {
        setComments(result.comments as Comment[])
      }
    } catch (error) {
      console.error("Failed to load comments:", error)
    } finally {
      setLoadingComments(false)
    }
  }

  // Cleanup save queue on unmount
  useEffect(() => {
    const saveQueue = saveQueueRef.current
    return () => {
      saveQueue.forEach(timeout => clearTimeout(timeout))
      saveQueue.clear()
    }
  }, [])

  const handleContentChange = (filePath: string, newContent: string) => {
    if (event && event.metadata.diffContents) {
      const updatedEvent = {
        ...event,
        metadata: {
          ...event.metadata,
          diffContents: {
            ...event.metadata.diffContents,
            [filePath]: {
              ...event.metadata.diffContents[filePath],
              newContent: newContent,
            },
          },
        },
      }
      setEvent(updatedEvent)

      // For git_branch storage, track pending changes for manual commit
      if (event.staging_storage_type === "git_branch") {
        pendingChangesRef.current[filePath] = newContent
        setHasUnsavedChanges(true)
      }
    }
  }

  // Handle committing changes to git branch
  const handleCommitChanges = async () => {
    if (!event || !hasUnsavedChanges || Object.keys(pendingChangesRef.current).length === 0) {
      return
    }

    setIsCommitting(true)
    try {
      const result = await commitStagingCode(
        event.trace_id,
        pendingChangesRef.current,
        `Update optimized code for ${event.function_name || "function"}`,
      )

      if (result.success) {
        toast.success("Changes committed successfully!", {
          description: `Commit SHA: ${result.data?.commitSha?.substring(0, 7)}`,
        })
        pendingChangesRef.current = {}
        setHasUnsavedChanges(false)
      } else {
        toast.error(result.error || "Failed to commit changes")
      }
    } catch (error) {
      console.error("Error committing changes:", error)
      toast.error("Failed to commit changes")
    } finally {
      setIsCommitting(false)
    }
  }

  // Handle autosave edits with database persistence (only for plain_text storage)
  const handleEdit = useCallback(
    async (filePath: string, newContent: string) => {
      if (!event) return

      // Skip autosave for git_branch storage - use manual commit instead
      if (event.staging_storage_type === "git_branch") {
        return
      }

      try {
        const existingTimeout = saveQueueRef.current.get(filePath)
        if (existingTimeout) {
          clearTimeout(existingTimeout)
        }

        const timeoutId = setTimeout(async () => {
          try {
            const result = (await saveOptimizationChanges({
              eventId: event.id,
              filePath,
              newContent,
            })) as SaveOptimizationResult

            if (result.success) {
              console.log(`Successfully saved ${filePath} to database`)
              if (result.event) {
                const transformedData: OptimizationEvent = {
                  ...result.event,
                  metadata: result.event.metadata as EventMetadata,
                  function_name: result.event.function_name || null,
                  file_path: result.event.file_path || null,
                  speedup_x: result.event.speedup_x || null,
                  speedup_pct: result.event.speedup_pct || null,
                  created_at: result.event.created_at,
                  status: result.event.status || null,
                  repository: result.event.repository || event.repository || null,
                }
                setEvent(transformedData)
              }
            } else {
              console.error(`Failed to save ${filePath}:`, result.error)
              toast.error(`Failed to save changes: ${result.error}`)
            }
          } catch (error) {
            console.error(`Error saving ${filePath}:`, error)
            toast.error("Failed to save changes")
          } finally {
            saveQueueRef.current.delete(filePath)
          }
        }, 100)

        saveQueueRef.current.set(filePath, timeoutId)
      } catch (error) {
        console.error("Error in handleEdit:", error)
      }
    },
    [event],
  )

  const handleSubmitReview = async (status: "approved" | "rejected") => {
    if (!event) return

    setIsUpdatingStatus(true)

    try {
      const result = await setApprovalStatus(event.id, status)

      if (result.success) {
        setEvent(prev => (prev ? { ...prev, status } : null))
      } else {
        throw new Error(result.error || `Failed to ${status} optimization`)
      }
    } catch {
      toast.error("Failed to submit review")
    } finally {
      setIsUpdatingStatus(false)
    }
  }

  const handleAddComment = async () => {
    if (!event || !newComment.trim()) return

    setIsSubmittingComment(true)
    try {
      const commentResult = await addComment({
        eventId: event.id,
        content: newComment.trim(),
      })

      if (!commentResult.success) {
        throw new Error(commentResult.error || "Failed to add comment")
      }

      // Reload comments and clear input
      await loadComments(event.id)
      setNewComment("")
    } catch {
      toast.error("Failed to add comment")
    } finally {
      setIsSubmittingComment(false)
    }
  }

  const handleOpenBaseBranchDialog = () => {
    setShowBaseBranchDialog(true)
  }

  const handleBaseBranchConfirm = async (branchName: string) => {
    setShowBaseBranchDialog(false)

    // Update the event with the new base branch
    if (event) {
      setEvent(prev => (prev ? { ...prev, baseBranch: branchName } : null))
    }

    // Small delay to ensure state is updated
    setTimeout(() => {
      handleCreatePR(branchName)
    }, 100)
  }

  const handleCreatePR = async (customBaseBranch?: string) => {
    if (!event || !event.trace_id || !event.metadata.diffContents) {
      toast.error("Missing required data to create PR")
      return
    }

    setCreatingPR(true)
    try {
      const speedupX = event.speedup_x ? `${event.speedup_x.toFixed(2)}x` : "N/A"
      const speedupPct = event.speedup_pct ? `${event.speedup_pct.toLocaleString()}%` : "N/A"

      const result = await createPullRequest({
        traceId: event.trace_id,
        diffContents: event.metadata.diffContents,
        prCommentFields: event.metadata.prCommentFields,
        generatedTests: event.metadata.generatedTests,
        existingTests: event.metadata.existingTests,
        functionName: event.function_name || undefined,
        filePath: event.file_path || undefined,
        speedupX: speedupX,
        speedupPct: speedupPct,
        baseBranch: customBaseBranch || event.baseBranch || undefined,
        full_repo_name: event.repository?.full_name,
        coverage_message: event.metadata.coverage_message,
        originalLineProfiler: event.metadata.originalLineProfiler,
        optimizedLineProfiler: event.metadata.optimizedLineProfiler,
      })

      console.log("[handleCreatePR] Result from createPullRequest:", {
        success: result.success,
        data: result.data,
        dataType: typeof result.data,
        error: result.error,
      })

      if (!result.success) {
        console.error("[handleCreatePR] Failed to create PR:", result.error)
        toast.error(result.error || "Failed to create pull request", {
          duration: 5000,
        })
        return
      }

      // Handle pending approval response (status 202)
      if (typeof result.data === "object" && result.data !== null) {
        const dataObj = result.data as { status?: string; message?: string }
        if (dataObj.status === "pending_approval") {
          console.log("[handleCreatePR] Pending approval response:", dataObj)
          toast.info(dataObj.message || "This optimization requires approval", {
            duration: 5000,
          })
          return
        }

        // If it's an object but not pending approval, something is wrong
        console.error("[handleCreatePR] Unexpected object response:", dataObj)
        toast.error("Failed to create pull request: Server returned unexpected response", {
          duration: 5000,
        })
        return
      }

      // Extract PR number - should be a number or string
      let prNumber: string | null = null
      if (typeof result.data === "number") {
        prNumber = String(result.data)
      } else if (typeof result.data === "string") {
        prNumber = result.data
      } else {
        console.error(
          "[handleCreatePR] Invalid data type. Expected number or string, got:",
          typeof result.data,
          result.data,
        )
        toast.error("Failed to create pull request: Invalid response from server", {
          duration: 5000,
        })
        return
      }

      console.log("[handleCreatePR] Successfully extracted PR number:", prNumber)

      let constructedUrl = ""
      if (prNumber && event.repository?.full_name)
        constructedUrl = `https://github.com/${event.repository.full_name}/pull/${prNumber}`

      // Update the event state with the new PR number
      if (prNumber) {
        setEvent(prev => (prev ? { ...prev, pr_url: constructedUrl } : null))
      }

      // Show success toast with custom duration and description
      toast.success("Pull request created successfully!", {
        description: `PR #${prNumber || "new"} has been created. Opening GitHub...`,
        duration: 5000,
        action: {
          label: "Open PR",
          onClick: () => {
            if (constructedUrl) {
              window.open(constructedUrl, "_blank")
            }
          },
        },
      })

      // Delay opening the window to ensure toast is visible
      setTimeout(() => {
        if (constructedUrl) {
          window.open(constructedUrl, "_blank")
        }
      }, 1000)
    } catch (error: unknown) {
      console.error("[handleCreatePR] Exception:", error)
      const errorMessage = error instanceof Error ? error.message : "Failed to create pull request"
      toast.error(errorMessage, {
        duration: 5000,
      })
    } finally {
      setCreatingPR(false)
    }
  }

  const handleViewPR = () => {
    if (!event?.pr_url) return
    window.open(event.pr_url, "_blank")
  }

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

  const formatTimeAgo = (date: Date) => {
    const seconds = Math.floor((new Date().getTime() - new Date(date).getTime()) / 1000)

    if (seconds < 60) return "just now"
    if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`
    if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`
    if (seconds < 2592000) return `${Math.floor(seconds / 86400)}d ago`
    return `${Math.floor(seconds / 2592000)}mo ago`
  }

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
      </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">
            The optimization event you&apos;re looking for doesn&apos;t exist.
          </p>
        </div>
      </div>
    )
  }

  const metadata = event.metadata || {}
  const diffContents = metadata.diffContents || {}
  const prCommentFields = metadata.prCommentFields || {}

  // Check if we have empty diffContents for git_branch storage type (merged PR in privacy mode)
  const isPrivacyModeWithNoDiff =
    event.staging_storage_type === "git_branch" && Object.keys(diffContents).length === 0

  return (
    <div className="min-h-screen bg-background">
      <div className="mx-auto">
        {/* Header */}
        <div className="px-4 py-2 bg-muted/30 border-b border-border">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <Zap className="w-6 h-6 text-primary" />
              <h1 className="text-xl font-semibold">
                {event.function_name ? (
                  <>
                    Code Optimization -{" "}
                    <code className="font-mono text-primary">{event.function_name}()</code>
                  </>
                ) : (
                  "Code Optimization"
                )}
              </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 className="flex items-center gap-2">
              {/* Performance Profile Button - Only show if profiler data exists */}
              {(metadata.originalLineProfiler || metadata.optimizedLineProfiler) && (
                <button
                  onClick={handleViewProfiler}
                  className="flex items-center gap-2 px-3 py-1.5 text-sm font-medium rounded-md
                    bg-purple-100 text-purple-700 hover:bg-purple-200
                    dark:bg-purple-900/30 dark:text-purple-300 dark:hover:bg-purple-900/50
                    transition-all duration-200"
                  title="View line-by-line performance profile"
                >
                  <BarChart3 className="w-4 h-4" />
                  <span>Performance Profile</span>
                </button>
              )}

              {/* Comments Toggle Button with Count */}
              <button
                onClick={() => setShowCommentsSection(!showCommentsSection)}
                className={`
                  relative p-1.5 rounded-md transition-all duration-200 flex items-center gap-1
                  ${showCommentsSection ? "bg-primary/10 text-foreground" : "hover:bg-muted text-foreground"}
                `}
                title={showCommentsSection ? "Hide comments panel" : "Show comments panel"}
              >
                <MessageSquare
                  className={`
                    w-4 h-4 transition-colors
                    ${showCommentsSection ? "text-primary" : "text-muted-foreground"}
                  `}
                />
                {comments.length > 0 && (
                  <span
                    className={`
                      absolute -top-1 -right-1 min-w-[16px] h-4 flex items-center justify-center
                      px-1 text-[10px] font-bold rounded-full transition-colors
                      ${
                        showCommentsSection
                          ? "bg-primary text-primary-foreground"
                          : "bg-muted-foreground text-background"
                      }
                    `}
                  >
                    {comments.length}
                  </span>
                )}
              </button>

              {/* Commit Button - Only for git_branch storage */}
              {event.staging_storage_type === "git_branch" && (
                <button
                  onClick={handleCommitChanges}
                  disabled={isCommitting || !hasUnsavedChanges}
                  className={`
                    flex items-center gap-2 px-3 py-1.5 text-sm font-medium rounded-md
                    transition-all duration-200
                    ${
                      isCommitting
                        ? "bg-muted text-muted-foreground cursor-not-allowed opacity-50"
                        : hasUnsavedChanges
                          ? "bg-blue-600 text-white hover:bg-blue-700"
                          : "bg-muted text-muted-foreground cursor-not-allowed"
                    }
                  `}
                  title={
                    hasUnsavedChanges ? "Commit changes to staging branch" : "No changes to commit"
                  }
                >
                  {isCommitting ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <GitCommit className="w-4 h-4" />
                  )}
                  <span>{hasUnsavedChanges ? "Commit" : "Committed"}</span>
                </button>
              )}

              {/* Approve Button */}
              <button
                onClick={() => handleSubmitReview("approved")}
                disabled={isUpdatingStatus || event.status === "approved"}
                className={`
                  flex items-center gap-2 px-3 py-1.5 text-sm font-medium rounded-md
                  transition-all duration-200
                  ${
                    event.status === "approved"
                      ? "bg-green-600 text-white cursor-default"
                      : isUpdatingStatus
                        ? "bg-muted text-muted-foreground cursor-not-allowed"
                        : "bg-muted hover:bg-green-600 hover:text-white text-foreground"
                  }
                  ${isUpdatingStatus ? "opacity-50" : ""}
                `}
              >
                {isUpdatingStatus ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <CheckCircle className="w-4 h-4" />
                )}
                <span>Approve</span>
              </button>

              {/* Reject Button */}
              <button
                onClick={() => handleSubmitReview("rejected")}
                disabled={isUpdatingStatus || event.status === "rejected"}
                className={`
                  flex items-center gap-2 px-3 py-1.5 text-sm font-medium rounded-md
                  transition-all duration-200
                  ${
                    event.status === "rejected"
                      ? "bg-red-600 text-white cursor-default"
                      : isUpdatingStatus
                        ? "bg-muted text-muted-foreground cursor-not-allowed"
                        : "bg-muted hover:bg-red-600 hover:text-white text-foreground"
                  }
                  ${isUpdatingStatus ? "opacity-50" : ""}
                `}
              >
                {isUpdatingStatus ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <XCircle className="w-4 h-4" />
                )}
                <span>Reject</span>
              </button>
            </div>
          </div>
        </div>

        {/* Main Content */}
        <div className="flex h-[calc(100vh-60px)] w-full overflow-hidden">
          {/* Editor Section */}
          <div className="flex-1">
            <MonacoDiffEditorGithub
              diffContents={diffContents}
              onContentChange={handleContentChange}
              onEdit={handleEdit}
              optimizationInfo={{
                speedup_x: event.speedup_x || undefined,
                speedup_pct: event.speedup_pct || undefined,
                prCommentFields: prCommentFields,
                generatedTests: metadata.generatedTests,
                coverage_message: metadata.coverage_message,
                review_explanation: event.review_explanation,
                review_quality: event.review_quality,
              }}
              functionName={event.function_name || undefined}
              filePath={event.file_path || undefined}
              onCreatePR={
                event.repository_id && !event.pr_url ? handleOpenBaseBranchDialog : undefined
              }
              onViewPR={event.pr_url ? handleViewPR : undefined}
              prNumber={event.pr_url ? event.pr_url.split("/").pop() : undefined}
              repositoryFullName={event.repository?.full_name || undefined}
              isCreatingPR={creatingPR}
              showGitDiffDownload={!isPrivacyModeWithNoDiff}
              disableAutoSave={event.staging_storage_type === "git_branch"}
              isPrivacyModeNoDiff={isPrivacyModeWithNoDiff}
            />
          </div>

          {/* Comments Sidebar */}
          <div
            className={`bg-muted/30 border-l border-border flex flex-col transition-all duration-300 ${
              showCommentsSection ? "w-96" : "w-0"
            } overflow-hidden`}
          >
            <div
              className={`h-full flex flex-col transition-opacity duration-300 ${showCommentsSection ? "opacity-100" : "opacity-0"}`}
            >
              {/* Comments Header */}
              <div className="p-3 border-b border-border">
                <h3 className="text-sm font-medium text-foreground flex items-center gap-2">
                  <MessageSquare className="w-4 h-4 text-primary" />
                  Comments
                  {comments.length > 0 && (
                    <span className="ml-auto px-1.5 py-0.5 text-xs bg-primary/20 rounded-full text-foreground">
                      {comments.length}
                    </span>
                  )}
                </h3>
              </div>

              {/* Comments List */}
              <div className="flex-1 overflow-y-auto">
                {loadingComments ? (
                  <div className="flex items-center justify-center py-8">
                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                  </div>
                ) : comments.length === 0 ? (
                  <div className="text-center py-8 px-4">
                    <MessageSquare className="w-12 h-12 mx-auto text-muted-foreground/50 mb-3" />
                    <p className="text-muted-foreground text-sm">No comments yet</p>
                  </div>
                ) : (
                  <div className="divide-y divide-border">
                    {comments.map(comment => (
                      <div key={comment.id} className="p-4 hover:bg-accent/50 transition-colors">
                        <div className="flex items-start gap-3">
                          <Image
                            src={
                              comment.author?.github_username
                                ? `https://github.com/${comment.author.github_username}.png`
                                : `https://ui-avatars.com/api/?name=${encodeURIComponent(
                                    comment.author?.name || comment.author?.email || "U",
                                  )}&background=d08e0d&color=fff`
                            }
                            alt={comment.author?.name || "User"}
                            width={32}
                            height={32}
                            className="w-8 h-8 rounded-full"
                          />
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2 mb-1">
                              <span className="font-medium text-sm text-foreground">
                                {comment.author?.name ||
                                  comment.author?.email?.split("@")[0] ||
                                  "Unknown"}
                              </span>
                              <span className="text-xs text-muted-foreground">
                                {formatTimeAgo(comment.created_at)}
                              </span>
                            </div>
                            <MarkdownViewer content={comment.content} />
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>

              {/* Comment Input with Custom Markdown Editor */}
              <div className="border-t border-border p-4 bg-background">
                <div className="mb-3">
                  <MarkdownEditor
                    value={newComment}
                    onChange={setNewComment}
                    placeholder="Add a comment... (supports Markdown)"
                    disabled={isSubmittingComment}
                    height={150}
                  />
                </div>

                {/* Submit Button */}
                <button
                  onClick={handleAddComment}
                  disabled={!newComment.trim() || isSubmittingComment}
                  className="w-full px-4 py-2 text-sm font-medium text-primary-foreground bg-primary hover:bg-primary/90 rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isSubmittingComment ? (
                    <>
                      <Loader2 className="w-4 h-4 animate-spin inline mr-2" />
                      Commenting...
                    </>
                  ) : (
                    "Comment"
                  )}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <BaseBranchDialog
        isOpen={showBaseBranchDialog}
        onClose={() => setShowBaseBranchDialog(false)}
        onConfirm={handleBaseBranchConfirm}
        initialBranch={event.baseBranch || "main"}
        isCreatingPR={creatingPR}
      />
    </div>
  )
}
