"use client";

import { usePermissoes } from "@/lib/permissoes-do-usuario";
import CaixaDeConfirmacao, { type Confirmacao } from "@/components/ui/caixa-de-confirmacao";
import { useEffect, useMemo, useState } from "react";
import {
  Activity,
  ArrowDownUp,
  Search,
  Copy,
  Download,
  ExternalLink,
  Link2,
  Pause,
  Pencil,
  Play,
  Plus,
  RefreshCcw,
  Settings,
  Tag,
  Trash2,
  ChevronDown,
  X,
} from "lucide-react";
import { PageHeader } from "@/components/ui/page-header";
import { CustomSelect } from "@/components/ui/custom-select";
import { Input } from "@/components/ui/input";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Valor } from "@/components/ui/valor";

type PaymentLinkStatus = "draft" | "active" | "paused" | "archived";
type PaymentLinkType = "one_time" | "subscription";
type SortOption = "recent" | "oldest" | "highest" | "lowest";
type ModalTab = "general" | "details";

type ClientLookup = {
  id: string;
  name: string;
  company_name: string | null;
  email: string | null;
  document: string | null;
  phone: string | null;
  whatsapp: string | null;
};

type ProductLookup = {
  id: string;
  name: string;
  price: number;
  image_url: string | null;
  price_on_request: boolean;
};

type LinkItemDraft = {
  key: string;
  product_id: string;
  quantity: string;
};

type PaymentLink = {
  id: string;
  code: string;
  slug: string;
  status: PaymentLinkStatus;
  type: PaymentLinkType;
  title: string;
  description: string;
  amount: number;
  currency: string;
  image_url: string;
  interval_count: number | null;
  interval_unit: string | null;
  allow_credit_card: boolean;
  allow_pix: boolean;
  allow_boleto: boolean;
  checkout_config: Record<string, unknown>;
  share_config: Record<string, unknown>;
  metadata: Record<string, unknown>;
  last_paid_at: string | null;
  last_opened_at: string | null;
  expires_at: string | null;
  created_at: string;
  updated_at: string;
  public_url: string;
  active_subscription_count: number;
  pending_subscription_count: number;
  subscriptions_total: number;
};

type LinkFormState = {
  id: string | null;
  title: string;
  description: string;
  whatsapp_message: string;
  amount: string;
  client_id: string;
  items: LinkItemDraft[];
  show_cookie_banner: boolean;
  type: PaymentLinkType;
  status: PaymentLinkStatus;
  interval_count: string;
  interval_unit: "days" | "months" | "years";
  image_url: string;
  expires_at: string;
  allow_credit_card: boolean;
  allow_pix: boolean;
  allow_boleto: boolean;
};

const emptyForm: LinkFormState = {
  id: null,
  title: "",
  description: "",
  whatsapp_message: "",
  amount: "",
  client_id: "",
  items: [],
  show_cookie_banner: true,
  type: "one_time",
  status: "active",
  interval_count: "1",
  interval_unit: "months",
  image_url: "",
  expires_at: "",
  allow_credit_card: true,
  allow_pix: true,
  allow_boleto: false,
};

const fieldClass =
  "h-11 w-full border border-slate-200 bg-white px-3 text-sm text-slate-900 outline-none transition focus:border-violet-500";
const textareaClass =
  "min-h-[96px] w-full border border-slate-200 bg-white px-3 py-3 text-sm text-slate-900 outline-none transition focus:border-violet-500";

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

/* O dinheiro desta tela passa pelo <Valor>: quem nao tem a permissao de ver
   valores continua abrindo a tela e trabalhando, com os numeros borrados. */
const dinheiro = (v: number) => <Valor>{formatMoney(v)}</Valor>;

function WhatsAppIcon({ className = "" }: { className?: string }) {
  return (
    <svg viewBox="0 0 24 24" aria-hidden="true" className={className} fill="currentColor">
      <path d="M19.05 4.91A9.82 9.82 0 0 0 12.03 2C6.62 2 2.23 6.39 2.23 11.8c0 1.73.45 3.42 1.31 4.91L2.15 22l5.43-1.35a9.75 9.75 0 0 0 4.45 1.13h.01c5.4 0 9.79-4.39 9.8-9.8a9.72 9.72 0 0 0-2.79-7.07Zm-7.02 15.2h-.01a8.1 8.1 0 0 1-4.12-1.13l-.29-.17-3.22.8.86-3.14-.19-.32a8.1 8.1 0 0 1-1.24-4.34c0-4.48 3.64-8.13 8.13-8.13 2.17 0 4.22.85 5.75 2.39a8.07 8.07 0 0 1 2.38 5.75c0 4.48-3.65 8.13-8.05 8.13Zm4.46-6.08c-.24-.12-1.43-.7-1.66-.78-.22-.08-.39-.12-.55.12-.16.24-.63.78-.77.94-.14.16-.28.18-.52.06-.24-.12-1-.37-1.91-1.18-.7-.63-1.18-1.4-1.32-1.64-.14-.24-.01-.37.11-.49.11-.11.24-.28.37-.42.12-.14.16-.24.24-.4.08-.16.04-.3-.02-.42-.06-.12-.55-1.33-.76-1.82-.2-.48-.4-.41-.55-.42h-.47c-.16 0-.42.06-.64.3-.22.24-.84.82-.84 2s.86 2.32.98 2.48c.12.16 1.68 2.56 4.07 3.59.57.25 1.02.4 1.37.52.58.18 1.1.16 1.52.1.46-.07 1.43-.58 1.63-1.14.2-.56.2-1.04.14-1.14-.05-.1-.21-.16-.45-.28Z" />
    </svg>
  );
}

