"use client";

import { useEffect, useState } from "react";
import { Bookmark, Check, ChevronRight, Pencil, Trash2, Wand2, X } from "lucide-react";
import { NOME_DO_MODO, RESUMO_DO_MODO, ehFamiliaVendor, ehModo, type Modo, type SecaoDoEditor, type Tema } from "@/lib/pagina-inicial";
import { DesenhoDoModo, SeloDoModo } from "./icones";

/* Um bloco de "Meus blocos" (catalog_blocos_salvos, migration 199). */
export type BlocoSalvo = {
  id: string;
  nome: string;
  modo: string;
  secao: Record<string, unknown>;
  produtos: string[];
  created_at: string;
};

/*
  Os tipos de seção para pôr na página, em três famílias. Tocou, entra no
  lugar escolhido (depois da seção escolhida, ou onde a pessoa tocou no "+"
  da loja) e já abre os ajustes dela.
*/

const FAMILIAS: Array<{ nome: string; modos: Modo[] }> = [
  { nome: "Imagens", modos: ["image_banner", "banner_carousel", "image_grid", "shoppable_image", "before_after"] },
  {
    nome: "Produtos",
    modos: ["manual_products", "category_products", "subcategory_products", "featured_products", "auto_list", "combo_highlight", "recently_viewed", "all_products"],
  },
  { nome: "Vendas e avisos", modos: ["flash_offer", "coupon_highlight", "order_cutoff", "next_live", "marquee"] },
  { nome: "Conteúdo", modos: ["text_image", "video_section", "faq", "store_location"] },
  { nome: "Navegação", modos: ["category_navigator", "category_circles"] },
];

/* "Próxima live" só aparece para a empresa com a área de produtos digitais
   (as lives moram lá): a mesma resposta que o menu lateral lê. */
let livesDaEmpresa: Promise<boolean> | null = null;
function useLivesLiberadas() {
  const [liberadas, setLiberadas] = useState(false);
  useEffect(() => {
    let vivo = true;
    livesDaEmpresa ??= fetch("/api/company/users", { method: "GET" })
      .then(async (r) => r.ok && ((await r.json().catch(() => null)) as { recursos?: { digitais?: unknown } } | null)?.recursos?.digitais === true)
      .catch(() => false);
    livesDaEmpresa.then((sim) => {
      if (vivo) setLiberadas(sim);
    });
    return () => {
      vivo = false;
    };
  }, []);
  return liberadas;
}

