import Link from "next/link";
import { Plus } from "lucide-react";
import { EmptyState } from "@/components/empty-state";
import { VolumeChart } from "@/components/volume-chart";
import { formatDateShort } from "@/lib/format";
import { listStrengthWorkouts } from "@/lib/models/strength";
import { workoutVolumeKg } from "@/lib/strength/stats";

export const dynamic = "force-dynamic";

const VOLUME_CHART_LIMIT = 12;

export default async function StrengthPage() {
  const workouts = await listStrengthWorkouts();

  const volumeData = workouts
    .slice(0, VOLUME_CHART_LIMIT)
    .map((workout) => ({ label: formatDateShort(workout.date), volumeKg: workoutVolumeKg(workout) }))
    .reverse();

  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-fg">Siłownia</h1>
          <p className="mt-1 text-sm text-fg/60">
            Treningi zaimportowane z aplikacji Strong.
          </p>
        </div>
        <Link
          href="/strength/import"
          className="flex items-center gap-1.5 rounded-md bg-accent px-3 py-2 text-sm font-semibold text-fg transition-opacity hover:opacity-90"
        >
          <Plus size={16} />
          Importuj
        </Link>
      </div>

      {volumeData.length > 1 ? <VolumeChart data={volumeData} /> : null}

      {workouts.length === 0 ? (
        <EmptyState
          title="Brak treningów siłowych"
          description="Zaimportuj swój pierwszy trening, wklejając tekst wygenerowany przez funkcję 'Share workout' w aplikacji Strong."
          action={{ href: "/strength/import", label: "Zaimportuj trening" }}
        />
      ) : (
        <ul className="flex flex-col gap-3">
          {workouts.map((workout) => (
            <li key={workout._id.toString()}>
              <Link
                href={`/strength/${workout._id.toString()}`}
                className="flex items-center justify-between rounded-lg border border-muted/40 bg-surface p-4 transition-colors hover:border-accent/60"
              >
                <div>
                  <div className="font-semibold text-fg">{workout.name}</div>
                  <div className="text-sm text-fg/60">{formatDateShort(workout.date)}</div>
                </div>
                <div className="text-sm text-fg/60">
                  {workout.exercises.length}{" "}
                  {workout.exercises.length === 1 ? "ćwiczenie" : "ćwiczeń"}
                </div>
              </Link>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
