"use client"

import React, { useState, useMemo, useEffect, useCallback, useRef } from "react"
import {
  Clock,
  GitPullRequest,
  Search,
  ChevronDown,
  X,
  RefreshCw,
  Filter,
  ArrowUpDown,
  BookOpen,
} from "lucide-react"
import Image from "next/image"
import { Card } from "@/components/ui/card"
import { getUserIdAndUsername } from "@/app/utils/auth"
import Link from "next/link"
import { getAllRepositories, RepositoryWithUsage } from "@/app/dashboard/action"
import { useViewMode } from "@/app/app/ViewModeContext"

// Error Boundary Component
class RepositoryErrorBoundary extends React.Component<
  { children: React.ReactNode },
  { hasError: boolean; error?: Error }
> {
  constructor(props: { children: React.ReactNode }) {
    super(props)
    this.state = { hasError: false }
  }

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

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error("Repository page error:", error, errorInfo)
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="flex justify-center items-center h-[70vh]">
          <div className="bg-red-50 text-red-800 p-6 sm:p-8 rounded-xl max-w-md border border-red-200">
            <h3 className="text-base sm:text-lg font-medium mb-2 sm:mb-3">Something went wrong</h3>
            <p className="mb-3 sm:mb-4 text-sm sm:text-base">
              There was an error loading the repositories page.
            </p>
            <button
              onClick={() => window.location.reload()}
              className="flex items-center gap-1 sm:gap-2 w-full justify-center px-3 sm:px-4 py-2 sm:py-2.5 bg-red-100 hover:bg-red-200 text-red-800 rounded-lg text-xs sm:text-sm font-medium transition-colors"
            >
              <RefreshCw size={14} className="sm:w-4 sm:h-4" /> Reload Page
            </button>
          </div>
        </div>
      )
    }

    return this.props.children
  }
}

// Custom hook for debouncing
const useDebounce = (callback: () => void, delay: number) => {
  const timeoutRef = useRef<NodeJS.Timeout>()

  return useCallback(() => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current)
    }
    timeoutRef.current = setTimeout(callback, delay)
  }, [callback, delay])
}

// Custom hook for detecting clicks outside of an element
const useOutsideClick = (callback: () => void) => {
  const ref = React.useRef<HTMLDivElement>(null)

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (ref.current && !ref.current.contains(event.target as Node)) {
        callback()
      }
    }

    document.addEventListener("mousedown", handleClickOutside)
    return () => {
      document.removeEventListener("mousedown", handleClickOutside)
    }
  }, [callback])

  return ref
}

// Enhanced search component
const SearchBar = ({
  searchQuery,
  setSearchQuery,
}: {
  searchQuery: string
  setSearchQuery: (value: string) => void
}) => {
  return (
    <div className="relative flex-1 group">
      <div className="relative">
        <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
          <Search
            size={18}
            className="text-muted-foreground/70 group-focus-within:text-primary transition-colors"
          />
        </div>
        <input
          type="text"
          placeholder="Search repositories..."
          value={searchQuery}
          onChange={e => setSearchQuery(e.target.value)}
          className="block w-full rounded-xl border border-border bg-background/60 p-3 pl-10 text-foreground focus:border-primary focus:ring-1 focus:ring-primary transition-all duration-200"
        />
        {searchQuery && (
          <button
            className="absolute inset-y-0 right-0 flex items-center pr-3 text-muted-foreground hover:text-foreground"
            onClick={() => setSearchQuery("")}
          >
            <X size={18} className="opacity-70 hover:opacity-100" />
          </button>
        )}
      </div>
    </div>
  )
}