export function PaletaDeSecoes({
  secoes,
  tema,
  lugar,
  aoEscolher,
  aoCancelarLugar,
  blocos,
  aoInserirBloco,
  aoRenomearBloco,
  aoApagarBloco,
  aoAbrirModelos,
}: {
  secoes: SecaoDoEditor[];
  tema: Tema;
  /* "na posição 3", quando veio do "+" da loja. */
  lugar: string | null;
  aoEscolher: (modo: Modo) => void;
  aoCancelarLugar?: () => void;
  /* Meus blocos (null = ainda lendo) e os modelos prontos. */
  blocos?: BlocoSalvo[] | null;
  aoInserirBloco?: (bloco: BlocoSalvo) => void;
  aoRenomearBloco?: (bloco: BlocoSalvo, nome: string) => void;
  aoApagarBloco?: (bloco: BlocoSalvo) => void;
  aoAbrirModelos?: () => void;
}) {
  const temGrade = secoes.some((s) => s.modo === "all_products" && s.ativa);
  const livesLiberadas = useLivesLiberadas();
  return (
    <div className="h-full overflow-y-auto px-4 pb-6 pt-4">
      {aoAbrirModelos ? (
        <button
          type="button"
          onClick={aoAbrirModelos}
          className="group mb-4 flex w-full items-center gap-3 rounded-2xl p-3 text-left text-white shadow-[0_12px_28px_-14px_rgba(91,47,214,0.8)] transition hover:brightness-110"
          style={{ background: "linear-gradient(135deg,#7346e8,#4c1fc2)" }}
        >
          <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-white/15">
            <Wand2 size={18} />
          </span>
          <span className="min-w-0 flex-1">
            <span className="block text-[13px] font-extrabold">Modelos prontos</span>
            <span className="block text-[11px] leading-[1.35] text-white/80">Gráfica, brindes, comunicação visual: a página montada com os seus dados.</span>
          </span>
          <ChevronRight size={16} className="shrink-0 opacity-80 transition group-hover:translate-x-0.5" />
        </button>
      ) : null}
      {blocos && blocos.length && aoInserirBloco ? (
        <div className="mb-4">
          <p className="mb-1.5 px-1 text-[10px] font-bold uppercase tracking-[0.16em] text-[var(--ks-color-text-soft)]">Meus blocos</p>
          <div className="space-y-1">
            {blocos.map((bloco) => (
              <LinhaDoBloco
                key={bloco.id}
                bloco={bloco}
                bloqueado={bloco.modo === "all_products" && temGrade}
                aoInserir={() => aoInserirBloco(bloco)}
                aoRenomear={aoRenomearBloco ? (nome) => aoRenomearBloco(bloco, nome) : undefined}
                aoApagar={aoApagarBloco ? () => aoApagarBloco(bloco) : undefined}
              />
            ))}
          </div>
        </div>
      ) : blocos && !blocos.length && aoInserirBloco ? (
        <div className="mb-4 flex items-start gap-2.5 rounded-xl bg-[var(--ks-color-bg-inset)] px-3 py-2.5">
          <Bookmark size={15} className="mt-0.5 shrink-0 text-[var(--ks-color-text-soft)]" />
          <p className="text-[11.5px] leading-[1.45] text-[var(--ks-color-text-soft)]">
            <b className="text-[var(--ks-color-text-secondary)]">Meus blocos:</b> nos ajustes de uma seção, toque em &quot;Salvar em Meus blocos&quot; para reaproveitar em qualquer página.
          </p>
        </div>
      ) : null}
      {lugar ? (
        <div className="mb-3 flex items-center justify-between gap-2 rounded-xl bg-[var(--ks-brand-50)] px-3 py-2 text-[12px] font-semibold text-[var(--ks-brand-700)]">
          <span>A seção entra {lugar}.</span>
          {aoCancelarLugar ? (
            <button type="button" onClick={aoCancelarLugar} aria-label="Pôr no lugar de sempre" className="rounded-md p-0.5 hover:bg-white/70">
              <X size={14} />
            </button>
          ) : null}
        </div>
      ) : null}
      {FAMILIAS.map((familia) => (
        <div key={familia.nome} className="mb-4">
          <p className="mb-1.5 px-1 text-[10px] font-bold uppercase tracking-[0.16em] text-[var(--ks-color-text-soft)]">{familia.nome}</p>
          <div className="space-y-1">
            {familia.modos.filter((modo) => modo !== "next_live" || livesLiberadas).map((modo) => {
              const bloqueado = modo === "all_products" && temGrade;
              return (
                <button
                  key={modo}
                  type="button"
                  disabled={bloqueado}
                  onClick={() => aoEscolher(modo)}
                  title={bloqueado ? 'A página já tem "Todos os produtos".' : undefined}
                  className="group flex w-full items-center gap-3 rounded-xl px-2 py-2 text-left transition hover:bg-[var(--ks-color-bg-hover)] disabled:cursor-not-allowed disabled:opacity-40"
                >
                  <SeloDoModo modo={modo} tamanho={34} />
                  <span className="min-w-0 flex-1">
                    <span className="block text-[12.5px] font-bold text-[var(--ks-color-text-primary)]">{NOME_DO_MODO[modo]}</span>
                    <span className="block text-[11px] leading-[1.35] text-[var(--ks-color-text-soft)]">
                      {modo === "all_products" && !ehFamiliaVendor(tema) && temGrade ? "Já está na página." : RESUMO_DO_MODO[modo]}
                    </span>
                  </span>
                  <DesenhoDoModo
                    modo={modo}
                    className="hidden h-8 w-14 shrink-0 text-[var(--ks-n-300)] transition group-hover:text-[var(--ks-brand-400)] xl:block"
                  />
                </button>
              );
            })}
          </div>
        </div>
      ))}
    </div>
  );
}

