"use client"
import React, { useState, useMemo, useEffect, useCallback, useRef } from "react"
import {
  Zap,
  Gauge,
  GitPullRequest,
  Clock,
  GitBranch,
  Users,
  RefreshCw,
  UserPlus,
  AlertCircle,
  BarChart3,
} from "lucide-react"
import { format, subDays } from "date-fns"
import { ActiveUsersLeaderboard } from "@/components/dashboard/ActiveUsersLeaderboard"
import { CompactPullRequestActivityCard } from "@/components/dashboard/CompactPullRequestActivityCard"
import { MetricCard } from "@/components/dashboard/MetricCard"
import { OptimizationPRsTable } from "@/components/dashboard/OptimizationPRsTable"
import { RepositoryDetailSkeleton } from "@/components/repositories/RepositoryDetailSkeleton"
import Image from "next/image"
import { useRouter, useSearchParams } from "next/navigation"
import {
  getRepositoryMembers,
  updateRepositoryMemberRole,
  removeRepositoryMember,
  addRepositoryMemberById,
} from "./action"
import { getRepoDetailInitData, getRepoDetailPrActivityData } from "./data"
import { GitHubUserSearchResult, Member } from "@/lib/types"
import { RepositoryWithUsage } from "@/app/(dashboard)/dashboard/action"
import { useViewMode } from "@/app/app/ViewModeContext"
import { MembersList } from "@/components/members/members-list"
import { UserSearchModal } from "@/components/members/user-search-modal"
import { RoleSelector } from "@/components/members/role-selector"
import { ConfirmDialog } from "@/components/confirm-dialog"

