import Link from "next/link";
import SystemNoticeFormClient from "@/app/tarjas-informativas/form-client";
import { createAdminClient } from "@/lib/supabase-admin";

type PageProps = { params: Promise<{ id: string }> };

type SystemNoticeRow = {
  id: string;
  scope: string;
  title: string | null;
  message: string;
  variant: string;
  dismiss_mode: string;
  active: boolean;
  position: number;
  start_at: string | null;
  end_at: string | null;
  show_on_paths: string[] | null;
  hide_on_paths: string[] | null;
  theme: Record<string, unknown> | null;
};

export default async function EditSystemNoticePage({ params }: PageProps) {
  const { id } = await params;
  const admin = createAdminClient();
  const { data } = await admin
    .from("system_notices")
    .select("id,scope,title,message,variant,dismiss_mode,active,position,start_at,end_at,show_on_paths,hide_on_paths,theme")
    .eq("id", id)
    .maybeSingle();

  const row = data as SystemNoticeRow | null;
  if (!row) {
    return (
      <div className="min-h-screen bg-slate-50/50 p-6 sm:p-10 font-sans">
        <div className="mx-auto max-w-[880px] rounded-2xl border border-slate-200 bg-white p-8 shadow-sm">
          <h1 className="text-xl font-semibold text-slate-900">Tarja não encontrada</h1>
          <p className="mt-2 text-sm text-slate-500">O item pode ter sido removido ou o ID está incorreto.</p>
          <div className="mt-6">
            <Link
              href="/tarjas-informativas"
              className="inline-flex h-11 items-center justify-center rounded-xl bg-slate-900 px-5 text-sm font-semibold text-white shadow-sm transition hover:bg-slate-800"
            >
              Voltar para listagem
            </Link>
          </div>
        </div>
      </div>
    );
  }

  return (
    <SystemNoticeFormClient
      mode="edit"
      initial={{
        ...row,
        theme: (row.theme || {}) as Record<string, unknown>,
      }}
    />
  );
}
