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 { updateContact } from "@/lib/admin-crud";
import { prisma } from "@/lib/prisma";

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

  const contact = await prisma.contact.findFirst({
    where: { id: contactId, tenantId: session.tenantId },
    include: { contactTags: { include: { tag: true } }, channel: true }
  });
  if (!contact) {
    redirect("/contacts?error=contact_not_found");
  }

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

  const tags = contact.contactTags.map((item) => item.tag.name).join(", ");

  return (
    <ShellPage shell="admin" title="Edit Contact" description="Form update data contact.">
      <SectionCard title="Contact form">
        <form action={updateContact} className="grid gap-4 md:max-w-2xl md:grid-cols-2">
          <input type="hidden" name="contactId" value={contact.id} />
          <input required name="fullName" defaultValue={contact.fullName} className="rounded-xl border border-line px-4 py-3" />
          <input
            required
            name="phoneNumber"
            defaultValue={contact.phoneNumber}
            className="rounded-xl border border-line px-4 py-3"
          />
          <input name="email" defaultValue={contact.email ?? ""} className="rounded-xl border border-line px-4 py-3" />
          <input
            name="countryCode"
            defaultValue={contact.countryCode ?? ""}
            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={contact.channelId || ""} className="mt-2 w-full rounded-xl border border-line px-4 py-3">
              <option value="">Tidak terkait 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">Tags</span>
            <input name="tags" defaultValue={tags} className="mt-2 w-full rounded-xl border border-line px-4 py-3" />
          </label>
          <label className="md:col-span-2 block text-sm">
            <span className="text-on-surface-variant">Opt-in status</span>
            <select
              name="optInStatus"
              defaultValue={contact.optInStatus}
              className="mt-2 w-full rounded-xl border border-line px-4 py-3"
            >
              <option value="UNKNOWN">Unknown</option>
              <option value="OPTED_IN">Opted in</option>
              <option value="OPTED_OUT">Opted out</option>
            </select>
          </label>
          <div className="md:col-span-2 flex gap-3">
            <Button type="submit" className="rounded-xl">
              Save changes
            </Button>
            <Link href={`/contacts/${contact.id}`} className="text-on-surface-variant hover:underline">
              Cancel
            </Link>
          </div>
        </form>
      </SectionCard>
    </ShellPage>
  );
}
