"use client"

import React, { useState, useCallback, useEffect, memo } from "react"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  GitPullRequest,
  GitMerge,
  GitPullRequestClosed,
  ExternalLink,
  ChevronLeft,
  ChevronRight,
  FileCode2,
  Zap,
  Clock,
  Filter,
  RefreshCw,
} from "lucide-react"
import { formatDistanceToNow } from "date-fns"
import Image from "next/image"
import type {
  OptimizationPREvent,
  OptimizationPRsResponse,
} from "@/app/(dashboard)/dashboard/action"

interface OptimizationPRsTableProps {
  className?: string
  repositoryId?: string
  initialData?: OptimizationPRsResponse | null
}

// Skeleton loader for table rows
const TableSkeleton = memo(() => (
  <>
    {Array.from({ length: 5 }).map((_, index) => (
      <TableRow key={index}>
        <TableCell>
          <div className="flex items-center gap-3">
            <div className="h-8 w-8 bg-muted animate-pulse rounded-full flex-shrink-0" />
            <div className="space-y-2 flex-1">
              <div className="h-4 bg-muted animate-pulse rounded w-32" />
              <div className="h-3 bg-muted animate-pulse rounded w-48" />
            </div>
          </div>
        </TableCell>
        <TableCell className="hidden md:table-cell text-center">
          <div className="h-6 bg-muted animate-pulse rounded-full w-20 mx-auto" />
        </TableCell>
        <TableCell className="hidden lg:table-cell text-center">
          <div className="h-6 bg-muted animate-pulse rounded w-16 mx-auto" />
        </TableCell>
        <TableCell className="hidden sm:table-cell text-center">
          <div className="h-4 bg-muted animate-pulse rounded w-24 mx-auto" />
        </TableCell>
        <TableCell className="text-center">
          <div className="h-8 bg-muted animate-pulse rounded w-20 mx-auto" />
        </TableCell>
      </TableRow>
    ))}
  </>
))
TableSkeleton.displayName = "TableSkeleton"

// Empty state component
const EmptyState = memo(({ hasFilter }: { hasFilter: boolean }) => (
  <TableRow>
    <TableCell colSpan={5} className="py-12">
      <div className="mx-auto max-w-md text-center bg-muted/5 border border-dashed border-border rounded-xl px-6 py-10">
        <div className="inline-flex items-center justify-center w-14 h-14 rounded-full bg-muted/30 mb-4">
          <GitPullRequest className="h-7 w-7 text-muted-foreground/50" />
        </div>
        <h3 className="text-base font-semibold mb-2">No optimization PRs yet</h3>
        <p className="text-sm text-muted-foreground mb-3">
          {hasFilter
            ? "No PRs match your current filter. Try adjusting or clearing the filter."
            : "When CodeFlash creates optimization PRs for your repositories, they'll appear here."}
        </p>
        {!hasFilter && (
          <div className="flex flex-col sm:flex-row items-center justify-center gap-2 mt-4">
            <a
              href="https://docs.codeflash.ai/getting-started/github-app"
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center justify-center rounded-lg border border-border px-4 py-2 text-sm font-medium text-foreground hover:bg-muted/40 transition-colors"
            >
              Learn more about PR creation
            </a>
          </div>
        )}
      </div>
    </TableCell>
  </TableRow>
))
EmptyState.displayName = "EmptyState"

// Status badge component
const StatusBadge = memo(({ eventType }: { eventType: string }) => {
  const variants: Record<string, { icon: React.ReactNode; label: string; className: string }> = {
    pr_created: {
      icon: <GitPullRequest className="h-3 w-3" />,
      label: "Created",
      className:
        "bg-blue-50 text-blue-700 border-blue-200 dark:bg-blue-900/20 dark:text-blue-300 dark:border-blue-800",
    },
    pr_merged: {
      icon: <GitMerge className="h-3 w-3" />,
      label: "Merged",
      className:
        "bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-300 dark:border-emerald-800",
    },
    pr_closed: {
      icon: <GitPullRequestClosed className="h-3 w-3" />,
      label: "Closed",
      className:
        "bg-red-50 text-red-700 border-red-200 dark:bg-red-900/20 dark:text-red-300 dark:border-red-800",
    },
  }

  const variant = variants[eventType] || {
    icon: <GitPullRequest className="h-3 w-3" />,
    label: eventType,
    className: "bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300",
  }

  return (
    <Badge variant="outline" className={`flex items-center gap-1.5 ${variant.className}`}>
      {variant.icon}
      <span>{variant.label}</span>
    </Badge>
  )
})
StatusBadge.displayName = "StatusBadge"

