import { NextResponse } from "next/server";
import { createClient } from "@/lib/supabase-server";
import { createAdminClient } from "@/lib/supabase-admin";
import { isOwnerUser } from "@/lib/owner-auth";

type ThemeConfig = {
  background?: string;
  text?: string;
  accent?: string;
  inline_icon?: string;
  watermark_icon?: string;
  cta_label?: string;
  cta_url?: string;
  cta_new_tab?: boolean;
};

function normalizeString(value: unknown) {
  return typeof value === "string" ? value.trim() : "";
}

function normalizeBoolean(value: unknown, fallback: boolean) {
  if (typeof value === "boolean") return value;
  return fallback;
}

function normalizeNumber(value: unknown, fallback: number) {
  const n = Number(value);
  return Number.isFinite(n) ? n : fallback;
}

function normalizeIsoDate(value: unknown) {
  const text = normalizeString(value);
  if (!text) return null;
  const parsed = new Date(text);
  if (Number.isNaN(parsed.getTime())) return null;
  return parsed.toISOString();
}

function normalizeScope(value: unknown) {
  const cleaned = normalizeString(value).toLowerCase();
  if (cleaned === "admin" || cleaned === "owner" || cleaned === "public" || cleaned === "all") return cleaned;
  return "all";
}

function normalizeVariant(value: unknown) {
  const cleaned = normalizeString(value).toLowerCase();
  if (cleaned === "info" || cleaned === "success" || cleaned === "warning" || cleaned === "danger") return cleaned;
  return "info";
}

function normalizeDismissMode(value: unknown) {
  const cleaned = normalizeString(value).toLowerCase();
  if (cleaned === "dismissible" || cleaned === "sticky" || cleaned === "session") return cleaned;
  return "dismissible";
}

function normalizeStringArray(value: unknown) {
  if (!Array.isArray(value)) return null;
  const items = value.map((v) => normalizeString(v)).filter(Boolean);
  return items.length ? items : null;
}

function normalizeTheme(value: unknown): ThemeConfig {
  if (!value || typeof value !== "object" || Array.isArray(value)) return {};
  const src = value as Record<string, unknown>;
  const background = normalizeString(src.background);
  const text = normalizeString(src.text);
  const accent = normalizeString(src.accent);
  const inline_icon = normalizeString(src.inline_icon);
  const watermark_icon = normalizeString(src.watermark_icon);
  const cta_label = normalizeString(src.cta_label);
  const cta_url = normalizeString(src.cta_url);
  const cta_new_tab = normalizeBoolean(src.cta_new_tab, false);
  return {
    ...(background ? { background } : {}),
    ...(text ? { text } : {}),
    ...(accent ? { accent } : {}),
    ...(inline_icon ? { inline_icon } : {}),
    ...(watermark_icon ? { watermark_icon } : {}),
    ...(cta_label ? { cta_label } : {}),
    ...(cta_url ? { cta_url } : {}),
    ...(cta_label && cta_url ? { cta_new_tab } : {}),
  };
}

function shouldShowOnPath(pathname: string, showOnPaths: string[] | null, hideOnPaths: string[] | null) {
  const clean = String(pathname || "/").trim() || "/";
  if (Array.isArray(hideOnPaths) && hideOnPaths.some((p) => p && clean.startsWith(p))) return false;
  if (Array.isArray(showOnPaths) && showOnPaths.length) return showOnPaths.some((p) => p && clean.startsWith(p));
  return true;
}

async function ensureOwner() {
  const supabase = await createClient();
  const {
    data: { user },
  } = await supabase.auth.getUser();

  if (!user || !isOwnerUser({ id: user.id, email: user.email })) {
    return { ok: false as const, status: 403, user: null };
  }

  return { ok: true as const, status: 200, user };
}

export async function GET(request: Request) {
  const auth = await ensureOwner();
  if (!auth.ok) return NextResponse.json({ error: "Sem permissão." }, { status: auth.status });

  const { searchParams } = new URL(request.url);
  const mode = normalizeString(searchParams.get("mode") || "");
  const scope = normalizeScope(searchParams.get("scope") || "owner");
  const pathname = normalizeString(searchParams.get("path") || "/");

  const admin = createAdminClient();
  const query = 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,created_at,updated_at")
    .order("position", { ascending: true })
    .order("created_at", { ascending: false });

  const { data, error } = await query;
  if (error) return NextResponse.json({ error: "Não foi possível carregar as tarjas." }, { status: 400 });

  const rows = Array.isArray(data) ? data : [];

  if (mode === "display") {
    const now = Date.now();
    const filtered = rows
      .filter((row) => Boolean(row?.active))
      .filter((row) => row.scope === "all" || row.scope === scope)
      .filter((row) => {
        const startAt = row.start_at ? new Date(row.start_at).getTime() : null;
        const endAt = row.end_at ? new Date(row.end_at).getTime() : null;
        if (startAt && Number.isFinite(startAt) && now < startAt) return false;
        if (endAt && Number.isFinite(endAt) && now > endAt) return false;
        return true;
      })
      .filter((row) => shouldShowOnPath(pathname, row.show_on_paths ?? null, row.hide_on_paths ?? null));

    return NextResponse.json({ ok: true, notices: filtered });
  }

  return NextResponse.json({ ok: true, notices: rows });
}

