import { 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 GenerateClient from '@/components/ai/GenerateClient';

export const dynamic = 'force-dynamic';

export default async function GeneratePage() {
  const user = await getCurrentUser();
  if (!user) redirect('/auth/login');

  const [templates, exercises, prefs, workoutCount] = await Promise.all([
    prisma.aIPromptTemplate.findMany({
      where: { OR: [{ userId: null }, { userId: user.id }] },
      orderBy: [{ isBuiltIn: 'desc' }, { name: 'asc' }],
      select: {
        id: true,
        name: true,
        description: true,
        isBuiltIn: true,
      },
    }),
    prisma.exercise.findMany({
      where: { userId: user.id },
      select: { id: true, name: true, type: true },
      orderBy: [{ type: 'asc' }, { name: 'asc' }],
    }),
    prisma.userPreferences.findUnique({
      where: { userId: user.id },
      select: { aiProvider: true, aiModel: true },
    }),
    prisma.workout.count({
      where: { userId: user.id, deletedAt: null },
    }),
  ]);

  const aiConfigured = !!prefs?.aiProvider && !!prefs?.aiModel;

  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 gap-3">
          <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-2xl sm:text-3xl font-bold text-white">
            AI · Generate program
          </h1>
        </div>
      </div>
      <div className="max-w-3xl mx-auto px-4 py-6">
        {!aiConfigured ? (
          <div className="bg-amber-950/30 border border-amber-900 rounded p-5 text-sm text-amber-200">
            <p className="font-bold text-amber-100 mb-2">
              AI is not configured.
            </p>
            <p>
              Pick a provider, model, and (if needed) API key in{' '}
              <Link
                href="/main/settings"
                className="underline hover:text-amber-100"
              >
                Settings → AI integration
              </Link>{' '}
              before you can generate programs.
            </p>
          </div>
        ) : (
          <GenerateClient
            templates={templates}
            exercises={exercises}
            providerLabel={prefs!.aiProvider!}
            modelLabel={prefs!.aiModel!}
            workoutCount={workoutCount}
          />
        )}
      </div>
    </div>
  );
}
