import { redirect } from "next/navigation";

import { ShellPage } from "@/components/page-templates";
import { Button, SectionCard } from "@/components/ui";
import { getSession } from "@/lib/auth";
import { createTemplate } from "@/lib/admin-crud";
import { prisma } from "@/lib/prisma";

export default async function NewTemplatePage({
  searchParams
}: {
  searchParams?: Promise<{ error?: string }>; 
}) {
  const session = await getSession();
  if (!session) {
    redirect("/login");
  }

  const channels = await prisma.channel.findMany({
    where: { tenantId: session.tenantId },
    orderBy: { channelName: "asc" }
  });

  const params = await (searchParams ?? Promise.resolve({ error: undefined }));
  const errorMessage = params.error === "missing_fields" ? "Lengkapi semua kolom wajib." : params.error === "invalid_channel" ? "Channel tidak valid." : null;

  return (
    <ShellPage shell="admin" title="Create Template Request" description="Form request template WhatsApp.">
      <SectionCard title="Template builder">
        <form action={createTemplate} className="grid gap-4 md:max-w-3xl">
          {errorMessage ? (
            <p className="rounded-xl border border-warning/30 bg-warning/10 p-3 text-sm text-warning md:col-span-2">{errorMessage}</p>
          ) : null}
          <input required name="name" className="rounded-xl border border-line px-4 py-3" placeholder="Template name" />
          <input required name="category" className="rounded-xl border border-line px-4 py-3" placeholder="Category" />
          <input required name="languageCode" className="rounded-xl border border-line px-4 py-3" placeholder="Language code (id)" />
          <label className="md:col-span-2 block text-sm">
            <span className="text-on-surface-variant">Channel</span>
            <select name="channelId" required className="mt-2 w-full rounded-xl border border-line px-4 py-3">
              <option value="">Pilih channel</option>
              {channels.map((channel) => (
                <option key={channel.id} value={channel.id}>
                  {channel.channelName}
                </option>
              ))}
            </select>
          </label>
          <label className="md:col-span-2 block text-sm">
            <span className="text-on-surface-variant">Template type</span>
            <input name="templateType" defaultValue="text" className="mt-2 w-full rounded-xl border border-line px-4 py-3" />
          </label>
          <textarea required name="bodyText" className="min-h-32 rounded-xl border border-line px-4 py-3" placeholder="Body text" />
          <Button type="submit" className="md:col-span-2 w-full">
            Submit template
          </Button>
        </form>
      </SectionCard>
    </ShellPage>
  );
}
