import { notFound, redirect } from 'next/navigation';
import Link from 'next/link';
import { ChevronLeft } from 'lucide-react';
import { getCurrentUser } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import { getProgramById, computeTodaysSessionForProgram } from '@/lib/db/programs';
import ProgramEditor, {
  type DraftProgram,
} from '@/components/programs/ProgramEditor';
import ProgramActions from '@/components/programs/ProgramActions';
import StartSessionButton from '@/components/programs/StartSessionButton';

export const dynamic = 'force-dynamic';

const DAY_LABELS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

export default async function ProgramDetailPage({
  params,
}: {
  params: { id: string };
}) {
  const user = await getCurrentUser();
  if (!user) redirect('/auth/login');

  const program = await getProgramById(user.id, params.id);
  if (!program) notFound();

  const exercises = await prisma.exercise.findMany({
    where: { userId: user.id },
    select: { id: true, name: true, type: true },
    orderBy: [{ type: 'asc' }, { name: 'asc' }],
  });

  const todaysSession = program.isActive
    ? computeTodaysSessionForProgram(program, new Date())
    : null;

  const draft: DraftProgram = {
    name: program.name,
    description: program.description,
    type: program.type,
    durationWeeks: program.durationWeeks,
    startDate: program.startDate.toISOString().slice(0, 10),
    isActive: program.isActive,
    weeks: program.weeks.map((w) => ({
      weekNumber: w.weekNumber,
      phase: w.phase,
      description: w.description,
      days: w.days.map((d) => ({
        dayOfWeek: d.dayOfWeek,
        name: d.name,
        description: d.description,
        exercises: d.exercises.map((ex) => ({
          exerciseId: ex.exerciseId,
          order: ex.order,
          sets: ex.sets,
          repsMin: ex.repsMin,
          repsMax: ex.repsMax,
          rpe: ex.rpe,
          restSeconds: ex.restSeconds,
          notes: ex.notes,
        })),
      })),
    })),
  };

  return (
    <div className="min-h-screen bg-[#0A0A0A]">
      <div className="border-b border-zinc-800">
        <div className="max-w-3xl mx-auto px-4 py-4 sm:py-6 flex items-center justify-between gap-3">
          <div className="flex items-center gap-3 min-w-0">
            <Link
              href="/main/programs"
              className="text-zinc-400 hover:text-white"
              aria-label="Back to programs"
            >
              <ChevronLeft className="w-5 h-5" />
            </Link>
            <h1 className="text-xl sm:text-2xl font-bold text-white truncate">
              {program.name}
              {program.isActive && (
                <span className="ml-2 text-[10px] uppercase tracking-wider bg-emerald-900/50 text-emerald-300 px-2 py-0.5 rounded font-normal">
                  active
                </span>
              )}
            </h1>
          </div>
          <ProgramActions programId={program.id} />
        </div>
      </div>

      <div className="max-w-3xl mx-auto px-4 py-6 space-y-6">
        {todaysSession?.day && (
          <section className="bg-emerald-950/30 border border-emerald-900 rounded p-4">
            <p className="text-[11px] uppercase tracking-wider text-emerald-400">
              Today · Week {todaysSession.weekNumber} ·{' '}
              {DAY_LABELS[todaysSession.dayOfWeek]}
            </p>
            <h2 className="text-lg font-bold text-white mt-1">
              {todaysSession.day.name ??
                `${DAY_LABELS[todaysSession.dayOfWeek]} session`}
            </h2>
            <ul className="mt-2 space-y-1 text-sm text-zinc-300">
              {todaysSession.day.exercises.map((ex) => (
                <li key={ex.id}>
                  {ex.exercise.name}
                  {ex.sets && (
                    <span className="text-zinc-500">
                      {' '}
                      · {ex.sets}×
                      {ex.repsMin === ex.repsMax || !ex.repsMax
                        ? (ex.repsMin ?? '?')
                        : `${ex.repsMin}-${ex.repsMax}`}
                      {ex.rpe ? ` @ RPE ${ex.rpe}` : ''}
                    </span>
                  )}
                </li>
              ))}
            </ul>
            <StartSessionButton
              programId={program.id}
              dayId={todaysSession.day.id}
            />
          </section>
        )}

        <ProgramEditor
          initialProgram={draft}
          programId={program.id}
          exercises={exercises}
        />
      </div>
    </div>
  );
}
