import Image from "next/image";
import Link from "next/link";
import { notFound } from "next/navigation";
import { CheckCircle2, CreditCard, ReceiptText, ShieldCheck } from "lucide-react";
import { createAdminClient } from "@/lib/supabase-admin";
import { mapPaymentLinkRecord, normalizeText, type PaymentLinkRecord } from "@/lib/payment-links";
import { getReadableTextColor } from "@/lib/color-contrast";

export const dynamic = "force-dynamic";
export const revalidate = 0;

type ProfileRow = {
  slug?: string | null;
  catalog_name?: string | null;
  store_name?: string | null;
  catalog_logo_url?: string | null;
  logo_url?: string | null;
  primary_color?: string | null;
  catalog_header_color?: string | null;
  catalog_header_text_color?: string | null;
};

type CompanyRow = {
  id?: string | null;
  owner_id?: string | null;
  name?: string | null;
};

function deriveLinkBrandValue(record: Record<string, unknown> | null | undefined, keys: string[]) {
  for (const key of keys) {
    const value = normalizeText(record?.[key]);
    if (value) return value;
  }
  return "";
}

function deriveProfileValue(rows: Array<ProfileRow | null | undefined>, keys: Array<keyof ProfileRow>) {
  for (const row of rows) {
    for (const key of keys) {
      const value = normalizeText(row?.[key]);
      if (value) return value;
    }
  }
  return "";
}

async function resolveAssetUrl(rawValue: string | null | undefined) {
  const value = normalizeText(rawValue);
  if (!value) return "";
  if (value.startsWith("data:")) return value;

  const parseStorageTarget = (input: string): { bucket: string; path: string } | null => {
    const normalized = input.replace(/^\/+/, "");

    if (/^https?:\/\//i.test(input)) {
      try {
        const parsed = new URL(input);
        const publicMarker = "/storage/v1/object/public/";
        const signMarker = "/storage/v1/object/sign/";
        const marker = parsed.pathname.includes(signMarker) ? signMarker : publicMarker;
        if (!parsed.pathname.includes(marker)) return null;
        const rest = parsed.pathname.slice(parsed.pathname.indexOf(marker) + marker.length);
        const [bucket, ...parts] = rest.split("/");
        return bucket && parts.length ? { bucket, path: parts.join("/") } : null;
      } catch {
        return null;
      }
    }

    const clean = normalized.replace(/^storage\/v1\/object\/public\//, "").replace(/^storage\/v1\/object\/sign\//, "");
    const [bucket, ...parts] = clean.split("/");
    return bucket && parts.length ? { bucket, path: parts.join("/") } : null;
  };

  const target = parseStorageTarget(value);
  if (!target) return value;

  try {
    const admin = createAdminClient();
    const { data: signedData, error: signedError } = await admin.storage
      .from(target.bucket)
      .createSignedUrl(target.path, 60 * 60 * 24 * 30);

    if (!signedError && signedData?.signedUrl) return signedData.signedUrl;

    const { data: publicData } = admin.storage.from(target.bucket).getPublicUrl(target.path);
    return publicData?.publicUrl || value;
  } catch {
    return value;
  }
}

function formatMoney(value: number | null | undefined, currency = "BRL") {
  return new Intl.NumberFormat("pt-BR", {
    style: "currency",
    currency: normalizeText(currency) || "BRL",
  }).format(Number(value || 0));
}

function formatDateTime(value: string | null | undefined) {
  if (!value) return "-";
  return new Intl.DateTimeFormat("pt-BR", {
    dateStyle: "short",
    timeStyle: "short",
  }).format(new Date(value));
}

function formatDocument(value: string | null | undefined) {
  const digits = normalizeText(value).replace(/\D/g, "");
  if (digits.length === 11) return digits.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, "$1.$2.$3-$4");
  if (digits.length === 14) return digits.replace(/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/, "$1.$2.$3/$4-$5");
  return normalizeText(value) || "-";
}

function getPaymentMethodLabel(method?: string | null) {
  switch (normalizeText(method).toLowerCase()) {
    case "pix":
      return "Pix";
    case "credit_card":
      return "Cartao de credito";
    case "debit_card":
      return "Cartao de debito";
    case "ticket":
      return "Boleto";
    default:
      return "Pagamento online";
  }
}