export async function POST(request: Request) {
  const auth = await ensureOwner();
  if (!auth.ok) return NextResponse.json({ error: "Sem permissão." }, { status: auth.status });

  const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
  const scope = normalizeScope(body?.scope);
  const title = normalizeString(body?.title) || null;
  const message = normalizeString(body?.message);
  const variant = normalizeVariant(body?.variant);
  const dismissMode = normalizeDismissMode(body?.dismiss_mode);
  const active = normalizeBoolean(body?.active, true);
  const position = normalizeNumber(body?.position, 0);
  const startAt = normalizeIsoDate(body?.start_at);
  const endAt = normalizeIsoDate(body?.end_at);
  const showOnPaths = normalizeStringArray(body?.show_on_paths);
  const hideOnPaths = normalizeStringArray(body?.hide_on_paths);
  const theme = normalizeTheme(body?.theme);

  if (!message) return NextResponse.json({ error: "Informe a mensagem." }, { status: 400 });

  const admin = createAdminClient();
  const now = new Date().toISOString();
  const { data, error } = await admin
    .from("system_notices")
    .insert({
      scope,
      title,
      message,
      variant,
      dismiss_mode: dismissMode,
      active,
      position,
      start_at: startAt,
      end_at: endAt,
      show_on_paths: showOnPaths,
      hide_on_paths: hideOnPaths,
      theme,
      created_at: now,
      updated_at: now,
    })
    .select("id")
    .single();

  if (error || !data?.id) return NextResponse.json({ error: "Não foi possível salvar a tarja." }, { status: 400 });
  return NextResponse.json({ ok: true, id: data.id });
}

export async function PATCH(request: Request) {
  const auth = await ensureOwner();
  if (!auth.ok) return NextResponse.json({ error: "Sem permissão." }, { status: auth.status });

  const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
  const id = normalizeString(body?.id);
  if (!id) return NextResponse.json({ error: "ID inválido." }, { status: 400 });

  const payload: Record<string, unknown> = { updated_at: new Date().toISOString() };

  if (body?.scope !== undefined) payload.scope = normalizeScope(body.scope);
  if (body?.title !== undefined) payload.title = normalizeString(body.title) || null;
  if (body?.message !== undefined) payload.message = normalizeString(body.message);
  if (body?.variant !== undefined) payload.variant = normalizeVariant(body.variant);
  if (body?.dismiss_mode !== undefined) payload.dismiss_mode = normalizeDismissMode(body.dismiss_mode);
  if (body?.active !== undefined) payload.active = normalizeBoolean(body.active, true);
  if (body?.position !== undefined) payload.position = normalizeNumber(body.position, 0);
  if (body?.start_at !== undefined) payload.start_at = normalizeIsoDate(body.start_at);
  if (body?.end_at !== undefined) payload.end_at = normalizeIsoDate(body.end_at);
  if (body?.show_on_paths !== undefined) payload.show_on_paths = normalizeStringArray(body.show_on_paths);
  if (body?.hide_on_paths !== undefined) payload.hide_on_paths = normalizeStringArray(body.hide_on_paths);
  if (body?.theme !== undefined) payload.theme = normalizeTheme(body.theme);

  if (payload.message !== undefined && !payload.message) {
    return NextResponse.json({ error: "Informe a mensagem." }, { status: 400 });
  }

  const admin = createAdminClient();
  const { error } = await admin.from("system_notices").update(payload).eq("id", id);
  if (error) return NextResponse.json({ error: "Não foi possível atualizar a tarja." }, { status: 400 });
  return NextResponse.json({ ok: true });
}

export async function DELETE(request: Request) {
  const auth = await ensureOwner();
  if (!auth.ok) return NextResponse.json({ error: "Sem permissão." }, { status: auth.status });

  const { searchParams } = new URL(request.url);
  const id = normalizeString(searchParams.get("id"));
  if (!id) return NextResponse.json({ error: "ID inválido." }, { status: 400 });

  const admin = createAdminClient();
  const { error } = await admin.from("system_notices").delete().eq("id", id);
  if (error) return NextResponse.json({ error: "Não foi possível deletar a tarja." }, { status: 400 });
  return NextResponse.json({ ok: true });
}
