import Link from "next/link";
import { startOfWeek } from "date-fns";
import { Activity, Dumbbell } from "lucide-react";
import { DashboardAnalysisCard } from "@/components/dashboard-analysis-card";
import { EmptyState } from "@/components/empty-state";
import { StatCard } from "@/components/stat-card";
import { formatDateShort, formatDistance, formatDuration, formatPace } from "@/lib/format";
import { getDashboardAnalysis, serializeAnalysis } from "@/lib/models/analysis";
import { listRunningActivities } from "@/lib/models/running";
import { listStrengthWorkouts } from "@/lib/models/strength";

export const dynamic = "force-dynamic";

export default async function Home() {
  const [runs, strengthWorkouts, dashboardAnalysis] = await Promise.all([
    listRunningActivities(),
    listStrengthWorkouts(),
    getDashboardAnalysis(),
  ]);

  const weekStart = startOfWeek(new Date(), { weekStartsOn: 1 });
  const weeklyKm = runs
    .filter((run) => run.startTime >= weekStart)
    .reduce((sum, run) => sum + run.distanceM, 0) / 1000;
  const weeklyStrengthSessions = strengthWorkouts.filter((workout) => workout.date >= weekStart).length;

  const latestRun = runs[0];
  const latestStrength = strengthWorkouts[0];

  return (
    <div className="flex flex-col gap-8">

      <section className="grid grid-cols-1 gap-4 sm:grid-cols-2">
        <StatCard label="Kilometry w tym tygodniu" value={`${weeklyKm.toFixed(1)} km`} hint="Bieganie" />
        <StatCard label="Treningi siłowe w tym tygodniu" value={weeklyStrengthSessions} hint="Siłownia" />
      </section>

      <section className="grid grid-cols-1 gap-4 sm:grid-cols-2">
        <div className="flex flex-col gap-3">
          <h2 className="text-lg font-semibold text-fg">Ostatni bieg</h2>
          {latestRun ? (
            <Link
              href={`/running/${latestRun._id.toString()}`}
              className="flex flex-col gap-2 rounded-lg border border-muted/40 bg-surface p-4 transition-colors hover:border-accent/60"
            >
              <div className="font-semibold text-fg">{latestRun.name}</div>
              <div className="text-sm text-fg/60">{formatDateShort(latestRun.startTime)}</div>
              <div className="text-sm text-fg/70">
                {formatDistance(latestRun.distanceM)} · {formatDuration(latestRun.durationSec)} ·{" "}
                {formatPace(latestRun.avgPaceSecPerKm)}
              </div>
            </Link>
          ) : (
            <EmptyState
              icon={<Activity size={32} />}
              title="Brak danych o bieganiu"
              description="Zsynchronizuj aktywności z Garmin Connect, aby zobaczyć tutaj swoje biegi."
              action={{ href: "/running", label: "Przejdź do biegania" }}
            />
          )}
        </div>
        <div className="flex flex-col gap-3">
          <h2 className="text-lg font-semibold text-fg">Ostatni trening siłowy</h2>
          {latestStrength ? (
            <Link
              href={`/strength/${latestStrength._id.toString()}`}
              className="flex flex-col gap-2 rounded-lg border border-muted/40 bg-surface p-4 transition-colors hover:border-accent/60"
            >
              <div className="font-semibold text-fg">{latestStrength.name}</div>
              <div className="text-sm text-fg/60">{formatDateShort(latestStrength.date)}</div>
              <div className="text-sm text-fg/70">
                {latestStrength.exercises.length}{" "}
                {latestStrength.exercises.length === 1 ? "ćwiczenie" : "ćwiczeń"}
              </div>
            </Link>
          ) : (
            <EmptyState
              icon={<Dumbbell size={32} />}
              title="Brak treningów siłowych"
              description="Zaimportuj trening wklejając tekst wygenerowany przez aplikację Strong."
              action={{ href: "/strength/import", label: "Zaimportuj trening" }}
            />
          )}
        </div>
      </section>

      <DashboardAnalysisCard analysis={dashboardAnalysis ? serializeAnalysis(dashboardAnalysis) : null} />
    </div>
  );
}