// Speedup badge component
const SpeedupBadge = memo(
  ({ speedup, speedupPct }: { speedup?: number | null; speedupPct?: number | null }) => {
    if (typeof speedup !== "number" || speedup <= 0)
      return <span className="text-muted-foreground">—</span>

    // Dynamic color based on speedup value
    const clamp = (v: number, min: number, max: number) => Math.min(Math.max(v, min), max)
    const x = clamp(speedup, 1, 100)
    const t = (x - 1) / 99

    const hue = 142 // Green hue
    const lightness = 92 - t * (92 - 35)
    const saturation = 50 + t * (85 - 50)
    const textColor = lightness < 55 ? "#fff" : "#14532d"
    const borderLightness = lightness > 60 ? lightness - 10 : lightness + 10

    const bgColor = `hsl(${hue}, ${saturation}%, ${lightness}%)`
    const borderColor = `hsl(${hue}, ${saturation}%, ${borderLightness}%)`

    return (
      <Badge
        className="font-mono text-[11px] px-2 py-0.5"
        style={{
          backgroundColor: bgColor,
          color: textColor,
          border: `1px solid ${borderColor}`,
        }}
      >
        {speedup.toFixed(1)}x
        {speedupPct && speedupPct > 0 && (
          <span className="ml-1 opacity-80">(+{speedupPct.toFixed(0)}%)</span>
        )}
      </Badge>
    )
  },
)
SpeedupBadge.displayName = "SpeedupBadge"

// Pagination component
const Pagination = memo(
  ({
    currentPage,
    totalPages,
    onPageChange,
    isLoading,
  }: {
    currentPage: number
    totalPages: number
    onPageChange: (page: number) => void
    isLoading: boolean
  }) => {
    if (totalPages <= 1) return null

    // Generate page numbers to display
    const getPageNumbers = () => {
      const pages: (number | "...")[] = []
      const maxVisible = 5

      if (totalPages <= maxVisible) {
        return Array.from({ length: totalPages }, (_, i) => i + 1)
      }

      // Always show first page
      pages.push(1)

      // Calculate range around current page
      let start = Math.max(2, currentPage - 1)
      let end = Math.min(totalPages - 1, currentPage + 1)

      // Adjust if we're near the beginning
      if (currentPage <= 3) {
        end = Math.min(4, totalPages - 1)
      }

      // Adjust if we're near the end
      if (currentPage >= totalPages - 2) {
        start = Math.max(2, totalPages - 3)
      }

      // Add ellipsis if needed before middle section
      if (start > 2) {
        pages.push("...")
      }

      // Add middle pages
      for (let i = start; i <= end; i++) {
        pages.push(i)
      }

      // Add ellipsis if needed after middle section
      if (end < totalPages - 1) {
        pages.push("...")
      }

      // Always show last page
      pages.push(totalPages)

      return pages
    }

    return (
      <div className="flex items-center justify-between mt-4 pt-4 border-t border-border">
        <Button
          variant="outline"
          size="sm"
          disabled={currentPage === 1 || isLoading}
          onClick={() => onPageChange(currentPage - 1)}
          className="flex items-center gap-1"
        >
          <ChevronLeft className="h-4 w-4" />
          <span className="hidden sm:inline">Previous</span>
        </Button>

        <div className="flex items-center gap-1">
          {getPageNumbers().map((pageNum, idx) =>
            pageNum === "..." ? (
              <span key={`ellipsis-${idx}`} className="px-2 text-muted-foreground">
                ...
              </span>
            ) : (
              <Button
                key={pageNum}
                variant={currentPage === pageNum ? "default" : "outline"}
                size="sm"
                className="w-8 h-8 p-0"
                disabled={isLoading}
                onClick={() => onPageChange(pageNum)}
              >
                {pageNum}
              </Button>
            ),
          )}
        </div>

        <Button
          variant="outline"
          size="sm"
          disabled={currentPage === totalPages || isLoading}
          onClick={() => onPageChange(currentPage + 1)}
          className="flex items-center gap-1"
        >
          <span className="hidden sm:inline">Next</span>
          <ChevronRight className="h-4 w-4" />
        </Button>
      </div>
    )
  },
)
Pagination.displayName = "Pagination"

