import Link from "next/link";
import { redirect } from "next/navigation";

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

export default async function EditTemplatePage({ params }: { params: Promise<{ templateId: string }> }) {
  const { templateId } = await params;
  const session = await getSession();
  if (!session) {
    redirect("/login");
  }

  const template = await prisma.messageTemplate.findFirst({
    where: { id: templateId, tenantId: session.tenantId }
  });
  if (!template) {
    redirect("/templates?error=template_not_found");
  }

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

  return (
    <ShellPage shell="admin" title="Edit Template" description="Resubmit template yang ditolak atau update draft.">
      <SectionCard title="Template form">
        <form action={updateTemplate} className="grid gap-4 md:max-w-3xl">
          <input type="hidden" name="templateId" value={template.id} />
          <input name="name" required defaultValue={template.name} className="rounded-xl border border-line px-4 py-3" />
          <input name="category" required defaultValue={template.category} className="rounded-xl border border-line px-4 py-3" />
          <input
            name="languageCode"
            required
            defaultValue={template.languageCode}
            className="rounded-xl border border-line px-4 py-3"
          />
          <label className="md:col-span-2 block text-sm">
            <span className="text-on-surface-variant">Channel</span>
            <select name="channelId" defaultValue={template.channelId} className="mt-2 w-full rounded-xl border border-line px-4 py-3">
              {channels.map((channel) => (
                <option key={channel.id} value={channel.id}>
                  {channel.channelName}
                </option>
              ))}
            </select>
          </label>
          <textarea
            required
            name="bodyText"
            className="min-h-32 rounded-xl border border-line px-4 py-3"
            defaultValue={template.bodyText}
          />
          <div className="md:col-span-2 flex gap-3">
            <Button type="submit" className="rounded-xl">
              Save template
            </Button>
            <Link href={`/templates/${template.id}`} className="text-on-surface-variant hover:underline">
              Cancel
            </Link>
          </div>
        </form>
      </SectionCard>
    </ShellPage>
  );
}
