import { redirect } from "next/navigation";

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

export default async function ConnectTenantChannelPage({
  params,
  searchParams
}: {
  params: Promise<{ tenantId: string }>;
  searchParams?: Promise<{ error?: string }>;
}) {
  const session = await getSession();
  if (!session || session.role !== "super_admin") {
    redirect("/unauthorized");
  }

  const { tenantId } = await params;
  const [tenant, errorResult] = await Promise.all([
    prisma.tenant.findUnique({ where: { id: tenantId }, select: { id: true, name: true } }),
    searchParams ?? Promise.resolve({ error: undefined })
  ]);

  if (!tenant) {
    redirect("/super-admin/tenants?error=tenant_not_found");
  }

  const error = errorResult.error;
  const errorMessage =
    error === "missing_fields"
      ? "Semua field wajib diisi."
      : error === "tenant_not_found"
        ? "Tenant tidak ditemukan."
        : error === "invalid_status"
          ? "Status channel tidak valid."
          : null;

  return (
    <ShellPage shell="super-admin" title="Connect Channel" description={`Hubungkan WABA ID, phone number ID, dan webhook config ke ${tenant.name}.`}>
      <SectionCard title="Channel form">
        <form action={connectTenantChannel} className="grid gap-4 md:max-w-3xl">
          <input type="hidden" name="tenantId" value={tenant.id} />
          {errorMessage ? <p className="rounded-xl border border-warning/30 bg-warning/10 p-3 text-sm text-warning">{errorMessage}</p> : null}
          <input name="provider" className="rounded-xl border border-line px-4 py-3" placeholder="Provider" required />
          <input name="channelName" className="rounded-xl border border-line px-4 py-3" placeholder="Channel name" required />
          <input name="wabaId" className="rounded-xl border border-line px-4 py-3" placeholder="WABA ID" required />
          <input name="phoneNumberId" className="rounded-xl border border-line px-4 py-3" placeholder="Phone Number ID" required />
          <input name="displayPhoneNumber" className="rounded-xl border border-line px-4 py-3" placeholder="Display Number" required />
          <label className="text-sm text-on-surface-variant">
            <span>Status awal</span>
            <select name="status" defaultValue={ChannelStatus.PENDING} className="mt-2 w-full rounded-xl border border-line px-4 py-3">
              {Object.values(ChannelStatus).map((status) => (
                <option key={status} value={status}>
                  {status}
                </option>
              ))}
            </select>
          </label>
          <div className="flex gap-3">
            <Button type="submit">Save channel</Button>
            <Button href={`/super-admin/tenants/${tenant.id}`} variant="secondary">
              Back
            </Button>
          </div>
        </form>
      </SectionCard>
    </ShellPage>
  );
}