export default async function PaymentLinkSuccessPage(props: {
  params: Promise<{ code: string }> | { code: string };
  searchParams: Promise<{ paymentId?: string }> | { paymentId?: string };
}) {
  const params = await Promise.resolve(props.params as { code: string });
  const searchParams = await Promise.resolve(props.searchParams as { paymentId?: string });
  const code = normalizeText(params?.code).toUpperCase();
  const paymentId = normalizeText(searchParams?.paymentId);

  if (!code || !paymentId) notFound();

  const admin = createAdminClient();
  const [{ data: rawLink }, { data: payment }] = await Promise.all([
    admin.from("payment_links").select("*").eq("code", code).maybeSingle(),
    admin
      .from("payment_link_payments")
      .select(
        "id,payment_link_id,status,payment_method,provider_payment_id,amount,currency,approved_at,updated_at,payer_name,payer_email,payer_document"
      )
      .eq("id", paymentId)
      .maybeSingle(),
  ]);

  if (!rawLink || !payment?.id) notFound();

  const link = mapPaymentLinkRecord(rawLink as PaymentLinkRecord);
  if (payment.payment_link_id !== link.id) notFound();
  if (normalizeText(payment.status).toLowerCase() !== "approved") notFound();

  const linkRow = rawLink as PaymentLinkRecord;
  const { data: companyRow } = linkRow.company_id
    ? await admin.from("companies").select("id,owner_id,name").eq("id", linkRow.company_id).maybeSingle()
    : { data: null };

  const [{ data: profile }, { data: profileBySlug }, { data: profileByCompanyOwner }] = await Promise.all([
    admin.from("profiles").select("*").eq("id", link.userId).maybeSingle(),
    admin.from("profiles").select("*").eq("slug", link.slug).maybeSingle(),
    (companyRow as CompanyRow | null)?.owner_id
      ? admin.from("profiles").select("*").eq("id", (companyRow as CompanyRow).owner_id as string).maybeSingle()
      : Promise.resolve({ data: null }),
  ]);

  const metadataBrand = (link.metadata || {}) as Record<string, unknown>;
  const checkoutBrand = (link.checkoutConfig || {}) as Record<string, unknown>;
  const shareBrand = (link.shareConfig || {}) as Record<string, unknown>;

  const fallbackStoreName =
    deriveLinkBrandValue(metadataBrand, ["store_name", "catalog_name", "brand_name"]) ||
    deriveLinkBrandValue(checkoutBrand, ["store_name", "catalog_name", "brand_name"]) ||
    deriveLinkBrandValue(shareBrand, ["store_name", "catalog_name", "brand_name"]) ||
    normalizeText((companyRow as CompanyRow | null)?.name) ||
    normalizeText(link.slug).replace(/-/g, " ");

  const fallbackLogoUrl =
    deriveLinkBrandValue(metadataBrand, ["catalog_logo_url", "logo_url"]) ||
    deriveLinkBrandValue(checkoutBrand, ["catalog_logo_url", "logo_url"]) ||
    deriveLinkBrandValue(shareBrand, ["catalog_logo_url", "logo_url"]);

  const brandProfiles = [profileBySlug as ProfileRow | null, profile as ProfileRow | null, profileByCompanyOwner as ProfileRow | null];
  const storeName = deriveProfileValue(brandProfiles, ["catalog_name", "store_name"]) || fallbackStoreName || "Loja";
  const rawLogoUrl = deriveProfileValue(brandProfiles, ["catalog_logo_url", "logo_url"]) || fallbackLogoUrl;
  const logoUrl = await resolveAssetUrl(rawLogoUrl);
  const primaryColor = deriveProfileValue(brandProfiles, ["primary_color"]) || "#16a34a";
  const receiptReference = normalizeText(payment.provider_payment_id) || normalizeText(payment.id);
  const approvedAt = normalizeText(payment.approved_at) || normalizeText(payment.updated_at);
  const amount = Number(payment.amount || link.amount || 0);
  const currency = normalizeText(payment.currency) || link.currency || "BRL";

  return (
    <main className="min-h-screen bg-[linear-gradient(180deg,#f6fdf8_0%,#ffffff_48%,#f8fafc_100%)] px-4 py-8 sm:px-6 sm:py-10">
      <div className="mx-auto max-w-3xl">
        <div className="mb-5 flex justify-center">
          {logoUrl ? (
            <Image src={logoUrl} alt={storeName} width={180} height={52} className="h-10 w-auto object-contain" unoptimized />
          ) : (
            <div className="text-xl font-semibold text-slate-950">{storeName}</div>
          )}
        </div>

        <section className="overflow-hidden rounded-[28px] border border-emerald-100 bg-white shadow-[0_24px_80px_rgba(22,163,74,0.10)]">
          <div
            className="border-b border-emerald-100 px-6 py-7 text-center sm:px-10"
            style={{ background: `linear-gradient(135deg, ${primaryColor}18 0%, rgba(22,163,74,0.08) 100%)` }}
          >
            <div className="mx-auto flex h-20 w-20 items-center justify-center rounded-full bg-emerald-100 text-emerald-600 shadow-inner shadow-emerald-200/60">
              <CheckCircle2 className="h-10 w-10" />
            </div>
            <div className="mt-5 inline-flex items-center gap-2 rounded-full border border-emerald-200 bg-emerald-50 px-4 py-1 text-xs font-bold uppercase tracking-[0.2em] text-emerald-700">
              <ShieldCheck className="h-3.5 w-3.5" />
              Pagamento aprovado
            </div>
            <h1 className="mt-4 text-3xl font-semibold tracking-[-0.04em] text-slate-950 sm:text-4xl">
              Obrigado, recebemos seu pagamento
            </h1>
            <p className="mx-auto mt-3 max-w-2xl text-sm leading-6 text-slate-600 sm:text-[15px]">
              Seu pagamento foi confirmado com sucesso. Abaixo esta o comprovante desta transacao para consulta.
            </p>
          </div>

          <div className="space-y-6 px-6 py-6 sm:px-10 sm:py-8">
            <div className="grid gap-4 rounded-[24px] border border-slate-200 bg-slate-50 p-5 sm:grid-cols-[minmax(0,1fr)_220px] sm:p-6">
              <div>
                <div className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400">Comprovante</div>
                <div className="mt-2 text-[24px] font-semibold tracking-[-0.04em] text-slate-950">{link.title || "Pagamento online"}</div>
                <div className="mt-2 text-sm text-slate-500">Processado com seguranca por {storeName} via Mercado Pago.</div>
              </div>
              <div className="rounded-[20px] border border-emerald-200 bg-white px-5 py-4 text-left sm:text-right">
                <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-emerald-500">Valor pago</div>
                <div className="mt-2 text-[32px] font-semibold tracking-[-0.05em] text-emerald-600">{formatMoney(amount, currency)}</div>
              </div>
            </div>

            <div className="grid gap-4 md:grid-cols-2">
              <div className="rounded-[22px] border border-slate-200 bg-white p-5">
                <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Resumo da transacao</div>
                <div className="mt-4 space-y-4">
                  <div className="flex items-start justify-between gap-4">
                    <span className="text-sm text-slate-500">Meio de pagamento</span>
                    <span className="inline-flex items-center gap-2 text-sm font-semibold text-slate-900">
                      <CreditCard className="h-4 w-4 text-emerald-500" />
                      {getPaymentMethodLabel(payment.payment_method)}
                    </span>
                  </div>
                  <div className="flex items-start justify-between gap-4">
                    <span className="text-sm text-slate-500">Data da aprovacao</span>
                    <span className="text-sm font-semibold text-slate-900">{formatDateTime(approvedAt)}</span>
                  </div>
                  <div className="flex items-start justify-between gap-4">
                    <span className="text-sm text-slate-500">Codigo do pagamento</span>
                    <span className="max-w-[220px] break-all text-right text-sm font-semibold text-slate-900">{receiptReference}</span>
                  </div>
                  <div className="flex items-start justify-between gap-4">
                    <span className="text-sm text-slate-500">Link</span>
                    <span className="text-sm font-semibold text-slate-900">{link.code}</span>
                  </div>
                </div>
              </div>

              <div className="rounded-[22px] border border-slate-200 bg-white p-5">
                <div className="text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400">Pagador</div>
                <div className="mt-4 space-y-4">
                  <div className="flex items-start justify-between gap-4">
                    <span className="text-sm text-slate-500">Nome</span>
                    <span className="max-w-[220px] text-right text-sm font-semibold text-slate-900">
                      {normalizeText(payment.payer_name) || "Nao informado"}
                    </span>
                  </div>
                  <div className="flex items-start justify-between gap-4">
                    <span className="text-sm text-slate-500">E-mail</span>
                    <span className="max-w-[220px] break-all text-right text-sm font-semibold text-slate-900">
                      {normalizeText(payment.payer_email) || "Nao informado"}
                    </span>
                  </div>
                  <div className="flex items-start justify-between gap-4">
                    <span className="text-sm text-slate-500">Documento</span>
                    <span className="text-sm font-semibold text-slate-900">{formatDocument(payment.payer_document)}</span>
                  </div>
                </div>
              </div>
            </div>

            <div className="rounded-[22px] border border-dashed border-emerald-200 bg-emerald-50/70 px-5 py-4">
              <div className="flex items-start gap-3">
                <ReceiptText className="mt-0.5 h-5 w-5 text-emerald-600" />
                <div>
                  <div className="text-sm font-semibold text-emerald-900">Pagamento confirmado com sucesso</div>
                  <div className="mt-1 text-sm leading-6 text-emerald-800/90">
                    Guarde este comprovante para sua referencia. Se precisar, voce pode compartilhar este codigo de pagamento com a loja.
                  </div>
                </div>
              </div>
            </div>

            <div className="flex flex-col justify-center gap-3 pt-2 sm:flex-row">
              <Link
                href={`/lp/${encodeURIComponent(link.code)}`}
                className="inline-flex h-12 items-center justify-center rounded-full border border-slate-200 bg-white px-6 text-sm font-semibold text-slate-700 transition hover:border-slate-300 hover:bg-slate-50"
              >
                Voltar ao link
              </Link>
              <Link
                href={`/lp/${encodeURIComponent(link.code)}`}
                className="inline-flex h-12 items-center justify-center rounded-full px-6 text-sm font-semibold text-white shadow-sm transition hover:opacity-95"
                style={{ backgroundColor: primaryColor, color: getReadableTextColor(primaryColor) }}
              >
                Fechar comprovante
              </Link>
            </div>
          </div>
        </section>
      </div>
    </main>
  );
}