function formatDate(value: string | null) {
  if (!value) return "—";
  return new Date(value).toLocaleString("pt-BR", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

function statusLabel(status: PaymentLinkStatus) {
  if (status === "active") return "Ativo";
  if (status === "paused") return "Pausado";
  if (status === "archived") return "Arquivado";
  return "Rascunho";
}

function statusTone(status: PaymentLinkStatus) {
  if (status === "active") return "ks-chip ks-chip-success";
  if (status === "paused") return "ks-chip ks-chip-warning";
  if (status === "archived") return "ks-chip ks-chip-danger";
  return "ks-chip";
}

function typeLabel(type: PaymentLinkType) {
  return type === "subscription" ? "Assinatura" : "Produto único";
}

function recurrenceLabel(link: PaymentLink) {
  if (link.type !== "subscription" || !link.interval_count || !link.interval_unit) return "Pagamento único";
  if (link.interval_unit === "days") {
    return link.interval_count === 1 ? "Cobrança diária" : `A cada ${link.interval_count} dias`;
  }
  if (link.interval_unit === "years") {
    return link.interval_count === 1 ? "Cobrança anual" : `A cada ${link.interval_count} anos`;
  }
  return link.interval_count === 1 ? "Cobrança mensal" : `A cada ${link.interval_count} meses`;
}

function paymentMethodsLabel(link: PaymentLink) {
  if (link.type === "subscription") return "Cartão de crédito";
  const methods = [
    link.allow_credit_card ? "Cartão" : null,
    link.allow_pix ? "Pix" : null,
    link.allow_boleto ? "Boleto" : null,
  ].filter(Boolean);
  return methods.length ? methods.join(" · ") : "Cartão";
}

function toInputDateTimeLocal(value: string | null) {
  if (!value) return "";
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "";
  const pad = (input: number) => String(input).padStart(2, "0");
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
}

function toIsoOrNull(value: string) {
  return value ? new Date(value).toISOString() : null;
}

function randomKey() {
  return `${Date.now()}-${Math.random().toString(16).slice(2)}`;
}

function normalizeCheckoutConfig(value: unknown) {
  const config =
    value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : ({} as Record<string, unknown>);

  const client_id = typeof config.client_id === "string" ? config.client_id : "";
  const show_cookie_banner = typeof config.show_cookie_banner === "boolean" ? config.show_cookie_banner : true;
  const itemsRaw = Array.isArray(config.items) ? config.items : [];
  const items: LinkItemDraft[] = itemsRaw
    .map((item) => {
      const record = item && typeof item === "object" && !Array.isArray(item) ? (item as Record<string, unknown>) : null;
      const product_id = typeof record?.product_id === "string" ? record.product_id : "";
      const quantityValue = typeof record?.quantity === "number" ? record.quantity : Number(record?.quantity || 0);
      const quantity = Number.isFinite(quantityValue) && quantityValue > 0 ? String(Math.floor(quantityValue)) : "1";
      if (!product_id) return null;
      return { key: randomKey(), product_id, quantity };
    })
    .filter((item): item is LinkItemDraft => Boolean(item));

  return { client_id, items, show_cookie_banner };
}

function normalizeShareConfig(value: unknown) {
  const config =
    value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : ({} as Record<string, unknown>);
  const whatsapp_message = typeof config.whatsapp_message === "string" ? config.whatsapp_message : "";
  return { whatsapp_message };
}

function mapLinkToForm(link: PaymentLink): LinkFormState {
  const normalizedConfig = normalizeCheckoutConfig(link.checkout_config);
  const normalizedShare = normalizeShareConfig(link.share_config);
  return {
    id: link.id,
    title: link.title,
    description: link.description || "",
    whatsapp_message: normalizedShare.whatsapp_message,
    amount: String(link.amount || ""),
    client_id: normalizedConfig.client_id,
    items: normalizedConfig.items,
    show_cookie_banner: normalizedConfig.show_cookie_banner,
    type: link.type,
    status: link.status,
    interval_count: String(link.interval_count || 1),
    interval_unit:
      link.interval_unit === "days" || link.interval_unit === "years" ? link.interval_unit : "months",
    image_url: link.image_url || "",
    expires_at: toInputDateTimeLocal(link.expires_at),
    allow_credit_card: link.allow_credit_card,
    allow_pix: link.allow_pix,
    allow_boleto: link.allow_boleto,
  };
}

export default function PaymentLinksPage() {
  const { pode } = usePermissoes();
  const podeLancar = pode("financial.links.write");

  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [confirmacao, setConfirmacao] = useState<Confirmacao | null>(null);
  const [actioningId, setActioningId] = useState<string | null>(null);
  const [links, setLinks] = useState<PaymentLink[]>([]);
  const [clients, setClients] = useState<ClientLookup[]>([]);
  const [products, setProducts] = useState<ProductLookup[]>([]);
  const [lookupLoading, setLookupLoading] = useState(false);
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState<"all" | PaymentLinkStatus>("all");
  const [typeFilter, setTypeFilter] = useState<"all" | PaymentLinkType>("all");
  const [sortBy, setSortBy] = useState<SortOption>("recent");
  const [dialogOpen, setDialogOpen] = useState(false);
  const [modalTab, setModalTab] = useState<ModalTab>("general");
  const [form, setForm] = useState<LinkFormState>(emptyForm);
  const [feedback, setFeedback] = useState<{ type: "success" | "error"; text: string } | null>(null);
  const [productPickerId, setProductPickerId] = useState("");
  const [whatsDialogOpen, setWhatsDialogOpen] = useState(false);
  const [whatsTargetLink, setWhatsTargetLink] = useState<PaymentLink | null>(null);
  const [whatsNumber, setWhatsNumber] = useState("");
  const [whatsMessage, setWhatsMessage] = useState("");
  const [settingsSaving, setSettingsSaving] = useState(false);
  const [whatsTemplateDraft, setWhatsTemplateDraft] = useState("");
  const [settingsMenuOpen, setSettingsMenuOpen] = useState(false);
  const [whatsTemplateModalOpen, setWhatsTemplateModalOpen] = useState(false);
  const [isMobile, setIsMobile] = useState(false);

  useEffect(() => {
    const mq = window.matchMedia("(max-width: 767px)");
    const update = () => setIsMobile(mq.matches);
    update();
    mq.addEventListener("change", update);
    return () => mq.removeEventListener("change", update);
  }, []);

  async function loadLinks() {
    try {
      setLoading(true);
      const response = await fetch("/api/financial/payment-links", { cache: "no-store" });
      const payload = (await response.json().catch(() => null)) as
        | { error?: string; links?: PaymentLink[] }
        | null;

      if (!response.ok) {
        throw new Error(payload?.error || "Nao foi possivel carregar os links.");
      }

      const nextLinks = Array.isArray(payload?.links) ? payload.links : [];
      setLinks(nextLinks);
      setSelectedId((current) => {
        if (current && nextLinks.some((item) => item.id === current)) return current;
        return nextLinks[0]?.id || null;
      });
    } catch (error) {
      setFeedback({
        type: "error",
        text: error instanceof Error ? error.message : "Nao foi possivel carregar os links.",
      });
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    void loadLinks();
  }, []);

  async function loadLookups() {
    try {
      if (lookupLoading) return;
      setLookupLoading(true);
      const [clientsRes, productsRes] = await Promise.all([
        fetch("/api/financial/payment-links?lookup=clients", { cache: "no-store" }),
        fetch("/api/financial/payment-links?lookup=products", { cache: "no-store" }),
      ]);
      const clientsPayload = (await clientsRes.json().catch(() => null)) as { error?: string; clients?: ClientLookup[] } | null;
      const productsPayload = (await productsRes.json().catch(() => null)) as { error?: string; products?: ProductLookup[] } | null;

      if (clientsRes.ok) setClients(Array.isArray(clientsPayload?.clients) ? clientsPayload!.clients! : []);
      if (productsRes.ok) setProducts(Array.isArray(productsPayload?.products) ? productsPayload!.products! : []);
    } finally {
      setLookupLoading(false);
    }
  }

  useEffect(() => {
    if (!dialogOpen) return;
    void loadLookups();
  }, [dialogOpen]);

  useEffect(() => {
    if (!selectedId) return;
    if (clients.length > 0 && products.length > 0) return;
    void loadLookups();
  }, [clients.length, products.length, selectedId]);

  const productsById = useMemo(() => new Map(products.map((product) => [product.id, product])), [products]);
  const clientOptions = useMemo(() => {
    return [
      { value: "", label: "Nenhum cliente" },
      ...clients.map((client) => ({
        value: client.id,
        label: client.company_name ? `${client.company_name} · ${client.name}` : client.name,
        selected_label: client.company_name ? `${client.company_name} · ${client.name}` : client.name,
        description: client.email || client.phone || undefined,
      })),
    ];
  }, [clients]);
  const productOptions = useMemo(() => {
    return [
      { value: "", label: "Selecione um produto" },
      ...products.map((product) => ({
        value: product.id,
        label: `${product.name} - ${product.price_on_request ? "Sob consulta" : formatMoney(product.price || 0)}`,
        selected_label: product.name,
        image_url: product.image_url,
      })),
    ];
  }, [products]);

  useEffect(() => {
    if (!dialogOpen) return;
    if (form.type !== "one_time") return;
    if (form.items.length === 0) return;
    const total = form.items.reduce((sum, item) => {
      const product = productsById.get(item.product_id);
      const qty = Math.max(1, Math.floor(Number(item.quantity || 0) || 1));
      const unit = product && !product.price_on_request ? product.price : 0;
      return sum + unit * qty;
    }, 0);
    const nextAmount = total > 0 ? String(Number(total.toFixed(2))) : form.amount;
    if (nextAmount !== form.amount) {
      setForm((current) => ({ ...current, amount: nextAmount }));
    }
  }, [dialogOpen, form.amount, form.items, form.type, productsById]);

  const filteredLinks = useMemo(() => {
    const normalizedSearch = search.trim().toLowerCase();
    const next = links.filter((link) => {
      const matchesSearch =
        !normalizedSearch ||
        link.title.toLowerCase().includes(normalizedSearch) ||
        link.code.toLowerCase().includes(normalizedSearch) ||
        link.description.toLowerCase().includes(normalizedSearch);
      const matchesStatus = statusFilter === "all" || link.status === statusFilter;
      const matchesType = typeFilter === "all" || link.type === typeFilter;
      return matchesSearch && matchesStatus && matchesType;
    });

    return next.sort((a, b) => {
      if (sortBy === "oldest") return new Date(a.created_at).getTime() - new Date(b.created_at).getTime();
      if (sortBy === "highest") return b.amount - a.amount;
      if (sortBy === "lowest") return a.amount - b.amount;
      return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
    });
  }, [links, search, sortBy, statusFilter, typeFilter]);

  const selectedLink = useMemo(
    () => filteredLinks.find((item) => item.id === selectedId) || links.find((item) => item.id === selectedId) || null,
    [filteredLinks, links, selectedId]
  );

  useEffect(() => {
    if (!selectedLink) return;
    setWhatsTemplateDraft(extractWhatsAppMessageFromLink(selectedLink));
    setSettingsMenuOpen(false);
    setWhatsTemplateModalOpen(false);
  }, [selectedLink?.id]);

  function formatClientName(client: ClientLookup | null) {
    if (!client) return "";
    const name = String(client.name || "").trim();
    const company = String(client.company_name || "").trim();
    if (name && company && name.toLowerCase() !== company.toLowerCase()) return `${name} (${company})`;
    return name || company;
  }

  function extractClientIdFromLink(link: PaymentLink) {
    const cfg = link.checkout_config && typeof link.checkout_config === "object" && !Array.isArray(link.checkout_config) ? link.checkout_config : {};
    const value = typeof (cfg as any).client_id === "string" ? String((cfg as any).client_id || "") : "";
    return value.trim();
  }

  function extractWhatsAppMessageFromLink(link: PaymentLink) {
    const cfg = link.share_config && typeof link.share_config === "object" && !Array.isArray(link.share_config) ? link.share_config : {};
    const value = typeof (cfg as any).whatsapp_message === "string" ? String((cfg as any).whatsapp_message || "") : "";
    return value.trim();
  }

  function normalizePhoneDigits(input: string) {
    const digits = String(input || "").replace(/\D/g, "");
    if (!digits) return "";
    if (digits.startsWith("55")) return digits;
    if (digits.length === 10 || digits.length === 11) return `55${digits}`;
    return digits;
  }

  function applyTemplate(template: string, data: Record<string, string>) {
    let output = template;
    for (const [key, value] of Object.entries(data)) {
      output = output.replaceAll(`{${key}}`, value);
    }
    return output;
  }

  function buildWhatsAppText(link: PaymentLink, client: ClientLookup | null) {
    const template =
      extractWhatsAppMessageFromLink(link) ||
      "Olá{cliente_saudaçao}! Segue seu link de pagamento: {link}\n\n{titulo}\nValor: {valor}";
    const clientName = formatClientName(client);
    const clientGreeting = clientName ? `, ${clientName}` : "";
    return applyTemplate(template, {
      link: link.public_url,
      titulo: link.title,
      valor: formatMoney(link.amount),
      codigo: link.code,
      cliente: clientName,
      cliente_saudaçao: clientGreeting,
      loja: link.slug,
    }).trim();
  }

  function openWhatsApp(link: PaymentLink, explicitNumber: string) {
    const clientId = extractClientIdFromLink(link);
    const client = clientId ? clients.find((item) => item.id === clientId) || null : null;
    const digits = normalizePhoneDigits(explicitNumber);
    const text = buildWhatsAppText(link, client);
    const url = `https://wa.me/${encodeURIComponent(digits)}?text=${encodeURIComponent(text)}`;
    window.open(url, "_blank", "noopener,noreferrer");
  }

  async function handleWhatsAppClick(link: PaymentLink) {
    if (!clients.length) {
      await loadLookups();
    }
    const clientId = extractClientIdFromLink(link);
    const client = clientId ? clients.find((item) => item.id === clientId) || null : null;
    const directDigits = normalizePhoneDigits(String(client?.whatsapp || ""));
    if (directDigits) {
      openWhatsApp(link, directDigits);
      return;
    }
    setWhatsTargetLink(link);
    setWhatsNumber(normalizePhoneDigits(String(client?.phone || "")));
    setWhatsMessage(buildWhatsAppText(link, client));
    setWhatsDialogOpen(true);
  }

  function closeWhatsAppDialog() {
    setWhatsDialogOpen(false);
    setWhatsTargetLink(null);
    setWhatsNumber("");
    setWhatsMessage("");
  }

  function handleSelectLink(linkId: string) {
    setSelectedId((current) => {
      if (isMobile) {
        return current === linkId ? null : linkId;
      }
      return linkId;
    });
  }

  async function handleSaveLinkSettings() {
    if (!selectedLink) return;
    try {
      if (settingsSaving) return;
      setSettingsSaving(true);
      setFeedback(null);

      const checkoutConfig = normalizeCheckoutConfig(selectedLink.checkout_config);
      const normalizedItems = checkoutConfig.items
        .map((item) => ({
          product_id: String(item.product_id || ""),
          quantity: Math.max(1, Math.floor(Number(item.quantity || 0) || 1)),
        }))
        .filter((item) => item.product_id);

      const response = await fetch("/api/financial/payment-links", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          id: selectedLink.id,
          title: selectedLink.title,
          description: selectedLink.description,
          amount: selectedLink.amount,
          type: selectedLink.type,
          status: selectedLink.status,
          expires_at: selectedLink.expires_at,
          interval_count: selectedLink.interval_count,
          interval_unit: selectedLink.interval_unit,
          image_url: selectedLink.image_url,
          allow_credit_card: selectedLink.allow_credit_card,
          allow_pix: selectedLink.allow_pix,
          allow_boleto: selectedLink.allow_boleto,
          checkout_config: {
            client_id: checkoutConfig.client_id || null,
            items: normalizedItems,
            show_cookie_banner: Boolean(checkoutConfig.show_cookie_banner),
          },
          share_config: {
            whatsapp_message: String(whatsTemplateDraft || "").trim() || null,
          },
          metadata: selectedLink.metadata || null,
        }),
      });

      const result = (await response.json().catch(() => null)) as { error?: string } | null;
      if (!response.ok) {
        throw new Error(result?.error || "Nao foi possivel salvar as configuracoes do link.");
      }

      setFeedback({ type: "success", text: "Configurações do link atualizadas." });
      await loadLinks();
      setWhatsTemplateModalOpen(false);
    } catch (error) {
      setFeedback({
        type: "error",
        text: error instanceof Error ? error.message : "Nao foi possivel salvar as configuracoes do link.",
      });
    } finally {
      setSettingsSaving(false);
    }
  }

  function openCreateDialog() {
    setForm(emptyForm);
    setModalTab("general");
    setDialogOpen(true);
  }

  function openEditDialog(link: PaymentLink) {
    setForm(mapLinkToForm(link));
    setModalTab("general");
    setDialogOpen(true);
  }

  function closeDialog() {
    if (saving) return;
    setDialogOpen(false);
    setModalTab("general");
    setForm(emptyForm);
    setProductPickerId("");
  }

  async function handleSave() {
    try {
      setSaving(true);
      setFeedback(null);

      const normalizedItems = form.items
        .map((item) => ({
          product_id: String(item.product_id || ""),
          quantity: Math.max(1, Math.floor(Number(item.quantity || 0) || 1)),
        }))
        .filter((item) => item.product_id);

      const computedTotal = normalizedItems.reduce((sum, item) => {
        const product = productsById.get(item.product_id);
        const unit = product && !product.price_on_request ? product.price : 0;
        return sum + unit * item.quantity;
      }, 0);

      const payload = {
        id: form.id,
        title: form.title,
        description: form.description,
        amount: normalizedItems.length > 0 && computedTotal > 0 ? Number(computedTotal.toFixed(2)) : Number(form.amount),
        type: form.type,
        status: form.status,
        interval_count: form.type === "subscription" ? Number(form.interval_count) : null,
        interval_unit: form.type === "subscription" ? form.interval_unit : null,
        image_url: form.image_url || null,
        expires_at: toIsoOrNull(form.expires_at),
        allow_credit_card: form.allow_credit_card,
        allow_pix: form.type === "one_time" ? form.allow_pix : false,
        allow_boleto: form.type === "one_time" ? form.allow_boleto : false,
        checkout_config: {
          client_id: form.client_id || null,
          items: normalizedItems,
          show_cookie_banner: Boolean(form.show_cookie_banner),
        },
        share_config: {
          whatsapp_message: String(form.whatsapp_message || "").trim() || null,
        },
      };

      const response = await fetch("/api/financial/payment-links", {
        method: form.id ? "PATCH" : "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      const result = (await response.json().catch(() => null)) as { error?: string } | null;
      if (!response.ok) {
        throw new Error(result?.error || "Nao foi possivel salvar o link.");
      }

      await loadLinks();
      setDialogOpen(false);
      setForm(emptyForm);
      setFeedback({
        type: "success",
        text: form.id ? "Link atualizado com sucesso." : "Link criado com sucesso.",
      });
    } catch (error) {
      setFeedback({
        type: "error",
        text: error instanceof Error ? error.message : "Nao foi possivel salvar o link.",
      });
    } finally {
      setSaving(false);
    }
  }

  async function handleStatusChange(link: PaymentLink, status: PaymentLinkStatus) {
    try {
      setActioningId(link.id);
      setFeedback(null);
      const checkoutConfig = normalizeCheckoutConfig(link.checkout_config);
      const shareConfig = normalizeShareConfig(link.share_config);
      const normalizedItems = checkoutConfig.items
        .map((item) => ({
          product_id: String(item.product_id || ""),
          quantity: Math.max(1, Math.floor(Number(item.quantity || 0) || 1)),
        }))
        .filter((item) => item.product_id);
      const response = await fetch("/api/financial/payment-links", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          id: link.id,
          title: link.title,
          description: link.description,
          amount: link.amount,
          type: link.type,
          status,
          expires_at: link.expires_at,
          interval_count: link.interval_count,
          interval_unit: link.interval_unit,
          image_url: link.image_url,
          allow_credit_card: link.allow_credit_card,
          allow_pix: link.allow_pix,
          allow_boleto: link.allow_boleto,
          checkout_config: {
            client_id: checkoutConfig.client_id || null,
            items: normalizedItems,
            show_cookie_banner: Boolean(checkoutConfig.show_cookie_banner),
          },
          share_config: {
            whatsapp_message: String(shareConfig.whatsapp_message || "").trim() || null,
          },
        }),
      });
      const result = (await response.json().catch(() => null)) as { error?: string } | null;
      if (!response.ok) {
        throw new Error(result?.error || "Nao foi possivel atualizar o status.");
      }
      await loadLinks();
    } catch (error) {
      setFeedback({
        type: "error",
        text: error instanceof Error ? error.message : "Nao foi possivel atualizar o status do link.",
      });
    } finally {
      setActioningId(null);
    }
  }

  function pedirParaExcluir(link: PaymentLink) {
    setConfirmacao({
      titulo: `Excluir o link "${link.title}"?`,
      texto: "Quem receber o link vai encontrar uma página fora do ar. Pagamentos já feitos continuam registrados.",
      confirmar: "Excluir link",
      tom: "perigo",
      aoConfirmar: () => {
        setConfirmacao(null);
        return handleDelete(link);
      },
    });
  }

  async function handleDelete(link: PaymentLink) {
    try {
      setDeletingId(link.id);
      setFeedback(null);
      const response = await fetch(`/api/financial/payment-links?id=${encodeURIComponent(link.id)}`, {
        method: "DELETE",
      });
      const result = (await response.json().catch(() => null)) as { error?: string } | null;
      if (!response.ok) {
        throw new Error(result?.error || "Nao foi possivel excluir o link.");
      }

      await loadLinks();
      setFeedback({ type: "success", text: "Link excluido com sucesso." });
    } catch (error) {
      setFeedback({
        type: "error",
        text: error instanceof Error ? error.message : "Nao foi possivel excluir o link.",
      });
    } finally {
      setDeletingId(null);
    }
  }

  async function copyToClipboard(value: string, message: string) {
    try {
      await navigator.clipboard.writeText(value);
      setFeedback({ type: "success", text: message });
    } catch {
      setFeedback({ type: "error", text: "Nao foi possivel copiar o link." });
    }
  }

  function exportCsv() {
    const header = ["Nome", "Codigo", "Tipo", "Valor", "Status", "Criado em", "URL"];
    const lines = filteredLinks.map((link) =>
      [
        link.title,
        link.code,
        typeLabel(link.type),
        String(link.amount).replace(".", ","),
        statusLabel(link.status),
        formatDate(link.created_at),
        link.public_url,
      ]
        .map((item) => `"${String(item).replace(/"/g, '""')}"`)
        .join(";")
    );
    const blob = new Blob([[header.join(";"), ...lines].join("\n")], {
      type: "text/csv;charset=utf-8;",
    });
    const url = URL.createObjectURL(blob);
    const anchor = document.createElement("a");
    anchor.href = url;
    anchor.download = "links-de-pagamento.csv";
    anchor.click();
    URL.revokeObjectURL(url);
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title="Links de Pagamento"
        subtitle="Crie links de pagamento e personalize a experiencia do seu checkout."
        actions={
          <div className="grid w-full grid-cols-2 gap-2 sm:flex sm:w-auto sm:items-center">
            <button
              type="button"
              onClick={exportCsv}
              className="ks-button ks-button-secondary w-full justify-center sm:w-auto"
            >
              <Download className="h-4 w-4" />
              <span className="hidden sm:inline">Exportar</span>
            </button>
            <div className="relative">
              <button
                type="button"
                onClick={() => setSettingsMenuOpen((prev) => !prev)}
                className="ks-button ks-button-secondary w-full justify-center sm:w-auto"
              >
                <Settings className="h-4 w-4" />
                <span className="hidden sm:inline">Configurações do link</span>
                <ChevronDown className={`h-4 w-4 transition-transform ${settingsMenuOpen ? "rotate-180" : ""}`} />
              </button>

              {settingsMenuOpen ? (
                <>
                  <button
                    type="button"
                    aria-label="Fechar menu"
                    onClick={() => setSettingsMenuOpen(false)}
                    className="fixed inset-0 z-40 cursor-default"
                  />
                  <div className="absolute right-0 top-[calc(100%+10px)] z-50 w-[92vw] max-w-[340px] rounded-2xl border border-[var(--ks-color-border-subtle)] bg-white p-2 shadow-[0_20px_60px_rgba(15,23,42,0.16)]">
                    <button
                      type="button"
                      disabled={!selectedLink}
                      onClick={() => {
                        setSettingsMenuOpen(false);
                        setWhatsTemplateModalOpen(true);
                      }}
                      className={`w-full rounded-xl p-3 text-left transition ${
                        selectedLink ? "hover:bg-[var(--ks-color-bg-soft)]" : "opacity-50"
                      }`}
                    >
                      <div className="flex items-start gap-3">
                        <div className="mt-0.5 flex h-10 w-10 items-center justify-center rounded-xl bg-emerald-50 text-emerald-600">
                          <WhatsAppIcon className="h-5 w-5" />
                        </div>
                        <div className="min-w-0">
                          <div className="text-sm font-semibold text-slate-900">Mensagem de envio do link</div>
                          <div className="mt-0.5 text-xs text-slate-500">
                            Defina o texto padrão enviado junto com o link no WhatsApp.
                          </div>
                        </div>
                      </div>
                    </button>
                  </div>
                </>
              ) : null}
            </div>
            {podeLancar && (
              <button
                type="button"
                onClick={openCreateDialog}
                className="ks-button ks-button-primary col-span-2 w-full justify-center sm:col-auto sm:w-auto"
              >
                <Link2 className="h-4 w-4" />
                Novo link
              </button>
            )}
          </div>
        }
      />

      {feedback ? (
        <div
          className={`border px-4 py-3 text-sm ${
            feedback.type === "success"
              ? "border-emerald-200 bg-emerald-50 text-emerald-700"
              : "border-rose-200 bg-rose-50 text-rose-700"
          }`}
        >
          {feedback.text}
        </div>
      ) : null}

      <div className="ks-table-shell grid gap-0 xl:grid-cols-[minmax(0,1fr)_420px]">
        <section className="min-w-0 xl:border-r xl:border-[var(--ks-color-border-subtle)]">
          <div className="border-b border-[var(--ks-color-border-subtle)] bg-[var(--ks-color-bg-soft)] p-4">
            <div className="flex flex-col gap-3 md:flex-row md:items-center">
              <div className="min-w-0 md:flex-1">
                <Input
                  value={search}
                  onChange={(event) => setSearch(event.target.value)}
                  placeholder="Buscar por nome ou ID..."
                  icon={<Search className="h-4 w-4" />}
                />
              </div>

              <div className="grid grid-cols-3 gap-2 md:w-[520px]">
                <div className="min-w-0">
                  <CustomSelect
                    value={statusFilter}
                    onChange={(value) => setStatusFilter(value as "all" | PaymentLinkStatus)}
                    dropdownFullWidth={isMobile}
                    forceOpenDown={isMobile}
                    size={isMobile ? "sm" : "md"}
                    showChevron={!isMobile}
                    options={[
                      { value: "all", label: "Status: Todos", selected_label: isMobile ? "Status" : undefined, icon: Activity },
                      { value: "active", label: "Status: Ativos", selected_label: isMobile ? "Status" : undefined, icon: Activity },
                      { value: "paused", label: "Status: Pausados", selected_label: isMobile ? "Status" : undefined, icon: Activity },
                      { value: "draft", label: "Status: Rascunhos", selected_label: isMobile ? "Status" : undefined, icon: Activity },
                      { value: "archived", label: "Status: Arquivados", selected_label: isMobile ? "Status" : undefined, icon: Activity },
                    ]}
                  />
                </div>
                <div className="min-w-0">
                  <CustomSelect
                    value={typeFilter}
                    onChange={(value) => setTypeFilter(value as "all" | PaymentLinkType)}
                    dropdownFullWidth={isMobile}
                    forceOpenDown={isMobile}
                    size={isMobile ? "sm" : "md"}
                    showChevron={!isMobile}
                    options={[
                      { value: "all", label: "Tipo: Todos", selected_label: isMobile ? "Tipo" : undefined, icon: Tag },
                      { value: "one_time", label: "Tipo: Produto único", selected_label: isMobile ? "Tipo" : undefined, icon: Tag },
                      { value: "subscription", label: "Tipo: Assinatura", selected_label: isMobile ? "Tipo" : undefined, icon: Tag },
                    ]}
                  />
                </div>
                <div className="min-w-0">
                  <CustomSelect
                    value={sortBy}
                    onChange={(value) => setSortBy(value as SortOption)}
                    dropdownFullWidth={isMobile}
                    forceOpenDown={isMobile}
                    size={isMobile ? "sm" : "md"}
                    showChevron={!isMobile}
                    options={[
                      { value: "recent", label: "Ordenar: Mais recentes", selected_label: isMobile ? "Ordenar" : undefined, icon: ArrowDownUp },
                      { value: "oldest", label: "Ordenar: Mais antigos", selected_label: isMobile ? "Ordenar" : undefined, icon: ArrowDownUp },
                      { value: "highest", label: "Ordenar: Maior valor", selected_label: isMobile ? "Ordenar" : undefined, icon: ArrowDownUp },
                      { value: "lowest", label: "Ordenar: Menor valor", selected_label: isMobile ? "Ordenar" : undefined, icon: ArrowDownUp },
                    ]}
                  />
                </div>
              </div>
            </div>
          </div>

          <div className="md:hidden">
            {loading ? (
              <div className="px-4 py-10 text-center text-sm text-slate-500">Carregando links...</div>
            ) : filteredLinks.length === 0 ? (
              <div className="px-4 py-10 text-center text-sm text-slate-500">Nenhum link encontrado com os filtros atuais.</div>
            ) : (
              <div className="space-y-3 p-4">
                {filteredLinks.map((link) => {
                  const selected = selectedId === link.id;
                  const config = normalizeCheckoutConfig(link.checkout_config);
                  const client = config.client_id ? clients.find((item) => item.id === config.client_id) || null : null;
                  const clientLabel = client
                    ? client.company_name
                      ? `${client.company_name} · ${client.name}`
                      : client.name
                    : config.client_id
                      ? `ID: ${config.client_id}`
                      : "Nenhum cliente";
                  return (
                    <div
                      key={link.id}
                      className={`w-full rounded-2xl border border-[var(--ks-color-border-subtle)] bg-white p-3.5 text-left transition ${
                        selected ? "ring-1 ring-[var(--ks-color-primary)] shadow-[0_8px_24px_rgba(15,23,42,0.06)]" : "hover:bg-[var(--ks-color-bg-soft)]"
                      }`}
                    >
                      <div className="flex items-start gap-3">
                        <button type="button" onClick={() => handleSelectLink(link.id)} className="min-w-0 flex-1 text-left">
                          <div className="flex items-start justify-between gap-3">
                            <div className="min-w-0">
                              <div className="truncate text-sm font-semibold text-slate-900">{link.title}</div>
                              <div className="mt-0.5 flex flex-wrap items-center gap-2 text-xs text-slate-500">
                                <span className="truncate">{link.code}</span>
                                <span>•</span>
                                <span>{typeLabel(link.type)}</span>
                              </div>
                            </div>
                            <ChevronDown
                              className={`mt-0.5 h-4 w-4 shrink-0 text-slate-400 transition-transform ${selected ? "rotate-180" : ""}`}
                            />
                          </div>

                          <div className="mt-2.5 flex items-center justify-between gap-3">
                            <div className="text-sm font-semibold text-slate-900">{dinheiro(link.amount)}</div>
                            <span className={statusTone(link.status)}>{statusLabel(link.status)}</span>
                          </div>
                        </button>
                        <button
                          type="button"
                          onClick={(event) => {
                            event.preventDefault();
                            event.stopPropagation();
                            void handleWhatsAppClick(link);
                          }}
                          className="inline-flex h-9 w-9 shrink-0 items-center justify-center text-[#25D366] transition hover:cursor-pointer hover:opacity-80"
                          aria-label="Enviar no WhatsApp"
                          title="Enviar no WhatsApp"
                        >
                          <WhatsAppIcon className="h-5 w-5" />
                        </button>
                      </div>

                      <div
                        className={`grid transition-all duration-300 ease-out ${
                          selected ? "mt-4 grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0"
                        }`}
                      >
                        <div className="min-h-0 overflow-hidden">
                          <div
                            className={`border-t border-[var(--ks-color-border-subtle)] pt-4 transition-transform duration-300 ease-out ${
                              selected ? "translate-y-0" : "-translate-y-2"
                            }`}
                          >
                            <div className="divide-y divide-[var(--ks-color-border-subtle)]">
                              <section className="space-y-2 pb-4">
                                <div className="text-[11px] font-semibold uppercase tracking-[0.14em] text-slate-500">Link</div>
                                <div className="space-y-2 rounded-2xl bg-[var(--ks-color-bg-soft)] p-3 text-sm text-slate-700">
                                  <div className="truncate">{link.public_url}</div>
                                  <div className="grid grid-cols-2 gap-2">
                                    <button
                                      type="button"
                                      onClick={() => void copyToClipboard(link.public_url, "Link copiado com sucesso.")}
                                      className="inline-flex h-10 items-center justify-center gap-2 rounded-xl border border-[var(--ks-color-border-subtle)] bg-white px-3 text-sm font-medium text-slate-700 transition hover:bg-[var(--ks-color-bg-soft)]"
                                    >
                                      <Copy className="h-4 w-4" />
                                      Copiar
                                    </button>
                                    <a
                                      href={link.public_url}
                                      target="_blank"
                                      rel="noreferrer"
                                      className="inline-flex h-10 items-center justify-center gap-2 rounded-xl border border-[var(--ks-color-border-subtle)] bg-white px-3 text-sm font-medium text-slate-700 transition hover:bg-[var(--ks-color-bg-soft)]"
                                    >
                                      <ExternalLink className="h-4 w-4" />
                                      Abrir
                                    </a>
                                  </div>
                                </div>
                              </section>

                              <section className="space-y-3 py-4">
                                <div className="text-[11px] font-semibold uppercase tracking-[0.14em] text-slate-500">Detalhes</div>
                                <div className="grid grid-cols-2 gap-3 text-sm">
                                  <div className="text-slate-500">Tipo</div>
                                  <div className="text-right text-slate-900">{typeLabel(link.type)}</div>
                                  <div className="text-slate-500">Recorrência</div>
                                  <div className="text-right text-slate-900">{recurrenceLabel(link)}</div>
                                  <div className="text-slate-500">Métodos</div>
                                  <div className="text-right text-slate-900">{paymentMethodsLabel(link)}</div>
                                  <div className="text-slate-500">Valor</div>
                                  <div className="text-right text-slate-900">{dinheiro(link.amount)}</div>
                                  <div className="text-slate-500">Expira em</div>
                                  <div className="text-right text-slate-900">{formatDate(link.expires_at)}</div>
                                </div>
                              </section>

                              <section className="space-y-3 py-4">
                                <div className="text-[11px] font-semibold uppercase tracking-[0.14em] text-slate-500">Vínculos</div>
                                <div className="space-y-2 text-sm">
                                  <div className="flex items-start justify-between gap-4">
                                    <div className="text-slate-500">Cliente</div>
                                    <div className="min-w-0 text-right text-slate-900">{clientLabel}</div>
                                  </div>
                                  {config.items.length ? (
                                    <div className="border-t border-[var(--ks-color-border-subtle)] pt-3">
                                      <div className="text-slate-500">Produtos</div>
                                      <div className="mt-2 space-y-2">
                                        {config.items.map((item) => {
                                          const product = productsById.get(item.product_id);
                                          const name = product?.name || item.product_id;
                                          return (
                                            <div key={item.key} className="flex items-start justify-between gap-4">
                                              <div className="min-w-0 text-slate-900">{name}</div>
                                              <div className="shrink-0 text-right text-slate-700">Qtd: {item.quantity}</div>
                                            </div>
                                          );
                                        })}
                                      </div>
                                    </div>
                                  ) : null}
                                </div>
                              </section>
                            </div>

                            <div className="grid grid-cols-[1fr_44px_44px] gap-2 pt-4">
                            {podeLancar && (<button
                              type="button"
                              onClick={() => openEditDialog(link)}
                              className="ks-button ks-button-secondary w-full justify-center"
                            >
                              <Pencil className="h-4 w-4" />
                              Editar link
                            </button>)}
                            {link.status === "active" ? (
                              <button
                                type="button"
                                onClick={() => void handleStatusChange(link, "paused")}
                                disabled={actioningId === link.id}
                                className="ks-button ks-button-secondary h-11 w-11 px-0 disabled:opacity-50"
                              >
                                <Pause className="h-4 w-4" />
                              </button>
                            ) : (
                              <button
                                type="button"
                                onClick={() => void handleStatusChange(link, "active")}
                                disabled={actioningId === link.id}
                                className="ks-button ks-button-secondary h-11 w-11 px-0 disabled:opacity-50"
                              >
                                <Play className="h-4 w-4" />
                              </button>
                            )}
                            {podeLancar && (<button
                              type="button"
                              onClick={() => pedirParaExcluir(link)}
                              disabled={deletingId === link.id}
                              className="inline-flex h-11 w-11 items-center justify-center rounded-full border border-rose-200 bg-white text-rose-600 shadow-[0_1px_3px_rgba(15,23,42,0.08)] transition hover:bg-rose-50 disabled:opacity-50"
                            >
                              <Trash2 className="h-4 w-4" />
                            </button>)}
                          </div>
                        </div>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>

          <div className="hidden overflow-x-auto md:block">
            <table className="ks-table min-w-full">
              <thead>
                <tr>
                  <th className="w-12 px-4 py-3">
                    <input type="checkbox" className="h-4 w-4 border-slate-300" readOnly />
                  </th>
                  <th className="px-4 py-3">Nome</th>
                  <th className="px-4 py-3">Tipo</th>
                  <th className="px-4 py-3">Valor</th>
                  <th className="px-4 py-3">Status</th>
                  <th className="px-4 py-3">Criado em</th>
                </tr>
              </thead>
              <tbody>
                {loading ? (
                  <tr>
                    <td colSpan={6} className="px-4 py-16 text-center text-sm text-slate-500">
                      Carregando links...
                    </td>
                  </tr>
                ) : filteredLinks.length === 0 ? (
                  <tr>
                    <td colSpan={6} className="px-4 py-16 text-center text-sm text-slate-500">
                      Nenhum link encontrado com os filtros atuais.
                    </td>
                  </tr>
                ) : (
                  filteredLinks.map((link) => {
                    const selected = selectedId === link.id;
                    return (
                      <tr
                        key={link.id}
                        onClick={() => handleSelectLink(link.id)}
                        className={`cursor-pointer transition ${selected ? "bg-[rgba(10,192,214,0.08)]" : ""}`}
                      >
                        <td className="px-4 py-4">
                          <input
                            type="checkbox"
                            className="h-4 w-4 border-slate-300"
                            checked={selected}
                            readOnly
                          />
                        </td>
                        <td className="px-4 py-4">
                          <div className="flex items-center justify-between gap-3">
                            <div className="flex min-w-0 items-center gap-3">
                              <div className="flex h-10 w-10 items-center justify-center rounded-xl bg-[var(--ks-color-primary-soft)] text-[var(--ks-color-primary-strong)]">
                                {link.type === "subscription" ? <RefreshCcw className="h-4 w-4" /> : <Link2 className="h-4 w-4" />}
                              </div>
                              <div className="min-w-0">
                                <div className="truncate text-sm font-semibold text-slate-900">{link.title}</div>
                                <div className="truncate text-xs text-slate-500">{link.code}</div>
                              </div>
                            </div>
                            <button
                              type="button"
                              onClick={(event) => {
                                event.preventDefault();
                                event.stopPropagation();
                                void handleWhatsAppClick(link);
                              }}
                              className="inline-flex h-9 w-9 items-center justify-center text-[#25D366] transition hover:cursor-pointer hover:opacity-80"
                              aria-label="Enviar no WhatsApp"
                              title="Enviar no WhatsApp"
                            >
                              <WhatsAppIcon className="h-5 w-5" />
                            </button>
                          </div>
                        </td>
                        <td className="px-4 py-4 text-sm text-slate-600">{typeLabel(link.type)}</td>
                        <td className="px-4 py-4 text-sm font-medium text-slate-900">
                          {dinheiro(link.amount)}
                          {link.type === "subscription" ? (
                            <div className="text-xs font-normal text-slate-500">{recurrenceLabel(link)}</div>
                          ) : null}
                        </td>
                        <td className="px-4 py-4">
                          <span className={statusTone(link.status)}>{statusLabel(link.status)}</span>
                        </td>
                        <td className="px-4 py-4 text-sm text-slate-600">{formatDate(link.created_at)}</td>
                      </tr>
                    );
                  })
                )}
              </tbody>
            </table>
          </div>

          <div className="px-4 py-4 text-xs text-slate-500">
            Mostrando {filteredLinks.length} de {links.length} links
          </div>
        </section>

        <aside className="hidden min-w-0 bg-white xl:block">
          {selectedLink ? (
            <div className="flex h-full flex-col">
              <div className="border-b border-[var(--ks-color-border-subtle)] p-5">
                <div className="flex items-start justify-between gap-3">
                  <div className="min-w-0">
                    <div className="truncate text-lg font-semibold text-slate-950">{selectedLink.title}</div>
                    <div className="mt-1 truncate text-sm text-slate-500">
                      {selectedLink.code} · Criado em {formatDate(selectedLink.created_at)}
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <span className={statusTone(selectedLink.status)}>{statusLabel(selectedLink.status)}</span>
                    <button
                      type="button"
                      onClick={() => setSelectedId(null)}
                      className="inline-flex h-9 w-9 items-center justify-center rounded-xl border border-[var(--ks-color-border-subtle)] bg-white text-slate-500 transition hover:bg-[var(--ks-color-bg-soft)] hover:text-slate-900"
                    >
                      <X className="h-4 w-4" />
                    </button>
                  </div>
                </div>
              </div>

              <div className="flex-1 space-y-6 p-5">
                <div className="space-y-2">
                  <div className="text-sm font-semibold text-slate-900">Link de pagamento</div>
                  <div className="flex items-center gap-2 rounded-2xl border border-[var(--ks-color-border-subtle)] bg-[var(--ks-color-bg-soft)] p-3 text-sm text-slate-700">
                    <span className="min-w-0 flex-1 truncate">{selectedLink.public_url}</span>
                    <button
                      type="button"
                      onClick={() => void copyToClipboard(selectedLink.public_url, "Link copiado com sucesso.")}
                      className="inline-flex h-9 w-9 items-center justify-center rounded-xl border border-[var(--ks-color-border-subtle)] bg-white transition hover:bg-[var(--ks-color-bg-soft)]"
                      aria-label="Copiar link"
                    >
                      <Copy className="h-4 w-4" />
                    </button>
                    <a
                      href={selectedLink.public_url}
                      target="_blank"
                      rel="noreferrer"
                      className="inline-flex h-9 items-center justify-center gap-2 rounded-xl border border-[var(--ks-color-border-subtle)] bg-white px-3 text-sm font-medium text-slate-700 transition hover:bg-[var(--ks-color-bg-soft)]"
                    >
                      <ExternalLink className="h-4 w-4" />
                      Abrir
                    </a>
                  </div>
                </div>

                <div className="space-y-3 rounded-2xl border border-[var(--ks-color-border-subtle)] bg-white p-4">
                  <div className="text-sm font-semibold text-slate-900">Detalhes</div>
                  <div className="grid grid-cols-2 gap-3 text-sm">
                    <div className="text-slate-500">Tipo</div>
                    <div className="text-right text-slate-900">{typeLabel(selectedLink.type)}</div>
                    <div className="text-slate-500">Recorrência</div>
                    <div className="text-right text-slate-900">{recurrenceLabel(selectedLink)}</div>
                    <div className="text-slate-500">Métodos</div>
                    <div className="text-right text-slate-900">{paymentMethodsLabel(selectedLink)}</div>
                    <div className="text-slate-500">Valor</div>
                    <div className="text-right text-slate-900">{dinheiro(selectedLink.amount)}</div>
                    <div className="text-slate-500">Expira em</div>
                    <div className="text-right text-slate-900">{formatDate(selectedLink.expires_at)}</div>
                  </div>
                </div>

                {(() => {
                  const config = normalizeCheckoutConfig(selectedLink.checkout_config);
                  const client = config.client_id ? clients.find((item) => item.id === config.client_id) : null;
                  const items = config.items;

                  const clientLabel = client
                    ? client.company_name
                      ? `${client.company_name} · ${client.name}`
                      : client.name
                    : config.client_id
                      ? `ID: ${config.client_id}`
                      : "Nenhum cliente";

                  return (
                    <div className="space-y-3 rounded-2xl border border-[var(--ks-color-border-subtle)] bg-white p-4">
                      <div className="text-sm font-semibold text-slate-900">Vínculos</div>
                      <div className="space-y-2 text-sm">
                        <div className="flex items-start justify-between gap-4">
                          <div className="text-slate-500">Cliente</div>
                          <div className="min-w-0 text-right text-slate-900">{clientLabel || "Nenhum cliente"}</div>
                        </div>

                        {items.length ? (
                          <div className="border-t border-[var(--ks-color-border-subtle)] pt-3">
                            <div className="text-slate-500">Produtos</div>
                            <div className="mt-2 space-y-2">
                              {items.map((item) => {
                                const product = productsById.get(item.product_id);
                                const name = product?.name || item.product_id;
                                return (
                                  <div key={item.key} className="flex items-start justify-between gap-4">
                                    <div className="min-w-0 text-slate-900">{name}</div>
                                    <div className="shrink-0 text-right text-slate-700">Qtd: {item.quantity}</div>
                                  </div>
                                );
                              })}
                            </div>
                          </div>
                        ) : null}
                      </div>
                    </div>
                  );
                })()}
              </div>

              <div className="mt-auto flex items-center gap-3 border-t border-[var(--ks-color-border-subtle)] bg-[var(--ks-color-bg-soft)] p-5">
                {podeLancar && (<button
                  type="button"
                  onClick={() => openEditDialog(selectedLink)}
                  className="ks-button ks-button-secondary flex-1"
                >
                  <Pencil className="h-4 w-4" />
                  Editar link
                </button>)}
                {selectedLink.status === "active" ? (
                  <button
                    type="button"
                    onClick={() => void handleStatusChange(selectedLink, "paused")}
                    disabled={actioningId === selectedLink.id}
                    className="ks-button ks-button-secondary h-11 w-11 px-0 disabled:opacity-50"
                  >
                    <Pause className="h-4 w-4" />
                  </button>
                ) : (
                  <button
                    type="button"
                    onClick={() => void handleStatusChange(selectedLink, "active")}
                    disabled={actioningId === selectedLink.id}
                    className="ks-button ks-button-secondary h-11 w-11 px-0 disabled:opacity-50"
                  >
                    <Play className="h-4 w-4" />
                  </button>
                )}
                <button
                  type="button"
                  onClick={() => void handleDelete(selectedLink)}
                  disabled={deletingId === selectedLink.id}
                  className="inline-flex h-11 w-11 items-center justify-center rounded-full border border-rose-200 bg-white text-rose-600 shadow-[0_1px_3px_rgba(15,23,42,0.08)] transition hover:bg-rose-50 disabled:opacity-50"
                >
                  <Trash2 className="h-4 w-4" />
                </button>
              </div>
            </div>
          ) : (
            <div className="flex h-full min-h-[520px] items-center justify-center px-6 text-center text-sm text-slate-500">
              Selecione um link para ver o painel lateral.
            </div>
          )}
        </aside>
      </div>

      <Dialog open={dialogOpen} onOpenChange={(open) => (open ? setDialogOpen(true) : closeDialog())}>
        <DialogContent className="flex h-[100dvh] w-[100vw] max-w-none flex-col gap-0 overflow-hidden border-slate-200 p-0 !left-0 !top-0 !translate-x-0 !translate-y-0 rounded-none sm:h-auto sm:w-[96vw] sm:max-w-[620px] sm:rounded-2xl sm:overflow-visible sm:!left-[50%] sm:!top-[50%] sm:!translate-x-[-50%] sm:!translate-y-[-50%]">
          <DialogHeader className="shrink-0 border-b border-slate-200 px-4 pb-4 pt-[calc(1rem+env(safe-area-inset-top))] sm:px-5 sm:py-4">
            <DialogTitle>{form.id ? "Editar link de pagamento" : "Novo link de pagamento"}</DialogTitle>
            <DialogDescription>
              Configure o checkout e publique um link pronto para compartilhar.
            </DialogDescription>
          </DialogHeader>

          <div className="grid shrink-0 grid-cols-2 border-b border-slate-200 px-4 sm:flex sm:px-5">
            {([
              { key: "general" as const, label: "Geral" },
              { key: "details" as const, label: "Pagamento" },
            ] as const).map((item) => (
              <button
                key={item.key}
                type="button"
                onClick={() => setModalTab(item.key)}
                className={[
                  "flex items-center justify-center px-3 py-2.5 text-xs font-semibold border-b-2 transition-colors -mb-px sm:justify-start",
                  modalTab === item.key
                    ? "border-violet-600 text-violet-700"
                    : "border-transparent text-slate-500 hover:text-slate-700",
                ].join(" ")}
              >
                {item.label}
              </button>
            ))}
          </div>

          <div className="min-h-0 flex-1 overflow-y-auto px-4 py-4 sm:px-5">
            {modalTab === "general" ? (
              <div className="grid gap-4 md:grid-cols-2">
                <label className="space-y-2 md:col-span-2">
                  <span className="text-sm font-medium text-slate-700">Nome do link</span>
                  <input
                    value={form.title}
                    onChange={(event) => setForm((current) => ({ ...current, title: event.target.value }))}
                    placeholder="Consultoria Estratégica"
                    className={fieldClass}
                  />
                </label>

                <label className="space-y-2 md:col-span-2">
                  <span className="text-sm font-medium text-slate-700">Descrição</span>
                  <textarea
                    value={form.description}
                    onChange={(event) => setForm((current) => ({ ...current, description: event.target.value }))}
                    placeholder="Explique o que o cliente está comprando."
                    className={`${textareaClass} min-h-[72px]`}
                    rows={3}
                  />
                </label>

                <div className="md:col-span-2">
                  <CustomSelect
                    label="Cliente (opcional)"
                    options={clientOptions}
                    value={form.client_id}
                    onChange={(value) => setForm((current) => ({ ...current, client_id: value }))}
                    searchable
                    portal={false}
                    disabled={lookupLoading && clients.length === 0}
                    placeholder={lookupLoading && clients.length === 0 ? "Carregando clientes..." : "Selecione..."}
                  />
                </div>

                <div className="space-y-2 md:col-span-2">
                  <div className="text-sm font-medium text-slate-700">Produtos (opcional)</div>
                  <div className="flex items-end gap-2">
                    <div className="min-w-0 flex-1">
                      <CustomSelect
                        options={productOptions}
                        value={productPickerId}
                        onChange={(value) => setProductPickerId(value)}
                        searchable
                        portal={false}
                        disabled={form.type === "subscription" || (lookupLoading && products.length === 0)}
                        placeholder={
                          form.type === "subscription"
                            ? "Assinatura nao suporta produtos"
                            : lookupLoading && products.length === 0
                              ? "Carregando produtos..."
                              : "Buscar produto..."
                        }
                      />
                    </div>
                    <button
                      type="button"
                      onClick={() => {
                        if (!productPickerId) return;
                        setForm((current) => {
                          const existing = current.items.find((item) => item.product_id === productPickerId);
                          if (existing) {
                            return {
                              ...current,
                              items: current.items.map((item) =>
                                item.product_id === productPickerId
                                  ? { ...item, quantity: String(Math.max(1, Math.floor(Number(item.quantity || 0) || 1) + 1)) }
                                  : item
                              ),
                            };
                          }
                          return {
                            ...current,
                            items: [...current.items, { key: randomKey(), product_id: productPickerId, quantity: "1" }],
                          };
                        });
                        setProductPickerId("");
                      }}
                      disabled={form.type === "subscription" || !productPickerId}
                      className="inline-flex h-11 items-center justify-center gap-2 rounded-xl border border-slate-200 bg-white px-4 text-sm font-medium text-slate-700 transition hover:bg-slate-50 disabled:opacity-50"
                    >
                      <Plus className="h-4 w-4" />
                      Adicionar
                    </button>
                  </div>

                  {form.items.length > 0 ? (
                    <div className="space-y-2 rounded-xl border border-slate-200 bg-slate-50 p-3">
                      {form.items.map((item) => {
                        const product = productsById.get(item.product_id);
                        return (
                          <div key={item.key} className="grid gap-2 md:grid-cols-[1fr_110px_44px] md:items-center">
                            <div className="min-w-0 text-sm font-medium text-slate-700">
                              {product ? product.name : "Produto"}
                            </div>
                            <input
                              value={item.quantity}
                              onChange={(event) => {
                                const next = event.target.value;
                                setForm((current) => ({
                                  ...current,
                                  items: current.items.map((candidate) =>
                                    candidate.key === item.key ? { ...candidate, quantity: next } : candidate
                                  ),
                                }));
                              }}
                              type="number"
                              min="1"
                              step="1"
                              className={fieldClass}
                            />
                            <button
                              type="button"
                              onClick={() =>
                                setForm((current) => ({
                                  ...current,
                                  items: current.items.filter((candidate) => candidate.key !== item.key),
                                }))
                              }
                              className="inline-flex h-11 items-center justify-center rounded-xl border border-slate-200 bg-white text-slate-600 transition hover:bg-slate-100"
                              aria-label="Remover"
                            >
                              <X className="h-4 w-4" />
                            </button>
                          </div>
                        );
                      })}
                    </div>
                  ) : null}
                </div>

                <label className="space-y-2">
                  <span className="text-sm font-medium text-slate-700">Tipo</span>
                  <select
                    value={form.type}
                    onChange={(event) =>
                      setForm((current) => ({
                        ...current,
                        type: event.target.value as PaymentLinkType,
                        allow_pix: event.target.value === "subscription" ? false : current.allow_pix,
                        allow_boleto: event.target.value === "subscription" ? false : current.allow_boleto,
                        items: event.target.value === "subscription" ? [] : current.items,
                      }))
                    }
                    className={fieldClass}
                  >
                    <option value="one_time">Produto único</option>
                    <option value="subscription">Assinatura</option>
                  </select>
                </label>

                <label className="space-y-2">
                  <span className="text-sm font-medium text-slate-700">Status</span>
                  <select
                    value={form.status}
                    onChange={(event) =>
                      setForm((current) => ({ ...current, status: event.target.value as PaymentLinkStatus }))
                    }
                    className={fieldClass}
                  >
                    <option value="active">Ativo</option>
                    <option value="paused">Pausado</option>
                    <option value="draft">Rascunho</option>
                    <option value="archived">Arquivado</option>
                  </select>
                </label>

                <label className="space-y-2 md:col-span-2">
                  <span className="text-sm font-medium text-slate-700">Valor</span>
                  <input
                    value={form.amount}
                    onChange={(event) => setForm((current) => ({ ...current, amount: event.target.value }))}
                    placeholder="497.00"
                    type="number"
                    min="0"
                    step="0.01"
                    className={fieldClass}
                    disabled={form.type === "one_time" && form.items.length > 0}
                  />
                  {form.type === "one_time" && form.items.length > 0 ? (
                    <div className="text-xs text-slate-500">Valor calculado pelos produtos selecionados.</div>
                  ) : null}
                </label>
              </div>
            ) : (
              <div className="grid gap-4 md:grid-cols-2">
                <label className="space-y-2">
                  <span className="text-sm font-medium text-slate-700">Expira em</span>
                  <input
                    value={form.expires_at}
                    onChange={(event) => setForm((current) => ({ ...current, expires_at: event.target.value }))}
                    type="datetime-local"
                    className={fieldClass}
                  />
                </label>

                <label className="space-y-2">
                  <span className="text-sm font-medium text-slate-700">Imagem</span>
                  <input
                    value={form.image_url}
                    onChange={(event) => setForm((current) => ({ ...current, image_url: event.target.value }))}
                    placeholder="https://..."
                    className={fieldClass}
                  />
                </label>

                {form.type === "subscription" ? (
                  <>
                    <label className="space-y-2">
                      <span className="text-sm font-medium text-slate-700">Frequência</span>
                      <input
                        value={form.interval_count}
                        onChange={(event) => setForm((current) => ({ ...current, interval_count: event.target.value }))}
                        type="number"
                        min="1"
                        step="1"
                        className={fieldClass}
                      />
                    </label>

                    <label className="space-y-2">
                      <span className="text-sm font-medium text-slate-700">Período</span>
                      <select
                        value={form.interval_unit}
                        onChange={(event) =>
                          setForm((current) => ({
                            ...current,
                            interval_unit: event.target.value as "days" | "months" | "years",
                          }))
                        }
                        className={fieldClass}
                      >
                        <option value="days">Dias</option>
                        <option value="months">Meses</option>
                        <option value="years">Anos</option>
                      </select>
                    </label>
                  </>
                ) : null}

                <div className="space-y-3 md:col-span-2">
                  <div className="text-sm font-medium text-slate-700">Meios de pagamento</div>
                  <div className="grid gap-3 md:grid-cols-3">
                    <label className="flex items-center gap-3 rounded-xl border border-slate-200 p-3 text-sm text-slate-700">
                      <input
                        type="checkbox"
                        checked={form.allow_credit_card}
                        onChange={(event) => setForm((current) => ({ ...current, allow_credit_card: event.target.checked }))}
                      />
                      Cartão
                    </label>
                    <label className="flex items-center gap-3 rounded-xl border border-slate-200 p-3 text-sm text-slate-700">
                      <input
                        type="checkbox"
                        checked={form.allow_pix}
                        disabled={form.type === "subscription"}
                        onChange={(event) => setForm((current) => ({ ...current, allow_pix: event.target.checked }))}
                      />
                      Pix
                    </label>
                    <label className="flex items-center gap-3 rounded-xl border border-slate-200 p-3 text-sm text-slate-700">
                      <input
                        type="checkbox"
                        checked={form.allow_boleto}
                        disabled={form.type === "subscription"}
                        onChange={(event) => setForm((current) => ({ ...current, allow_boleto: event.target.checked }))}
                      />
                      Boleto
                    </label>
                  </div>
                  {form.type === "subscription" ? (
                    <div className="rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800">
                      Assinaturas recorrentes usam cartão tokenizado no checkout para criar a cobrança automática.
                    </div>
                  ) : null}
                </div>

                <label className="flex items-start gap-3 rounded-xl border border-slate-200 bg-white p-3 text-sm text-slate-700 md:col-span-2">
                  <input
                    type="checkbox"
                    checked={form.show_cookie_banner}
                    onChange={(event) => setForm((current) => ({ ...current, show_cookie_banner: event.target.checked }))}
                    className="mt-0.5"
                  />
                  <div className="min-w-0">
                    <div className="font-medium text-slate-900">Exibir aviso de cookies</div>
                    <div className="mt-0.5 text-xs text-slate-500">
                      Exibe o banner de cookies no checkout do link (com preferências e opção de fechar).
                    </div>
                  </div>
                </label>
              </div>
            )}
          </div>

          <DialogFooter className="shrink-0 border-t border-slate-200 px-4 py-4 pb-[calc(1rem+env(safe-area-inset-bottom))] sm:px-5 sm:py-4">
            <button
              type="button"
              onClick={closeDialog}
              className="inline-flex h-10 items-center justify-center rounded-xl border border-slate-200 bg-white px-4 text-sm font-medium text-slate-700 transition hover:bg-slate-50"
            >
              Cancelar
            </button>
            <button
              type="button"
              onClick={() => void handleSave()}
              disabled={saving}
              className="inline-flex h-10 items-center justify-center rounded-xl bg-violet-600 px-4 text-sm font-semibold text-white transition hover:bg-violet-700 disabled:opacity-50"
            >
              {saving ? "Salvando..." : form.id ? "Salvar alterações" : "Criar link"}
            </button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={whatsDialogOpen} onOpenChange={(open) => (open ? setWhatsDialogOpen(true) : closeWhatsAppDialog())}>
        <DialogContent className="w-[96vw] max-w-[520px] overflow-visible rounded-2xl border-slate-200 p-0">
          <DialogHeader className="border-b border-slate-200 px-5 py-4">
            <DialogTitle>Enviar no WhatsApp</DialogTitle>
            <DialogDescription>
              Envie o link de pagamento diretamente para um número de WhatsApp.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 px-5 py-4">
            <label className="space-y-2">
              <span className="text-sm font-medium text-slate-700">Número</span>
              <Input
                value={whatsNumber}
                onChange={(event) => setWhatsNumber(event.target.value)}
                placeholder="Ex: 55 11 99999-9999"
              />
            </label>

            <label className="space-y-2">
              <span className="text-sm font-medium text-slate-700">Mensagem</span>
              <textarea
                value={whatsMessage}
                onChange={(event) => setWhatsMessage(event.target.value)}
                className={`${textareaClass} min-h-[96px]`}
                rows={4}
              />
            </label>
          </div>

          <DialogFooter className="border-t border-slate-200 px-5 py-4">
            <button
              type="button"
              onClick={closeWhatsAppDialog}
              className="inline-flex h-10 items-center justify-center rounded-xl border border-slate-200 bg-white px-4 text-sm font-medium text-slate-700 transition hover:bg-slate-50"
            >
              Cancelar
            </button>
            <button
              type="button"
              onClick={() => {
                if (!whatsTargetLink) return;
                const digits = normalizePhoneDigits(whatsNumber);
                if (!digits) {
                  setFeedback({ type: "error", text: "Informe um numero de WhatsApp valido." });
                  return;
                }
                openWhatsApp(whatsTargetLink, digits);
                closeWhatsAppDialog();
              }}
              className="inline-flex h-10 items-center justify-center gap-2 rounded-xl bg-emerald-600 px-4 text-sm font-semibold text-white transition hover:bg-emerald-700"
            >
              <WhatsAppIcon className="h-4 w-4" />
              Enviar
            </button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog
        open={whatsTemplateModalOpen}
        onOpenChange={(open) => {
          if (open) setWhatsTemplateModalOpen(true);
          else setWhatsTemplateModalOpen(false);
        }}
      >
        <DialogContent className="w-[96vw] max-w-[560px] overflow-visible rounded-2xl border-slate-200 p-0">
          <DialogHeader className="border-b border-slate-200 px-5 py-4">
            <DialogTitle>Mensagem de envio do link</DialogTitle>
            <DialogDescription>
              Texto padrão usado ao enviar o link pelo WhatsApp.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-3 px-5 py-4">
            <textarea
              value={whatsTemplateDraft}
              onChange={(event) => setWhatsTemplateDraft(event.target.value)}
              placeholder="Ex: Olá{cliente_saudaçao}! Segue seu link de pagamento: {link}"
              className="min-h-[140px] w-full rounded-xl border border-slate-200 bg-white px-3 py-3 text-sm text-slate-900 outline-none transition focus:border-violet-500"
              rows={6}
            />
            <div className="text-xs text-slate-500">
              Variáveis: {"{link}"} {"{titulo}"} {"{valor}"} {"{codigo}"} {"{cliente}"} {"{loja}"} {"{cliente_saudaçao}"}
            </div>
          </div>

          <DialogFooter className="border-t border-slate-200 px-5 py-4">
            <button
              type="button"
              onClick={() => setWhatsTemplateModalOpen(false)}
              className="inline-flex h-10 items-center justify-center rounded-xl border border-slate-200 bg-white px-4 text-sm font-medium text-slate-700 transition hover:bg-slate-50"
            >
              Cancelar
            </button>
            <button
              type="button"
              onClick={() => void handleSaveLinkSettings()}
              disabled={!selectedLink || settingsSaving}
              className="ks-button ks-button-primary disabled:opacity-50"
            >
              Salvar
            </button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <CaixaDeConfirmacao
        pedido={confirmacao}
        ocupado={Boolean(deletingId)}
        aoFechar={() => setConfirmacao(null)}
      />
    </div>
  );
}