// Main table component
export const OptimizationPRsTable: React.FC<OptimizationPRsTableProps> = memo(
  ({ className, repositoryId, initialData }) => {
    const [data, setData] = useState<OptimizationPRsResponse | null>(initialData ?? null)
    const [isLoading, setIsLoading] = useState(!initialData)
    const [error, setError] = useState<string | null>(null)
    const [currentPage, setCurrentPage] = useState(1)
    const [eventTypeFilter, setEventTypeFilter] = useState("all")
    const [refreshKey, setRefreshKey] = useState(0)
    const pageSize = 10

    // Skip the client-side fetch when server-provided initialData already
    // covers the current query (page 1, all statuses, no repo filter,
    // no manual refresh). This is declarative so it survives React Strict
    // Mode's double-effect invocation in development.
    const initialDataCoversQuery =
      initialData &&
      currentPage === 1 &&
      eventTypeFilter === "all" &&
      !repositoryId &&
      refreshKey === 0

    useEffect(() => {
      if (initialDataCoversQuery) return

      const controller = new AbortController()
      setIsLoading(true)
      setError(null)

      const params = new URLSearchParams({
        page: String(currentPage),
        pageSize: String(pageSize),
        eventTypeFilter,
      })
      if (repositoryId) params.set("repositoryId", repositoryId)

      fetch(`/api/optimization-prs?${params}`, { signal: controller.signal })
        .then(res => {
          if (!res.ok) throw new Error(`HTTP ${res.status}`)
          return res.json() as Promise<OptimizationPRsResponse>
        })
        .then(result => setData(result))
        .catch(err => {
          if (controller.signal.aborted) return
          if (err instanceof DOMException && err.name === "AbortError") return
          console.error("Failed to fetch optimization PRs:", err)
          setError(err instanceof Error ? err.message : "Failed to load optimization PRs")
        })
        .finally(() => {
          if (!controller.signal.aborted) setIsLoading(false)
        })

      return () => controller.abort()
    }, [currentPage, eventTypeFilter, repositoryId, refreshKey, initialDataCoversQuery])

    const handleRefresh = useCallback(() => {
      setRefreshKey(k => k + 1)
    }, [])

    const handlePageChange = useCallback((page: number) => {
      setCurrentPage(page)
    }, [])

    const handleFilterChange = useCallback((value: string) => {
      setEventTypeFilter(value)
      setCurrentPage(1) // Reset to first page when filter changes
    }, [])

    const hasFilter = eventTypeFilter !== "all"

    return (
      <div
        className={`bg-card rounded-xl border border-border p-4 sm:p-5 hover:shadow-md transition-all duration-300 hover:border-primary/20 ${className || ""}`}
      >
        {/* Header */}
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-4">
          <div>
            <h3 className="text-base sm:text-lg font-semibold flex items-center gap-2">
              <GitPullRequest className="h-5 w-5 text-primary" />
              Optimization Pull Requests
            </h3>
            <p className="text-xs sm:text-sm text-muted-foreground mt-0.5">
              PRs created by CodeFlash with performance improvements
            </p>
          </div>

          <div className="flex items-center gap-2">
            <div className="flex items-center gap-1.5 text-sm text-muted-foreground">
              <Filter className="h-4 w-4" />
            </div>
            <Select value={eventTypeFilter} onValueChange={handleFilterChange}>
              <SelectTrigger className="w-[130px] h-8 text-xs sm:text-sm focus:ring-1 focus:ring-offset-0">
                <SelectValue placeholder="All statuses" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">All statuses</SelectItem>
                <SelectItem value="pr_created">Created</SelectItem>
                <SelectItem value="pr_merged">Merged</SelectItem>
                <SelectItem value="pr_closed">Closed</SelectItem>
              </SelectContent>
            </Select>

            <Button
              variant="ghost"
              size="sm"
              onClick={handleRefresh}
              disabled={isLoading}
              className="h-8 w-8 p-0"
            >
              <RefreshCw className={`h-4 w-4 ${isLoading ? "animate-spin" : ""}`} />
            </Button>
          </div>
        </div>

        {/* Error state */}
        {error && (
          <div className="mb-4 p-3 rounded-lg bg-destructive/10 border border-destructive/20">
            <p className="text-destructive text-sm">{error}</p>
            <Button
              variant="outline"
              size="sm"
              onClick={handleRefresh}
              className="mt-2"
              disabled={isLoading}
            >
              Retry
            </Button>
          </div>
        )}

        {/* Table */}
        <div className="rounded-lg border border-border overflow-hidden">
          <Table>
            <TableHeader>
              <TableRow className="bg-muted/30">
                <TableHead className="font-semibold">Repository / Function</TableHead>
                <TableHead className="font-semibold hidden md:table-cell text-center">
                  Status
                </TableHead>
                <TableHead className="font-semibold hidden lg:table-cell text-center">
                  Speedup
                </TableHead>
                <TableHead className="font-semibold hidden sm:table-cell text-center">
                  <div className="flex items-center justify-center gap-1">
                    <Clock className="h-3.5 w-3.5" />
                    <span>Created</span>
                  </div>
                </TableHead>
                <TableHead className="font-semibold text-center">Action</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {isLoading ? (
                <TableSkeleton />
              ) : !data || data.events.length === 0 ? (
                <EmptyState hasFilter={hasFilter} />
              ) : (
                data.events.map((event: OptimizationPREvent) => (
                  <TableRow key={event.id} className="group hover:bg-muted/30">
                    <TableCell>
                      <div className="flex items-center gap-3">
                        {/* Repository avatar */}
                        {event.repository ? (
                          <div className="relative h-8 w-8 flex-shrink-0">
                            <Image
                              src={`https://github.com/${event.repository.full_name.split("/")[0]}.png`}
                              alt={event.repository.full_name}
                              fill
                              sizes="32px"
                              className="rounded-full object-cover"
                              onError={e => {
                                e.currentTarget.style.display = "none"
                              }}
                            />
                          </div>
                        ) : (
                          <div className="h-8 w-8 rounded-full bg-muted flex items-center justify-center flex-shrink-0">
                            <Zap className="h-4 w-4 text-muted-foreground" />
                          </div>
                        )}

                        <div className="min-w-0 flex-1">
                          {/* Repository name */}
                          <div className="text-sm font-medium truncate">
                            {event.repository?.full_name || "Unknown Repository"}
                          </div>
                          {/* Function info */}
                          <div className="flex items-center gap-1.5 text-xs text-muted-foreground truncate">
                            <FileCode2 className="h-3 w-3 flex-shrink-0" />
                            <span className="truncate">
                              {event.function_name || "Unknown function"}
                            </span>
                          </div>
                          {/* Mobile: Status and speedup */}
                          <div className="flex items-center gap-2 mt-1.5 md:hidden">
                            <StatusBadge eventType={event.event_type} />
                            <SpeedupBadge
                              speedup={event.speedup_x}
                              speedupPct={event.speedup_pct}
                            />
                          </div>
                        </div>
                      </div>
                    </TableCell>

                    {/* Status - hidden on mobile */}
                    <TableCell className="hidden md:table-cell text-center">
                      <StatusBadge eventType={event.event_type} />
                    </TableCell>

                    {/* Speedup - hidden on mobile and tablet */}
                    <TableCell className="hidden lg:table-cell text-center">
                      <SpeedupBadge speedup={event.speedup_x} speedupPct={event.speedup_pct} />
                    </TableCell>

                    {/* Created at - hidden on smallest screens */}
                    <TableCell className="hidden sm:table-cell text-center">
                      <span className="text-sm text-muted-foreground whitespace-nowrap">
                        {formatDistanceToNow(new Date(event.created_at), { addSuffix: true })}
                      </span>
                    </TableCell>

                    {/* Action */}
                    <TableCell className="text-center">
                      {event.pr_url ? (
                        <a
                          href={event.pr_url}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-md bg-primary/10 text-primary hover:bg-primary/20 transition-colors"
                        >
                          <span className="hidden sm:inline">View PR</span>
                          <ExternalLink className="h-3.5 w-3.5" />
                        </a>
                      ) : (
                        <span className="text-xs text-muted-foreground">No link</span>
                      )}
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>

        {/* Pagination */}
        {data && data.totalPages > 1 && (
          <Pagination
            currentPage={data.page}
            totalPages={data.totalPages}
            onPageChange={handlePageChange}
            isLoading={isLoading}
          />
        )}

        {/* Results summary */}
        {data && data.totalCount > 0 && (
          <div className="mt-3 text-xs text-muted-foreground text-center sm:text-left">
            Showing {(data.page - 1) * data.pageSize + 1} to{" "}
            {Math.min(data.page * data.pageSize, data.totalCount)} of {data.totalCount} optimization
            PRs
          </div>
        )}
      </div>
    )
  },
)
OptimizationPRsTable.displayName = "OptimizationPRsTable"

export default OptimizationPRsTable
