import { redirect } from "next/navigation";

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

export default async function NewCampaignPage({
  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 templates = await prisma.messageTemplate.findMany({ where: { tenantId: session.tenantId }, orderBy: { createdAt: "desc" } });
  const segments = await prisma.contactSegment.findMany({ where: { tenantId: session.tenantId }, orderBy: { name: "asc" } });

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

  return (
    <ShellPage shell="admin" title="Create Campaign" description="Stepper metadata, template, audience, dan scheduling.">
      <SectionCard title="Campaign setup">
        <form action={createCampaign} 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">{errorMessage}</p> : null}
          <input required name="name" className="rounded-xl border border-line px-4 py-3" placeholder="Campaign name" />
          <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</span>
            <select name="templateId" required className="mt-2 w-full rounded-xl border border-line px-4 py-3">
              <option value="">Pilih template</option>
              {templates.map((template) => (
                <option key={template.id} value={template.id}>
                  {template.name}
                </option>
              ))}
            </select>
          </label>
          <label className="md:col-span-2 block text-sm">
            <span className="text-on-surface-variant">Audience</span>
            <select name="audienceType" required defaultValue={CampaignAudienceType.MANUAL} className="mt-2 w-full rounded-xl border border-line px-4 py-3">
              <option value={CampaignAudienceType.SEGMENT}>Segment</option>
              <option value={CampaignAudienceType.IMPORT}>Import</option>
              <option value={CampaignAudienceType.MANUAL}>Manual</option>
            </select>
          </label>
          <label className="md:col-span-2 block text-sm">
            <span className="text-on-surface-variant">Segment (hanya untuk audience segment)</span>
            <select name="segmentId" defaultValue="" className="mt-2 w-full rounded-xl border border-line px-4 py-3">
              <option value="">Pilih segment</option>
              {segments.map((segment) => (
                <option key={segment.id} value={segment.id}>
                  {segment.name}
                </option>
              ))}
            </select>
          </label>
          <label className="md:col-span-2 block text-sm">
            <span className="text-on-surface-variant">Scheduled at</span>
            <input name="scheduledAt" type="datetime-local" className="mt-2 w-full rounded-xl border border-line px-4 py-3" />
          </label>
          <Button type="submit" className="md:col-span-2 w-full">
            Create campaign
          </Button>
        </form>
      </SectionCard>
    </ShellPage>
  );
}
