import { Suspense } from "react"
import { Lock, Globe, Zap, Gauge, FolderGit2, BookOpen } from "lucide-react"
import { getDashboardData, getOptimizationPRs } from "./action"
import { getAccountContext } from "@/lib/server/get-account-context"
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 {
  OptimizationPRsTableSkeleton,
  MetricCardSkeleton,
  PullRequestActivityCardSkeleton,
  ActiveUsersLeaderboardSkeleton,
} from "@/components/dashboard/DashboardSkeleton"
import { YearSelector } from "./_components/YearSelector"
import { cacheLife, cacheTag } from "next/cache"
import { format, subDays } from "date-fns"
import type { AccountPayload } from "@codeflash-ai/common"

function getDateRangeDisplay(): string {
  const now = new Date()
  const last30DaysStart = subDays(now, 30)
  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}`
  }
  if (startYear === endYear) {
    return `${format(last30DaysStart, "MMMM d")} - ${format(now, "MMMM d")}, ${startYear}`
  }
  return `${format(last30DaysStart, "MMMM d, yyyy")} - ${format(now, "MMMM d, yyyy")}`
}

// Async server component: streams PR table data independently
async function OptimizationPRsSection({ payload }: { payload: AccountPayload }) {
  "use cache"
  cacheLife("frequent")
  cacheTag("optimization-prs")

  const data = await getOptimizationPRs(payload)
  return <OptimizationPRsTable initialData={data} />
}

// Async server component: streams stats + charts independently
async function DashboardStatsSection({
  payload,
  selectedYear,
}: {
  payload: AccountPayload
  selectedYear: number
}) {
  "use cache"
  cacheLife("dashboard")
  cacheTag("dashboard-stats")

  const { stats, repos } = await getDashboardData(payload, selectedYear)

  const repositories = Array.isArray(repos) ? repos : []
  const privateRepos = repositories.filter(repo => repo?.is_private).length
  const publicRepos = repositories.length - privateRepos
  const totalRepos = repositories.length

  const dateRangeDisplay = getDateRangeDisplay()

  const optimizationsTrend = stats.optimizations.timeSeries.map(item => item.count)
  const optimizationsTrendDates = stats.optimizations.timeSeries.map(item => item.date)
  const successfulOptimizationsTrend = stats.optimizations.successfulTimeSeries.map(
    item => item.count,
  )
  const successfulOptimizationsTrendDates = stats.optimizations.successfulTimeSeries.map(
    item => item.date,
  )

  return (
    <>
      {totalRepos === 0 && (
        <div className="mb-6 sm:mb-8">
          <div className="rounded-xl border border-dashed border-border bg-muted/10 px-5 py-4 sm:px-6 sm:py-5 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
            <div>
              <h2 className="text-sm sm:text-base font-semibold text-foreground">
                Connect a repository to unlock insights
              </h2>
              <p className="text-xs sm:text-sm text-muted-foreground max-w-xl">
                Install the Codeflash GitHub App and grant access to at least one repository so we
                can populate your dashboard with optimization activity.
              </p>
            </div>
            <div className="flex flex-col sm:flex-row gap-2 sm:gap-3">
              <a
                href="https://github.com/apps/codeflash-ai/installations/select_target"
                target="_blank"
                rel="noopener noreferrer"
                className="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="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>
      )}

      <div className="grid grid-cols-1 gap-3 sm:gap-5 mb-6 sm:mb-8">
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-5">
          <MetricCard
            title="Optimization Attempts"
            value={stats.optimizations.total}
            icon={<Zap />}
            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={`Year ${selectedYear}`}
            emptyStateMessage="No data"
            cumulativeChart={true}
          />
          <MetricCard
            title="Optimizations Found"
            value={stats.optimizations.successful}
            subtitle=""
            icon={<Gauge />}
            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 data"
            timeText={`Year ${selectedYear}`}
            cumulativeChart={true}
            showChart={successfulOptimizationsTrend.length > 0}
          />
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-3 sm:gap-5">
          <MetricCard
            title="Total Repositories"
            value={totalRepos}
            icon={<BookOpen />}
            gradientFrom="bg-gradient-to-br from-blue-500/20"
            gradientTo="to-blue-600/20"
            iconColor="text-blue-500"
            timeText=""
            showChart={false}
          />

          <MetricCard
            title="Active Repositories"
            value={stats.activeReposLast30Days.length}
            subtitle="last 30 days"
            icon={<FolderGit2 />}
            gradientFrom="bg-gradient-to-br from-purple-500/20"
            gradientTo="to-purple-600/20"
            iconColor="text-purple-500"
            timeText={dateRangeDisplay}
            showChart={false}
          />

          <MetricCard
            title="Private Repositories"
            value={privateRepos}
            icon={<Lock />}
            gradientFrom="bg-gradient-to-br from-amber-500/20"
            gradientTo="to-amber-600/20"
            iconColor="text-amber-500"
            timeText=""
            showChart={false}
          />

          <MetricCard
            title="Public Repositories"
            value={publicRepos}
            icon={<Globe />}
            gradientFrom="bg-gradient-to-br from-violet-500/20"
            gradientTo="to-violet-600/20"
            iconColor="text-violet-500"
            timeText=""
            showChart={false}
          />
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-5 mb-6 sm:mb-8 h-96 md:h-[500px]">
        <CompactPullRequestActivityCard
          prData={stats.pullRequests}
          selectedYear={selectedYear}
          className="h-full"
        />

        <div className="h-full">
          <ActiveUsersLeaderboard leaderboardData={stats.activeUsersLast30Days} />
        </div>
      </div>
    </>
  )
}

// Skeleton for the stats section matching the exact layout structure
function StatsSkeletonFallback() {
  return (
    <>
      <div className="grid grid-cols-1 gap-3 sm:gap-5 mb-6 sm:mb-8">
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-5">
          <MetricCardSkeleton showChart={true} />
          <MetricCardSkeleton showChart={true} />
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-3 sm:gap-5">
          <MetricCardSkeleton showChart={false} />
          <MetricCardSkeleton showChart={false} />
          <MetricCardSkeleton showChart={false} />
          <MetricCardSkeleton showChart={false} />
        </div>
      </div>
      <div className="grid grid-cols-1 md:grid-cols-2 gap-3 sm:gap-5 mb-6 sm:mb-8 h-96 md:h-[500px]">
        <PullRequestActivityCardSkeleton />
        <ActiveUsersLeaderboardSkeleton />
      </div>
    </>
  )
}

export default async function DashboardPage({
  searchParams,
}: {
  searchParams: Promise<{ year?: string }>
}) {
  const params = await searchParams
  const currentYear = new Date().getFullYear()
  const parsedYear = params.year ? parseInt(params.year, 10) : currentYear
  const selectedYear = Number.isNaN(parsedYear) ? currentYear : parsedYear

  const accountPayload = await getAccountContext()

  return (
    <div className="min-h-screen pb-8 py-6 sm:py-8 px-4 sm:px-6 max-w-[1400px] mx-auto">
      <div className="mb-6 sm:mb-8">
        <div className="flex items-center justify-between mb-2">
          <h1 className="text-xl sm:text-2xl font-bold">Dashboard</h1>
          <Suspense>
            <YearSelector selectedYear={selectedYear} />
          </Suspense>
        </div>
      </div>

      {/* PR table streams independently — first data section to appear */}
      <div className="mb-6 sm:mb-8">
        <Suspense fallback={<OptimizationPRsTableSkeleton />}>
          <OptimizationPRsSection payload={accountPayload} />
        </Suspense>
      </div>

      {/* Stats, metrics, and charts stream as a group */}
      <Suspense fallback={<StatsSkeletonFallback />}>
        <DashboardStatsSection payload={accountPayload} selectedYear={selectedYear} />
      </Suspense>
    </div>
  )
}
