import { redirect } from "next/navigation";

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

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

  const params = await (searchParams ?? Promise.resolve<{ error?: string }>({}));
  const error = params.error;
  const errorMessage = error === "missing_fields" ? "Nama segment wajib diisi." : null;

  return (
    <ShellPage shell="admin" title="Create Segment" description="Rule builder sederhana untuk audience segmentation.">
      <SectionCard title="Segment rule">
        <form action={createContactSegment} className="grid gap-4 md:max-w-2xl">
          {errorMessage ? (
            <p className="rounded-xl border border-warning/30 bg-warning/10 p-3 text-sm text-warning">{errorMessage}</p>
          ) : null}
          <input name="name" required className="rounded-xl border border-line px-4 py-3" placeholder="Segment name" />
          <label className="text-sm text-on-surface-variant">
            <span>Rules JSON / human-readable rules</span>
            <textarea
              name="rules"
              className="mt-2 min-h-32 w-full rounded-xl border border-line px-4 py-3"
              placeholder='Contoh: {"tags":["Enterprise"]} atau tulis deskripsi aturan di sini'
            />
          </label>
          <div>
            <Button type="submit">Save segment</Button>
          </div>
        </form>
      </SectionCard>
    </ShellPage>
  );
}
