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 TemplatesList from '@/components/ai/TemplatesList';

export const dynamic = 'force-dynamic';

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

  const templates = await prisma.aIPromptTemplate.findMany({
    where: { OR: [{ userId: null }, { userId: user.id }] },
    orderBy: [{ isBuiltIn: 'desc' }, { name: 'asc' }],
  });

  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/ai"
            className="text-zinc-400 hover:text-white"
          >
            <ChevronLeft className="w-5 h-5" />
          </Link>
          <h1 className="text-2xl sm:text-3xl font-bold text-white">
            AI · Prompt templates
          </h1>
        </div>
      </div>
      <div className="max-w-3xl mx-auto px-4 py-6">
        <TemplatesList
          initialTemplates={templates.map((t) => ({
            id: t.id,
            name: t.name,
            description: t.description,
            systemPrompt: t.systemPrompt,
            userPromptTemplate: t.userPromptTemplate,
            isBuiltIn: t.isBuiltIn,
            isMine: t.userId === user.id,
          }))}
          isAdmin={user.isAdmin}
        />
      </div>
    </div>
  );
}