// GitHub-style Repository Card Component
const RepositoryCard = ({ repo }: { repo: RepositoryWithUsage }) => (
  <Link href={`/repositories/${repo.id}`}>
    <Card
      key={repo.id}
      className="bg-card bg-muted/5 rounded-xl border border-border hover:border-primary/30 hover:shadow-md hover:shadow-primary/5 transition-all duration-300 overflow-hidden group"
    >
      <div className="p-5">
        <div className="flex items-start">
          {/* Circular avatar for organization */}
          <div className="mr-3 flex-shrink-0">
            {repo.avatarUrl ? (
              <div className="w-9 h-9 sm:w-11 sm:h-11 rounded-full overflow-hidden border-2 border-border/50 group-hover:border-primary/20 transition-colors">
                <Image
                  src={repo.avatarUrl}
                  alt={`${repo.organization} avatar`}
                  width={44}
                  height={44}
                  className="object-cover w-full h-full"
                />
              </div>
            ) : (
              <div className="w-9 h-9 sm:w-11 sm:h-11 rounded-full bg-gradient-to-br from-primary/10 to-primary/30 flex items-center justify-center border-2 border-border group-hover:from-primary/20 group-hover:to-primary/40 transition-colors">
                <span className="text-primary font-semibold">
                  {repo.name?.substring(0, 1).toUpperCase() || "?"}
                </span>
              </div>
            )}
          </div>

          <div className="flex-1 min-w-0">
            {/* Repository name with visibility badge */}
            <div className="flex items-center flex-wrap gap-1">
              <h3 className="text-sm sm:text-base font-semibold text-primary hover:underline truncate">
                {repo.name || "Unknown Repository"}
              </h3>

              <span
                className={`ml-1 px-1.5 sm:px-2 py-0.5 text-xs font-medium rounded-full ${repo.is_private ? "bg-amber-100 text-amber-700" : "bg-emerald-100 text-emerald-700"}`}
              >
                {repo.is_private ? "Private" : "Public"}
              </span>
            </div>

            {/* Organization/full name */}
            <p className="text-xs sm:text-sm text-muted-foreground mb-2">
              {repo.full_name || repo.name}
            </p>

            {/* Repository stats - matching schema data */}
            <div className="flex items-center flex-wrap gap-1.5 sm:gap-2">
              {/* Active status */}
              <span
                className={`inline-flex items-center px-1.5 sm:px-2 py-0.5 sm:py-1 rounded-full text-xs ${repo.is_active ? "bg-green-100 text-green-700" : "bg-gray-100 text-gray-600"}`}
              >
                <span
                  className={`inline-block w-1.5 sm:w-2 h-1.5 sm:h-2 rounded-full ${repo.is_active ? "bg-green-500" : "bg-gray-400"} mr-1 sm:mr-1.5`}
                ></span>
                <span>{repo.is_active ? "Active" : "Inactive"}</span>
              </span>

              {/* GitHub Action */}
              {repo.has_github_action && (
                <span className="inline-flex items-center px-1.5 sm:px-2 py-0.5 sm:py-1 rounded-full bg-blue-50 text-xs text-blue-700">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    viewBox="0 0 16 16"
                    width="10"
                    height="10"
                    className="mr-1 fill-current sm:w-3 sm:h-3"
                  >
                    <path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"></path>
                  </svg>
                  Action
                </span>
              )}

              {/* Members count if available */}
              {repo.membersCount !== undefined && repo.membersCount > 0 && (
                <span className="inline-flex items-center px-1.5 sm:px-2 py-0.5 sm:py-1 rounded-full bg-indigo-50 text-xs text-indigo-700">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="10"
                    height="10"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    className="mr-1 sm:w-3 sm:h-3"
                  >
                    <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path>
                    <circle cx="9" cy="7" r="4"></circle>
                    <path d="M23 21v-2a4 4 0 0 0-3-3.87"></path>
                    <path d="M16 3.13a4 4 0 0 1 0 7.75"></path>
                  </svg>
                  {repo.membersCount}
                </span>
              )}
            </div>
          </div>
        </div>

        {/* Last optimized date */}
        {repo.last_optimized && (
          <div className="mt-3 sm:mt-4 text-xs text-muted-foreground flex items-center">
            <Clock size={10} className="mr-1 sm:w-3 sm:h-3" />
            Last optimized: {new Date(repo.last_optimized).toLocaleDateString()}
          </div>
        )}
      </div>
    </Card>
  </Link>
)

// Import skeleton loaders
import {
  RepositoriesSkeleton,
  RepositoriesRefreshingSkeleton,
} from "@/components/repositories/RepositoriesSkeleton"

// Loading State Component (now using skeleton loaders)
const RepositoriesLoading = ({ isRefreshing = false }: { isRefreshing?: boolean }) =>
  isRefreshing ? (
    <RepositoriesRefreshingSkeleton />
  ) : (
    <RepositoriesSkeleton message="Loading repositories..." />
  )

// Page Header Component
const PageHeader = ({ totalCount }: { totalCount: number }) => (
  <div className="mb-6 sm:mb-8">
    <div className="flex items-center gap-3 mb-2">
      <h1 className="text-xl sm:text-2xl font-bold">Repositories</h1>
      <div className="px-2 py-0.5 sm:px-2.5 sm:py-1 bg-primary/10 text-primary rounded-full text-xs sm:text-sm font-medium">
        {totalCount} total
      </div>
    </div>
  </div>
)