function LinhaDoBloco({
  bloco,
  bloqueado,
  aoInserir,
  aoRenomear,
  aoApagar,
}: {
  bloco: BlocoSalvo;
  bloqueado: boolean;
  aoInserir: () => void;
  aoRenomear?: (nome: string) => void;
  aoApagar?: () => void;
}) {
  const [editando, setEditando] = useState(false);
  const [nome, setNome] = useState(bloco.nome);
  const modo = ehModo(bloco.modo) ? bloco.modo : null;
  if (editando && aoRenomear) {
    return (
      <form
        className="flex items-center gap-1.5 rounded-xl bg-[var(--ks-color-bg-inset)] px-2 py-1.5"
        onSubmit={(e) => {
          e.preventDefault();
          if (nome.trim()) aoRenomear(nome.trim().slice(0, 80));
          setEditando(false);
        }}
      >
        <input
          autoFocus
          value={nome}
          onChange={(e) => setNome(e.target.value.slice(0, 80))}
          aria-label="Nome do bloco"
          className="h-8 min-w-0 flex-1 rounded-lg border border-[var(--ks-color-border-subtle)] bg-[var(--ks-color-bg-elevated)] px-2.5 text-[12.5px] outline-none focus:border-[var(--ks-color-primary)]"
        />
        <button type="submit" aria-label="Salvar o nome" className="flex h-8 w-8 items-center justify-center rounded-lg text-[var(--ks-color-primary)] hover:bg-white">
          <Check size={15} />
        </button>
        <button
          type="button"
          aria-label="Cancelar"
          onClick={() => {
            setNome(bloco.nome);
            setEditando(false);
          }}
          className="flex h-8 w-8 items-center justify-center rounded-lg text-[var(--ks-color-text-soft)] hover:bg-white"
        >
          <X size={15} />
        </button>
      </form>
    );
  }
  return (
    <div className="group/bloco flex items-center gap-1 rounded-xl transition hover:bg-[var(--ks-color-bg-hover)]">
      <button
        type="button"
        disabled={bloqueado || !modo}
        onClick={aoInserir}
        title={bloqueado ? "A página já tem Todos os produtos." : "Pôr este bloco na página"}
        className="flex min-w-0 flex-1 items-center gap-3 px-2 py-2 text-left disabled:cursor-not-allowed disabled:opacity-40"
      >
        {modo ? <SeloDoModo modo={modo} tamanho={34} /> : <span className="h-[34px] w-[34px] rounded-xl bg-[var(--ks-color-bg-inset)]" />}
        <span className="min-w-0 flex-1">
          <span className="block truncate text-[12.5px] font-bold text-[var(--ks-color-text-primary)]">{bloco.nome}</span>
          <span className="block truncate text-[11px] text-[var(--ks-color-text-soft)]">{modo ? NOME_DO_MODO[modo] : "Tipo que o editor não tem mais"}</span>
        </span>
      </button>
      {aoRenomear ? (
        <button
          type="button"
          aria-label={`Renomear ${bloco.nome}`}
          title="Renomear"
          onClick={() => setEditando(true)}
          className="flex h-8 w-8 items-center justify-center rounded-lg text-[var(--ks-n-300)] opacity-100 transition hover:text-[var(--ks-color-primary)] lg:opacity-0 lg:group-hover/bloco:opacity-100"
        >
          <Pencil size={14} />
        </button>
      ) : null}
      {aoApagar ? (
        <button
          type="button"
          aria-label={`Apagar ${bloco.nome}`}
          title="Apagar"
          onClick={aoApagar}
          className="mr-1 flex h-8 w-8 items-center justify-center rounded-lg text-[var(--ks-n-300)] opacity-100 transition hover:text-rose-600 lg:opacity-0 lg:group-hover/bloco:opacity-100"
        >
          <Trash2 size={14} />
        </button>
      ) : null}
    </div>
  );
}