// Repository Header Component
const RepositoryHeader = ({ repository }: { repository: RepositoryWithUsage }) => {
  return (
    <div className="mb-6 sm:mb-8">
      <div className="flex items-start">
        <div className="flex items-start gap-4 w-full">
          {/* Repository Avatar - Circular */}
          <div className="flex-shrink-0">
            {repository.avatarUrl ? (
              <div className="w-12 h-12 sm:w-16 sm:h-16 rounded-full overflow-hidden border-2 border-border/50 shadow-sm">
                <Image
                  src={repository.avatarUrl}
                  alt={`${repository.organization} avatar`}
                  width={64}
                  height={64}
                  className="object-cover w-full h-full"
                />
              </div>
            ) : (
              <div className="w-12 h-12 sm:w-16 sm:h-16 rounded-full bg-gradient-to-br from-primary/10 to-primary/30 flex items-center justify-center border-2 border-border shadow-sm">
                <span className="text-primary font-semibold text-lg sm:text-xl">
                  {repository.name?.substring(0, 1).toUpperCase() || "?"}
                </span>
              </div>
            )}
          </div>

          {/* Repository Info */}
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 flex-wrap">
              <h1 className="text-xl sm:text-2xl font-bold truncate text-foreground">
                {repository.name}
              </h1>
              <span
                className={`px-2.5 py-1 text-xs font-medium rounded-full whitespace-nowrap ${
                  repository.is_private
                    ? "bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400"
                    : "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400"
                }`}
              >
                {repository.is_private ? "Private" : "Public"}
              </span>
              {repository.is_active && (
                <span className="inline-flex items-center px-2.5 py-1 rounded-full text-xs bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400 whitespace-nowrap">
                  <span className="inline-block w-2 h-2 rounded-full bg-green-500 mr-1.5 animate-pulse"></span>
                  Active
                </span>
              )}
              {repository.has_github_action && (
                <span className="inline-flex items-center px-2.5 py-1 rounded-full bg-blue-100 text-xs text-blue-700 dark:bg-blue-900/30 dark:text-blue-400 whitespace-nowrap">
                  <GitBranch size={12} className="mr-1" />
                  GitHub Action
                </span>
              )}
            </div>

            <a
              href={`https://github.com/${repository.full_name}`}
              target="_blank"
              rel="noopener noreferrer"
              className="text-sm text-muted-foreground hover:text-primary transition-colors mt-1 inline-block hover:underline"
            >
              {repository.full_name}
            </a>

            <div className="flex items-center gap-4 mt-2 flex-wrap">
              {repository.last_optimized && (
                <div className="text-xs text-muted-foreground flex items-center whitespace-nowrap">
                  <Clock size={12} className="mr-1" />
                  Last optimized: {new Date(repository.last_optimized).toLocaleDateString()}
                </div>
              )}
              {repository.membersCount !== undefined && repository.membersCount > 0 && (
                <div className="text-xs text-muted-foreground flex items-center whitespace-nowrap">
                  <Users size={12} className="mr-1" />
                  {repository.membersCount} {repository.membersCount === 1 ? "member" : "members"}
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

// Tab Navigation Component
const TabNavigation = ({
  activeTab,
  onTabChange,
}: {
  activeTab: "statistics" | "members"
  onTabChange: (tab: "statistics" | "members") => void
}) => {
  return (
    <div className="bg-card rounded-2xl border border-border shadow-sm p-2 mb-6">
      <div className="flex gap-2">
        <button
          onClick={() => onTabChange("statistics")}
          className={`flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-xl font-medium transition-all duration-200 ${
            activeTab === "statistics"
              ? "bg-primary text-primary-foreground shadow-sm"
              : "text-muted-foreground hover:bg-accent hover:text-foreground"
          }`}
        >
          <BarChart3 size={18} />
          <span className="hidden sm:inline">Statistics</span>
          <span className="sm:hidden">Stats</span>
        </button>
        <button
          onClick={() => onTabChange("members")}
          className={`flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-xl font-medium transition-all duration-200 ${
            activeTab === "members"
              ? "bg-primary text-primary-foreground shadow-sm"
              : "text-muted-foreground hover:bg-accent hover:text-foreground"
          }`}
        >
          <Users size={18} />
          <span>Members</span>
        </button>
      </div>
    </div>
  )
}

// Statistics Tab Component
const StatisticsTab = ({
  optimizationStats,
  optimizationsTrend,
  optimizationsTrendDates,
  successfulOptimizationsTrend,
  successfulOptimizationsTrendDates,
  prActivityData,
  selectedPrYear,
  setSelectedPrYear,
  activeUsersData,
  dateRangeDisplay,
  isMobile,
  repositoryId,
}: {
  optimizationStats: { totalAttempts: number; successfulAttempts: number }
  optimizationsTrend: number[]
  optimizationsTrendDates: string[]
  successfulOptimizationsTrend: number[]
  successfulOptimizationsTrendDates: string[]
  prActivityData: Array<{
    month: string
    pr_created: number
    pr_merged: number
    pr_closed: number
  }>
  selectedPrYear: number
  setSelectedPrYear: (year: number) => void
  activeUsersData: { username: string; eventCount: number; avatarUrl: string }[]
  dateRangeDisplay: string
  isMobile: boolean
  repositoryId: string
}) => {
  return (
    <div className="space-y-6">
      {/* Repository Stats */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-5">
        <MetricCard
          title="Optimization Attempts"
          value={optimizationStats.totalAttempts}
          icon={<Zap size={isMobile ? 16 : 20} />}
          gradientFrom="bg-gradient-to-br from-blue-500/20"
          gradientTo="to-blue-600/20"
          iconColor="text-blue-500"
          chartData={optimizationsTrend}
          chartDates={optimizationsTrendDates}
          chartColor="rgba(59, 130, 246, 1)"
          chartFillColor="rgba(59, 130, 246, 0.2)"
          timeText={dateRangeDisplay}
          emptyStateMessage="No optimization attempts"
          cumulativeChart={true}
        />
        <MetricCard
          title="Optimizations Found"
          value={optimizationStats.successfulAttempts}
          icon={<Gauge size={isMobile ? 16 : 20} />}
          gradientFrom="bg-gradient-to-br from-emerald-500/20"
          gradientTo="to-emerald-600/20"
          iconColor="text-emerald-500"
          chartData={successfulOptimizationsTrend}
          chartDates={successfulOptimizationsTrendDates}
          chartColor="rgba(16, 185, 129, 1)"
          chartFillColor="rgba(16, 185, 129, 0.2)"
          emptyStateMessage="No optimizations found"
          timeText="All time"
          cumulativeChart={true}
          showChart={successfulOptimizationsTrend.length > 0}
        />
      </div>

      {/* PR Activity and Active Users */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-5 h-96 md:h-[500px]">
        <CompactPullRequestActivityCard
          prData={prActivityData}
          selectedYear={selectedPrYear}
          onYearChange={setSelectedPrYear}
          className="h-full"
        />

        <div className="h-full">
          <ActiveUsersLeaderboard leaderboardData={activeUsersData} />
        </div>
      </div>

      {/* Optimization PRs Table */}
      <div>
        <OptimizationPRsTable repositoryId={repositoryId} />
      </div>
    </div>
  )
}

// Members Tab Component
const MembersTab = ({ repoId, currentUserId }: { repoId: string; currentUserId: string }) => {
  const [members, setMembers] = useState<Member[]>([])
  const [loading, setLoading] = useState(true)
  const [showAddModal, setShowAddModal] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [updatingMember, setUpdatingMember] = useState<string | null>(null)
  const [success, setSuccess] = useState<string | null>(null)
  const [searchQuery, setSearchQuery] = useState("")
  const [filterRole, setFilterRole] = useState<"all" | "owner" | "admin" | "member">("all")
  const [isRefreshing, setIsRefreshing] = useState(false)
  const [selectedRole, setSelectedRole] = useState<"admin" | "member">("member")
  const [confirmDialog, setConfirmDialog] = useState<{
    open: boolean
    memberId: string
    memberUsername: string
  } | null>(null)

  const currentUserMember = members.find(m => m.user_id === currentUserId)
  const isAdmin = currentUserMember?.role === "admin" || currentUserMember?.role === "owner"
  const isOnlyMember = members.length === 1

  const fetchMembers = useCallback(async () => {
    if (!isRefreshing) {
      setLoading(true)
    }
    setError(null)

    const result = await getRepositoryMembers(repoId)

    if (result.success && result.data) {
      setMembers(result.data)
    } else {
      setError(result.error || "Failed to load members")
    }

    setLoading(false)
    setIsRefreshing(false)
  }, [repoId, isRefreshing])

  useEffect(() => {
    fetchMembers()
  }, [fetchMembers])

  useEffect(() => {
    if (success) {
      const timer = setTimeout(() => setSuccess(null), 5000)
      return () => clearTimeout(timer)
    }
  }, [success])

  const handleMemberAdded = async () => {
    setIsRefreshing(true)
    await fetchMembers()
    setSuccess("Member added successfully!")
  }

  const handleUserAdd = async (user: GitHubUserSearchResult) => {
    const result = await addRepositoryMemberById(repoId, user, selectedRole)
    if (result.success) {
      handleMemberAdded()
    }
    return result
  }

  const handleUpdateRole = async (memberId: string, newRole: "admin" | "member" | "owner") => {
    setUpdatingMember(memberId)
    setError(null)
    setSuccess(null)

    const result = await updateRepositoryMemberRole(repoId, memberId, newRole)

    if (result.success) {
      setSuccess("Member role updated successfully")
      setIsRefreshing(true)
      await fetchMembers()
    } else {
      setError(result.error || "Failed to update role")
    }

    setUpdatingMember(null)
  }

  const handleRemoveMember = async (memberId: string, memberUsername: string) => {
    setConfirmDialog({ open: true, memberId, memberUsername })
  }

  const confirmRemoveMember = async () => {
    if (!confirmDialog) return

    const { memberId, memberUsername } = confirmDialog

    setUpdatingMember(memberId)
    setError(null)
    setSuccess(null)

    const result = await removeRepositoryMember(repoId, memberId)

    if (result.success) {
      setSuccess(`${memberUsername} has been removed successfully`)
      setIsRefreshing(true)
      await fetchMembers()
    } else {
      setError(result.error || "Failed to remove member")
    }

    setUpdatingMember(null)
    setConfirmDialog(null)
  }

  if (loading) {
    return (
      <div className="bg-card rounded-2xl border border-border p-8 shadow-sm">
        <div className="flex flex-col items-center justify-center">
          <div className="relative">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
            <div className="absolute inset-0 rounded-full border-2 border-primary/20"></div>
          </div>
          <p className="text-sm text-muted-foreground mt-4">Loading members...</p>
        </div>
      </div>
    )
  }

  const adminCount = members.filter(m => m.role === "admin" || m.role === "owner").length
  const memberCount = members.filter(m => m.role === "member").length

  return (
    <>
      <div className="bg-card rounded-2xl border border-border shadow-sm overflow-hidden">
        <div className="p-6 border-b border-border bg-accent/20">
          <div className="flex items-center justify-between gap-4 mb-4">
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-3 mb-2">
                <div className="p-2 rounded-lg bg-primary/10">
                  <Users size={20} className="text-primary" />
                </div>
                <h2 className="text-xl font-semibold text-foreground">Repository Members</h2>
              </div>
              <p className="text-sm text-muted-foreground">
                {members.length} {members.length === 1 ? "member" : "members"} • {adminCount}{" "}
                {adminCount === 1 ? "admin" : "admins"} • {memberCount}{" "}
                {memberCount === 1 ? "member" : "members"}
              </p>
            </div>
            {(isAdmin || isOnlyMember) && (
              <div className="flex items-center gap-3">
                <RoleSelector
                  selectedRole={selectedRole}
                  onChange={setSelectedRole}
                  disabled={showAddModal}
                />
                <button
                  onClick={() => setShowAddModal(true)}
                  disabled={showAddModal}
                  className="flex items-center gap-2 px-4 py-2.5 bg-primary text-primary-foreground rounded-xl hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 text-sm font-medium whitespace-nowrap flex-shrink-0 shadow-sm hover:shadow-md"
                >
                  <UserPlus size={16} />
                  <span className="hidden sm:inline">Add Member</span>
                  <span className="sm:hidden">Add</span>
                </button>
              </div>
            )}
          </div>
        </div>

        <MembersList
          members={members}
          currentUserId={currentUserId}
          isAdmin={isAdmin}
          updatingMember={updatingMember}
          error={error}
          success={success}
          searchQuery={searchQuery}
          filterRole={filterRole}
          onSearchChange={setSearchQuery}
          onFilterChange={setFilterRole}
          onUpdateRole={handleUpdateRole}
          onRemove={handleRemoveMember}
          onDismissError={() => setError(null)}
          onDismissSuccess={() => setSuccess(null)}
        />
      </div>

      <UserSearchModal
        isOpen={showAddModal}
        onClose={() => setShowAddModal(false)}
        onUserAdd={handleUserAdd}
        title={`Add Repository Member as ${selectedRole === "admin" ? "Admin" : "Member"}`}
        description="Search for GitHub users and add them to this repository"
        addButtonText={`Add as ${selectedRole === "admin" ? "Admin" : "Member"}`}
      />

      {/* Confirm Dialog */}
      <ConfirmDialog
        open={confirmDialog?.open || false}
        onOpenChange={open => !open && setConfirmDialog(null)}
        onConfirm={confirmRemoveMember}
        title="Remove Member"
        description={`Are you sure you want to remove ${confirmDialog?.memberUsername} from this repository? This action cannot be undone.`}
        confirmText="Remove"
        cancelText="Cancel"
        variant="destructive"
      />
    </>
  )
}

export interface RepoDetailStats {
  totalAttempts: number
  successfulAttempts: number
  optimizationsTrend: number[]
  optimizationsTrendDates: string[]
  successfulOptimizationsTrend: number[]
  successfulOptimizationsTrendDates: string[]
  prActivityData: Array<{
    month: string
    pr_created: number
    pr_merged: number
    pr_closed: number
  }>
  activeUsersData: { username: string; eventCount: number; avatarUrl: string }[]
  prYear: number
}

export interface RepoDetailClientProps {
  repositoryId: string
  initialUserId: string
  initialOrgId: string | null
  initialRepository: RepositoryWithUsage
  initialStats: RepoDetailStats
}

export function RepoDetailClient({
  repositoryId,
  initialUserId,
  initialOrgId,
  initialRepository,
  initialStats,
}: RepoDetailClientProps) {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { currentOrg } = useViewMode()
  const initialOrgIdRef = useRef(initialOrgId)

  const [repository, setRepository] = useState<RepositoryWithUsage | null>(initialRepository)
  const [currentUserId] = useState<string>(initialUserId)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [retryCount, setRetryCount] = useState(0)
  const maxRetries = 3

  const tabFromUrl = (searchParams.get("tab") as "statistics" | "members") || "statistics"
  const [activeTab, setActiveTab] = useState<"statistics" | "members">(
    currentOrg ? "statistics" : tabFromUrl,
  )

  const [optimizationStats, setOptimizationStats] = useState({
    totalAttempts: initialStats.totalAttempts,
    successfulAttempts: initialStats.successfulAttempts,
  })

  const [prActivityData, setPrActivityData] = useState(initialStats.prActivityData)
  const [selectedPrYear, setSelectedPrYear] = useState<number>(initialStats.prYear)
  const [activeUsersData, setActiveUsersData] = useState(initialStats.activeUsersData)

  const [optimizationsTrend, setOptimizationsTrend] = useState(initialStats.optimizationsTrend)
  const [optimizationsTrendDates, setOptimizationsTrendDates] = useState(
    initialStats.optimizationsTrendDates,
  )
  const [successfulOptimizationsTrend, setSuccessfulOptimizationsTrend] = useState(
    initialStats.successfulOptimizationsTrend,
  )
  const [successfulOptimizationsTrendDates, setSuccessfulOptimizationsTrendDates] = useState(
    initialStats.successfulOptimizationsTrendDates,
  )
  const [isMobile, setIsMobile] = useState<boolean>(false)

  useEffect(() => {
    const handleResize = () => {
      setIsMobile(window.innerWidth < 640)
    }

    if (typeof window !== "undefined") {
      handleResize()
      window.addEventListener("resize", handleResize)
      return () => window.removeEventListener("resize", handleResize)
    }
  }, [])

  useEffect(() => {
    if (currentOrg) {
      setActiveTab("statistics")
    }
  }, [currentOrg])

  const handleTabChange = (tab: "statistics" | "members") => {
    if (currentOrg) return

    setActiveTab(tab)
    const url = new URL(window.location.href)
    url.searchParams.set("tab", tab)
    router.push(url.pathname + url.search, { scroll: false })
  }

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

        if (attempt > 0) {
          await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000))
        }

        const initData = await getRepoDetailInitData(repositoryId, selectedPrYear)

        if (!initData?.repository || !initData.stats) {
          throw new Error("Repository not found")
        }

        setRepository(initData.repository)
        setOptimizationStats({
          totalAttempts: initData.stats.totalAttempts,
          successfulAttempts: initData.stats.successfulAttempts,
        })
        setOptimizationsTrend(initData.stats.optimizationsTrend)
        setOptimizationsTrendDates(initData.stats.optimizationsTrendDates)
        setSuccessfulOptimizationsTrend(initData.stats.successfulOptimizationsTrend)
        setSuccessfulOptimizationsTrendDates(initData.stats.successfulOptimizationsTrendDates)
        setPrActivityData(initData.stats.prActivityData)
        setActiveUsersData(initData.stats.activeUsersData)
        setRetryCount(0)
      } catch (err) {
        console.error(`Failed to fetch repository data (attempt ${attempt + 1}):`, err)

        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 fetchRepositoryData(attempt + 1)
        }

        setError(
          err instanceof Error && err.message === "Repository not found"
            ? "Repository not found"
            : "Failed to load repository data. Please try again later.",
        )
      } finally {
        setLoading(false)
      }
    },
    [maxRetries, selectedPrYear, repositoryId],
  )

  // Only refetch when org changes from what the server provided, or when prYear changes
  useEffect(() => {
    const currentOrgId = currentOrg?.id ?? null
    if (currentOrgId === initialOrgIdRef.current) return
    initialOrgIdRef.current = currentOrgId
    fetchRepositoryData()
  }, [currentOrg?.id, fetchRepositoryData])

  // Refetch PR data when year changes
  const initialPrYearRef = useRef(initialStats.prYear)
  useEffect(() => {
    if (selectedPrYear === initialPrYearRef.current) return
    initialPrYearRef.current = selectedPrYear
    getRepoDetailPrActivityData(repositoryId, selectedPrYear).then(prData => {
      if (prData) {
        setPrActivityData(Array.isArray(prData) ? prData : [])
      }
    })
  }, [selectedPrYear, repositoryId])

  const now = useMemo(() => new Date(), [])
  const last30DaysStart = subDays(now, 30)

  const dateRangeDisplay = useMemo(() => {
    const startMonth = format(last30DaysStart, "MMMM")
    const endMonth = format(now, "MMMM")
    const startYear = format(last30DaysStart, "yyyy")
    const endYear = format(now, "yyyy")

    if (startMonth === endMonth && startYear === endYear) {
      return `${startMonth} ${format(last30DaysStart, "d")}-${format(now, "d")}, ${startYear}`
    } else if (startYear === endYear) {
      return `${format(last30DaysStart, "MMMM d")} - ${format(now, "MMMM d")}, ${startYear}`
    } else {
      return `${format(last30DaysStart, "MMMM d, yyyy")} - ${format(now, "MMMM d, yyyy")}`
    }
  }, [last30DaysStart, now])

  if (loading) {
    return <RepositoryDetailSkeleton showTabNavigation={!currentOrg} />
  }

  if (error) {
    return (
      <div className="flex justify-center items-center min-h-[70vh] p-4">
        <div className="bg-destructive/10 border border-destructive/20 text-destructive p-6 sm:p-8 rounded-2xl w-full max-w-md shadow-lg">
          <div className="inline-flex items-center justify-center w-12 h-12 rounded-full bg-destructive/20 mb-4">
            <AlertCircle size={24} />
          </div>
          <h3 className="text-base sm:text-lg font-semibold mb-2">Unable to Load Repository</h3>
          <p className="mb-4 text-sm sm:text-base opacity-90">{error}</p>
          {retryCount > 0 && (
            <p className="mb-4 text-xs opacity-75">
              Retry attempt: {retryCount}/{maxRetries}
            </p>
          )}
          <button
            onClick={() => fetchRepositoryData()}
            className="flex items-center gap-2 w-full justify-center px-4 py-2.5 bg-destructive hover:bg-destructive/90 text-destructive-foreground rounded-xl text-sm font-medium transition-all shadow-sm hover:shadow-md"
          >
            <RefreshCw size={16} /> Try Again
          </button>
        </div>
      </div>
    )
  }

  if (!repository) {
    return (
      <div className="flex justify-center items-center min-h-[70vh] p-4">
        <div className="text-center">
          <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-accent mb-4">
            <GitPullRequest size={32} className="text-muted-foreground" />
          </div>
          <h3 className="text-lg font-semibold mb-2 text-foreground">Repository not found</h3>
          <p className="text-sm text-muted-foreground">
            The repository you&apos;re looking for doesn&apos;t exist or you don&apos;t have access
            to it.
          </p>
        </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">
        <RepositoryHeader repository={repository} />

        {!currentOrg && <TabNavigation activeTab={activeTab} onTabChange={handleTabChange} />}

        {currentOrg || activeTab === "statistics" ? (
          <StatisticsTab
            optimizationStats={optimizationStats}
            optimizationsTrend={optimizationsTrend}
            optimizationsTrendDates={optimizationsTrendDates}
            successfulOptimizationsTrend={successfulOptimizationsTrend}
            successfulOptimizationsTrendDates={successfulOptimizationsTrendDates}
            prActivityData={prActivityData}
            selectedPrYear={selectedPrYear}
            setSelectedPrYear={setSelectedPrYear}
            activeUsersData={activeUsersData}
            dateRangeDisplay={dateRangeDisplay}
            isMobile={isMobile}
            repositoryId={repositoryId}
          />
        ) : (
          <MembersTab repoId={repositoryId} currentUserId={currentUserId} />
        )}
      </div>
    </div>
  )
}