// Main component for repository list with filters
const RepositoryList = ({ repositories }: { repositories: RepositoryWithUsage[] }) => {
  const [searchQuery, setSearchQuery] = useState("")
  const [filter, setFilter] = useState<"all" | "active" | "public" | "private">("all")
  const [isFilterDropdownOpen, setIsFilterDropdownOpen] = useState(false)
  const [sortBy, setSortBy] = useState<"name">("name")
  const [isSortDropdownOpen, setIsSortDropdownOpen] = useState(false)

  const filterDropdownRef = useOutsideClick(() => setIsFilterDropdownOpen(false))
  const sortDropdownRef = useOutsideClick(() => setIsSortDropdownOpen(false))

  const getSortLabel = (sortType: string) => {
    switch (sortType) {
      case "name":
        return "Name"
      default:
        return "Last Optimized"
    }
  }

  const filteredRepositories = useMemo(() => {
    // Add safety check for repositories array
    if (!repositories || !Array.isArray(repositories)) {
      return []
    }

    let repos = repositories.filter(repo => {
      // Add safety checks for repo properties
      if (!repo) return false

      // Search in name and full_name with safety checks
      const matchesSearch =
        searchQuery === "" ||
        (repo.name && repo.name.toLowerCase().includes(searchQuery.toLowerCase())) ||
        (repo.full_name && repo.full_name.toLowerCase().includes(searchQuery.toLowerCase())) ||
        (repo.organization && repo.organization.toLowerCase().includes(searchQuery.toLowerCase()))

      if (!matchesSearch) return false

      switch (filter) {
        case "active":
          return repo.is_active
        case "public":
          return !repo.is_private
        case "private":
          return repo.is_private
        default:
          return true
      }
    })

    // Sort repositories with safety check
    switch (sortBy) {
      case "name":
        repos = repos.sort((a, b) => {
          const nameA = a?.name || ""
          const nameB = b?.name || ""
          return nameA.localeCompare(nameB)
        })
        break
    }

    return repos
  }, [repositories, searchQuery, filter, sortBy])

  return (
    <>
      <div className="flex flex-col md:flex-row gap-3 sm:gap-4 mb-5 sm:mb-6">
        <SearchBar searchQuery={searchQuery} setSearchQuery={setSearchQuery} />

        <div className="flex gap-2">
          <div className="relative" ref={filterDropdownRef}>
            <button
              onClick={() => setIsFilterDropdownOpen(!isFilterDropdownOpen)}
              className="flex items-center gap-1 sm:gap-2 px-3 sm:px-4 py-2.5 sm:py-3 text-xs sm:text-sm bg-background border border-border rounded-xl hover:border-primary/50 transition-colors focus:outline-none focus:ring-1 focus:ring-primary"
            >
              <Filter size={14} className="text-muted-foreground sm:w-4 sm:h-4" />
              <span>
                {filter === "all"
                  ? "All"
                  : filter.charAt(0).toUpperCase() + filter.slice(1).replace(/-/g, " ")}
              </span>
              <ChevronDown
                size={14}
                className={`transition-transform text-muted-foreground sm:w-4 sm:h-4 ${isFilterDropdownOpen ? "rotate-180" : ""}`}
              />
            </button>

            {isFilterDropdownOpen && (
              <div className="absolute z-10 mt-2 w-48 sm:w-52 bg-card rounded-xl shadow-lg overflow-hidden border border-border animate-in fade-in-50 slide-in-from-top-5">
                <div className="py-1">
                  <button
                    onClick={() => {
                      setFilter("all")
                      setIsFilterDropdownOpen(false)
                    }}
                    className={`w-full px-3 sm:px-4 py-2 sm:py-2.5 text-left hover:bg-muted flex items-center ${filter === "all" ? "bg-primary/10 text-primary font-medium" : ""}`}
                  >
                    <span className="w-4 sm:w-5 h-4 sm:h-5 mr-1.5 sm:mr-2 flex items-center justify-center">
                      {filter === "all" && (
                        <span className="w-1.5 h-1.5 rounded-full bg-primary"></span>
                      )}
                    </span>
                    All repositories
                  </button>
                </div>
                <div className="border-t border-border py-1">
                  <button
                    onClick={() => {
                      setFilter("active")
                      setIsFilterDropdownOpen(false)
                    }}
                    className={`w-full px-3 sm:px-4 py-2 sm:py-2.5 text-left hover:bg-muted flex items-center ${filter === "active" ? "bg-primary/10 text-primary font-medium" : ""}`}
                  >
                    <span className="w-4 sm:w-5 h-4 sm:h-5 mr-1.5 sm:mr-2 flex items-center justify-center">
                      {filter === "active" && (
                        <span className="w-1.5 h-1.5 rounded-full bg-primary"></span>
                      )}
                    </span>
                    Active
                  </button>
                </div>
                <div className="border-t border-border py-1">
                  <button
                    onClick={() => {
                      setFilter("public")
                      setIsFilterDropdownOpen(false)
                    }}
                    className={`w-full px-3 sm:px-4 py-2 sm:py-2.5 text-left hover:bg-muted flex items-center ${filter === "public" ? "bg-primary/10 text-primary font-medium" : ""}`}
                  >
                    <span className="w-4 sm:w-5 h-4 sm:h-5 mr-1.5 sm:mr-2 flex items-center justify-center">
                      {filter === "public" && (
                        <span className="w-1.5 h-1.5 rounded-full bg-primary"></span>
                      )}
                    </span>
                    Public
                  </button>
                  <button
                    onClick={() => {
                      setFilter("private")
                      setIsFilterDropdownOpen(false)
                    }}
                    className={`w-full px-3 sm:px-4 py-2 sm:py-2.5 text-left hover:bg-muted flex items-center ${filter === "private" ? "bg-primary/10 text-primary font-medium" : ""}`}
                  >
                    <span className="w-4 sm:w-5 h-4 sm:h-5 mr-1.5 sm:mr-2 flex items-center justify-center">
                      {filter === "private" && (
                        <span className="w-1.5 h-1.5 rounded-full bg-primary"></span>
                      )}
                    </span>
                    Private
                  </button>
                </div>
              </div>
            )}
          </div>

          <div className="relative" ref={sortDropdownRef}>
            <button
              onClick={() => setIsSortDropdownOpen(!isSortDropdownOpen)}
              className="flex items-center gap-1 sm:gap-2 px-3 sm:px-4 py-2.5 sm:py-3 text-xs sm:text-sm bg-background border border-border rounded-xl hover:border-primary/50 transition-colors focus:outline-none focus:ring-1 focus:ring-primary"
            >
              <ArrowUpDown size={14} className="text-muted-foreground sm:w-4 sm:h-4" />
              <span>Sort: {getSortLabel(sortBy)}</span>
              <ChevronDown
                size={14}
                className={`transition-transform text-muted-foreground sm:w-4 sm:h-4 ${isSortDropdownOpen ? "rotate-180" : ""}`}
              />
            </button>

            {isSortDropdownOpen && (
              <div className="absolute right-0 z-10 mt-2 w-48 sm:w-52 bg-card rounded-xl shadow-lg overflow-hidden border border-border animate-in fade-in-50 slide-in-from-top-5">
                <div className="py-1">
                  <button
                    onClick={() => {
                      setSortBy("name")
                      setIsSortDropdownOpen(false)
                    }}
                    className={`w-full px-3 sm:px-4 py-2 sm:py-2.5 text-left hover:bg-muted flex items-center ${sortBy === "name" ? "bg-primary/10 text-primary font-medium" : ""}`}
                  >
                    <span className="w-4 sm:w-5 h-4 sm:h-5 mr-1.5 sm:mr-2 flex items-center justify-center">
                      {sortBy === "name" && (
                        <span className="w-1.5 h-1.5 rounded-full bg-primary"></span>
                      )}
                    </span>
                    Name
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Search indicator */}
      {searchQuery && (
        <div className="flex items-center mb-4 sm:mb-5 ml-1">
          <span className="text-xs sm:text-sm text-muted-foreground mr-1 sm:mr-2">
            Searching for:
          </span>
          <div className="bg-primary/10 text-primary px-2 sm:px-3 py-1 sm:py-1.5 rounded-full text-xs sm:text-sm flex items-center gap-1 sm:gap-1.5">
            <span>{searchQuery}</span>
            <button
              onClick={() => setSearchQuery("")}
              className="text-primary hover:text-primary/80"
            >
              <X size={12} className="sm:w-4 sm:h-4" />
            </button>
          </div>
        </div>
      )}

      {filteredRepositories.length === 0 ? (
        <div className="text-center py-16 sm:py-20 bg-card/50 rounded-xl border border-dashed border-border">
          <div className="inline-flex items-center justify-center w-16 h-16 sm:w-20 sm:h-20 rounded-full bg-muted/40 mb-3 sm:mb-4">
            <Search size={24} className="text-muted-foreground sm:w-7 sm:h-7" />
          </div>
          <h3 className="text-base sm:text-lg font-medium mb-1 sm:mb-2">No repositories found</h3>
          <p className="text-xs sm:text-sm text-muted-foreground max-w-md mx-auto">
            {
              "We couldn't find any repositories matching your search criteria. Try adjusting your filters or search term."
            }
          </p>
          <button
            onClick={() => {
              setSearchQuery("")
              setFilter("all")
            }}
            className="mt-4 sm:mt-5 px-4 sm:px-5 py-2 sm:py-2.5 bg-primary text-primary-foreground rounded-lg sm:rounded-xl text-xs sm:text-sm hover:bg-primary/90 transition-colors"
          >
            Clear filters
          </button>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-5">
          {filteredRepositories.map(repo => (
            <RepositoryCard key={repo.id} repo={repo} />
          ))}
        </div>
      )}
    </>
  )
}

// Main page component
const maxRetries = 3

function RepositoriesPage() {
  const [repositories, setRepositories] = useState<RepositoryWithUsage[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [isRefreshing, setIsRefreshing] = useState(false)
  const [retryCount, setRetryCount] = useState(0)
  const { currentOrg } = useViewMode()

  const fetchRepositories = useCallback(
    async (attempt = 0) => {
      try {
        setLoading(attempt === 0)
        setError(null)

        // Add a small delay for rapid refreshes and retries
        if (attempt > 0) {
          await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000))
        }

        const data = await getUserIdAndUsername()
        if (!data || !data.userId || !data.username) {
          throw new Error("User authentication data not found")
        }

        const repos = await getAllRepositories(
          currentOrg ? { orgId: currentOrg.id } : { userId: data.userId, username: data.username },
        )

        if (Array.isArray(repos)) {
          setRepositories(repos)
          setRetryCount(0) // Reset retry count on success
        } else {
          console.warn("Received non-array repositories data:", repos)
          setRepositories([])
        }
      } catch (err) {
        console.error(`Failed to fetch repositories (attempt ${attempt + 1}):`, err)

        // If it's an auth error and we haven't exceeded retries, try again
        if (
          attempt < maxRetries &&
          err instanceof Error &&
          (err.message.includes("authentication") ||
            err.message.includes("User authentication data not found") ||
            err.message.includes("Unauthorized") ||
            err.message.includes("No valid session found"))
        ) {
          setRetryCount(attempt + 1)
          return fetchRepositories(attempt + 1)
        }

        setError("Failed to load repositories. Please try again later.")
        setRepositories([])
      } finally {
        setLoading(false)
        setIsRefreshing(false)
      }
    },
    [currentOrg],
  )

  // Debounced refresh to prevent rapid successive calls
  const debouncedRefresh = useDebounce(() => {
    setIsRefreshing(true)
    fetchRepositories()
  }, 300)

  const handleRefresh = () => {
    if (!isRefreshing && !loading) {
      debouncedRefresh()
    }
  }

  // Handle browser refresh with beforeunload
  useEffect(() => {
    const handleBeforeUnload = () => {
      // Clear any pending timeouts
      return null
    }

    window.addEventListener("beforeunload", handleBeforeUnload)
    return () => window.removeEventListener("beforeunload", handleBeforeUnload)
  }, [])

  useEffect(() => {
    // Check if user was recently authenticated
    const lastAuthCheck = localStorage.getItem("lastAuthCheck")
    const now = Date.now()

    // If last auth check was less than 2 seconds ago, wait a bit
    if (lastAuthCheck && now - parseInt(lastAuthCheck) < 2000) {
      const delay = 2000 - (now - parseInt(lastAuthCheck))
      setTimeout(() => {
        fetchRepositories()
      }, delay)
    } else {
      // Add a small delay to prevent race conditions on rapid refreshes
      const timeoutId = setTimeout(() => {
        fetchRepositories()
      }, 100)

      const cleanup = () => clearTimeout(timeoutId)
      return cleanup
    }

    // Update last auth check time
    localStorage.setItem("lastAuthCheck", now.toString())
  }, [fetchRepositories])

  // Refresh Button Component
  const RefreshButton = () => (
    <button
      onClick={handleRefresh}
      disabled={isRefreshing || loading}
      className={`flex items-center gap-1 sm:gap-2 px-3 sm:px-4 py-1.5 sm:py-2 rounded-lg text-xs sm:text-sm border border-border bg-background hover:bg-muted/50 transition-colors ${
        isRefreshing || loading ? "opacity-50 cursor-not-allowed" : ""
      }`}
    >
      <RefreshCw
        size={12}
        className={`text-muted-foreground sm:w-4 sm:h-4 ${isRefreshing || loading ? "animate-spin" : ""}`}
      />
      {isRefreshing ? "Refreshing..." : "Refresh"}
    </button>
  )

  if (loading) {
    return <RepositoriesLoading isRefreshing={isRefreshing} />
  }

  if (error) {
    return (
      <div className="flex justify-center items-center h-[70vh]">
        <div className="bg-red-50 text-red-800 p-6 sm:p-8 rounded-xl max-w-md border border-red-200">
          <h3 className="text-base sm:text-lg font-medium mb-2 sm:mb-3">
            Unable to Load Repositories
          </h3>
          <p className="mb-3 sm:mb-4 text-sm sm:text-base">{error}</p>
          {retryCount > 0 && (
            <p className="mb-3 text-xs text-red-600">
              Retry attempt: {retryCount}/{maxRetries}
            </p>
          )}
          <button
            onClick={() => fetchRepositories()}
            className="flex items-center gap-1 sm:gap-2 w-full justify-center px-3 sm:px-4 py-2 sm:py-2.5 bg-red-100 hover:bg-red-200 text-red-800 rounded-lg text-xs sm:text-sm font-medium transition-colors"
          >
            <RefreshCw size={14} className="sm:w-4 sm:h-4" /> Try Again
          </button>
        </div>
      </div>
    )
  }

  return (
    <div className="flex-1 bg-background">
      <div className="h-screen py-6 sm:py-8 px-4 sm:px-6 max-w-[1400px] mx-auto">
        <PageHeader totalCount={repositories?.length || 0} />

        <div className="bg-card p-4 sm:p-6 rounded-xl border border-border">
          <div className="flex justify-between items-center mb-4 sm:mb-6">
            <h2 className="text-base sm:text-lg font-semibold flex items-center">
              <BookOpen size={18} className="mr-2 text-primary" />
              Repository List
            </h2>
            <RefreshButton />
          </div>

          {!repositories || repositories.length === 0 ? (
            <div className="flex justify-center items-center min-h-[300px] sm:min-h-[400px] w-full">
              <div className="text-center py-12 sm:py-16 bg-muted/10 rounded-xl border border-dashed border-border max-w-lg w-full px-5 sm:px-8">
                <div className="inline-flex items-center justify-center w-12 h-12 sm:w-16 sm:h-16 rounded-full bg-muted/20 mb-3 sm:mb-4">
                  <GitPullRequest size={20} className="text-muted-foreground sm:w-6 sm:h-6" />
                </div>
                <h3 className="text-base sm:text-lg font-semibold mb-2">
                  No repositories connected
                </h3>
                <p className="text-xs sm:text-sm text-muted-foreground mx-auto mb-4 sm:mb-6 max-w-md">
                  Install the Codeflash GitHub App for your organization and grant access to the
                  repositories you want us to optimize.
                </p>
                <div className="flex flex-col sm:flex-row items-center justify-center gap-2 sm:gap-3">
                  <a
                    href="https://github.com/apps/codeflash-ai/installations/select_target"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="w-full sm:w-auto inline-flex items-center justify-center rounded-lg bg-primary px-4 py-2 text-xs sm:text-sm font-medium text-primary-foreground hover:bg-primary/90 transition-colors"
                  >
                    Install GitHub App
                  </a>
                  <a
                    href="https://docs.codeflash.ai/getting-started/local-installation"
                    target="_blank"
                    rel="noopener noreferrer"
                    className="w-full sm:w-auto inline-flex items-center justify-center rounded-lg border border-border px-4 py-2 text-xs sm:text-sm font-medium text-foreground hover:bg-muted/40 transition-colors"
                  >
                    View setup guide
                  </a>
                </div>
              </div>
            </div>
          ) : (
            <RepositoryList repositories={repositories} />
          )}
        </div>
      </div>
    </div>
  )
}

// Main export with error boundary
export default function RepositoriesPageWrapper() {
  return (
    <RepositoryErrorBoundary>
      <RepositoriesPage />
    </RepositoryErrorBoundary>
  )
}
