"use client";

import { usePermissoes } from "@/lib/permissoes-do-usuario";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { AnimatePresence, motion } from "framer-motion";
import { getSupabaseClient } from "@/lib/supabase";
import {
  MessageCircle,
  Save,
  Loader2,
  CheckCircle2,
  AlertCircle,
  RotateCcw,
  ShoppingBag,
  FileText,
  Package,
  ChevronDown,
  ChevronUp,
  Eye,
  EyeOff,
  Info,
  Copy,
  Check,
} from "lucide-react";
import { PageHeader } from "@/components/ui/page-header";

/* ------------------------------------------------------------------ */
/*  Template types                                                     */
/* ------------------------------------------------------------------ */
interface TemplateConfig {
  product_inquiry: string;
  cart_checkout_header: string;
  cart_checkout_footer: string;
  quote_share: string;
  order_status: string;
}

interface TemplateDefinition {
  key: keyof TemplateConfig;
  label: string;
  description: string;
  icon: typeof MessageCircle;
  shortcodes: { code: string; label: string }[];
  defaultValue: string;
  previewBuilder: (template: string) => string;
}

/* ------------------------------------------------------------------ */
/*  Default templates (match existing code)                            */
/* ------------------------------------------------------------------ */
const DEFAULTS: TemplateConfig = {
  product_inquiry:
    "Olá! Tenho interesse no produto {{nome_produto}}",
  cart_checkout_header: "*Novo Pedido*",
  cart_checkout_footer:
    "{{resumo_itens}}\n\n{{subtotal}}\n{{desconto}}\n*Total: {{total}}*",
  quote_share:
    "Olá! Segue o orçamento #{{numero_orcamento}}. Total: {{total}}.{{validade}} {{link}}",
  order_status:
    "Olá! Segue atualização sobre seu pedido #{{numero_pedido}}. Status atual: *{{status}}*. Acompanhe o progresso em tempo real: {{link}}",
};

/* ------------------------------------------------------------------ */
/*  Templates definition                                               */
/* ------------------------------------------------------------------ */
const TEMPLATE_DEFS: TemplateDefinition[] = [
  {
    key: "product_inquiry",
    label: "Dúvidas sobre Produto",
    description:
      'Mensagem enviada quando o cliente clica em "Tirar dúvidas no WhatsApp" na página do produto no catálogo.',
    icon: ShoppingBag,
    shortcodes: [
      { code: "{{nome_produto}}", label: "Nome do produto" },
    ],
    defaultValue: DEFAULTS.product_inquiry,
    previewBuilder: (t) =>
      t.replace("{{nome_produto}}", "Adesivo Vinílico Premium"),
  },
  {
    key: "cart_checkout_header",
    label: "Carrinho — Cabeçalho",
    description:
      "Cabeçalho da mensagem quando o cliente finaliza o pedido pelo carrinho no catálogo. Os itens do carrinho são inseridos automaticamente abaixo.",
    icon: ShoppingBag,
    shortcodes: [],
    defaultValue: DEFAULTS.cart_checkout_header,
    previewBuilder: (t) =>
      `${t}\n\n2x Adesivo Vinílico - R$ 50,00\n1x Papel Fotográfico - R$ 25,00`,
  },
  {
    key: "cart_checkout_footer",
    label: "Carrinho — Rodapé / Resumo",
    description:
      "Rodapé da mensagem do carrinho com o resumo de valores. Os itens já estarão listados acima.",
    icon: ShoppingBag,
    shortcodes: [
      { code: "{{resumo_itens}}", label: "Lista de itens (automático)" },
      { code: "{{subtotal}}", label: "Subtotal formatado" },
      { code: "{{desconto}}", label: "Desconto (se houver cupom)" },
      { code: "{{total}}", label: "Valor total formatado" },
    ],
    defaultValue: DEFAULTS.cart_checkout_footer,
    previewBuilder: (t) =>
      t
        .replace("{{resumo_itens}}", "2x Adesivo Vinílico - R$ 50,00\n1x Papel Fotográfico - R$ 25,00")
        .replace("{{subtotal}}", "Subtotal: R$ 75,00")
        .replace("{{desconto}}", "Desconto (PROMO10): -R$ 7,50")
        .replace("{{total}}", "R$ 67,50"),
  },
  {
    key: "quote_share",
    label: "Compartilhar Orçamento",
    description:
      "Mensagem enviada quando você compartilha um orçamento pelo WhatsApp com o cliente.",
    icon: FileText,
    shortcodes: [
      { code: "{{numero_orcamento}}", label: "Número do orçamento" },
      { code: "{{total}}", label: "Valor total formatado" },
      { code: "{{validade}}", label: "Data de validade (se definida)" },
      { code: "{{condicoes}}", label: "Condições de pagamento (se definidas)" },
      { code: "{{link}}", label: "Link público do orçamento" },
    ],
    defaultValue: DEFAULTS.quote_share,
    previewBuilder: (t) =>
      t
        .replace("{{numero_orcamento}}", "42")
        .replace("{{total}}", "R$ 1.500,00")
        .replace("{{validade}}", " Validade: 15/03/2025.")
        .replace("{{condicoes}}", " Pagamento: Entrada de 50% (R$ 750,00) na aprovação e saldo na entrega. Pix ou cartão de crédito.")
        .replace("{{link}}", "https://loja.ktalogu.com/minha-loja/o/abc123"),
  },
  {
    key: "order_status",
    label: "Atualização de Pedido",
    description:
      "Mensagem enviada quando você envia uma atualização de status do pedido para o cliente via WhatsApp.",
    icon: Package,
    shortcodes: [
      { code: "{{numero_pedido}}", label: "Número do pedido" },
      { code: "{{status}}", label: "Status atual do pedido" },
      { code: "{{link}}", label: "Link de acompanhamento" },
    ],
    defaultValue: DEFAULTS.order_status,
    previewBuilder: (t) =>
      t
        .replace("{{numero_pedido}}", "15")
        .replace("{{status}}", "Em Produção")
        .replace("{{link}}", "https://loja.ktalogu.com/minha-loja/status/abc123"),
  },
];

/* ------------------------------------------------------------------ */
/*  Shortcode Badge component                                          */
/* ------------------------------------------------------------------ */
function ShortcodeBadge({
  code,
  label,
  onInsert,
}: {
  code: string;
  label: string;
  onInsert: (code: string) => void;
}) {
  const [copied, setCopied] = useState(false);
  return (
    <button
      type="button"
      onClick={() => {
        onInsert(code);
        setCopied(true);
        setTimeout(() => setCopied(false), 1200);
      }}
      className="group inline-flex items-center gap-1.5 rounded-lg border border-[var(--ks-color-primary)]/20 bg-[var(--ks-color-primary)]/5 px-2.5 py-1.5 text-xs font-semibold text-[var(--ks-color-primary-strong)] transition-all hover:bg-[var(--ks-color-primary)]/10 hover:border-[var(--ks-color-primary)]/40 hover:shadow-sm active:scale-[0.97]"
      title={`Clique para inserir ${code}`}
    >
      <code className="font-mono text-[11px] bg-white/60 rounded px-1 py-0.5 border border-[var(--ks-color-primary)]/10">
        {code}
      </code>
      <span className="text-[10px] text-[var(--ks-color-text-muted)] hidden sm:inline">{label}</span>
      {copied ? (
        <Check size={12} className="text-emerald-500" />
      ) : (
        <Copy size={12} className="opacity-40 group-hover:opacity-70" />
      )}
    </button>
  );
}

/* ------------------------------------------------------------------ */
/*  Template card component                                            */
/* ------------------------------------------------------------------ */
function TemplateCard({
  def,
  value,
  onChange,
}: {
  def: TemplateDefinition;
  value: string;
  onChange: (value: string) => void;
}) {
  const [expanded, setExpanded] = useState(false);
  const [showPreview, setShowPreview] = useState(false);
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  const Icon = def.icon;
  const isModified = value !== def.defaultValue;
  const preview = def.previewBuilder(value);

  const insertShortcode = useCallback(
    (code: string) => {
      const ta = textareaRef.current;
      if (!ta) {
        onChange(value + code);
        return;
      }
      const start = ta.selectionStart;
      const end = ta.selectionEnd;
      const newValue = value.slice(0, start) + code + value.slice(end);
      onChange(newValue);
      requestAnimationFrame(() => {
        ta.focus();
        const pos = start + code.length;
        ta.setSelectionRange(pos, pos);
      });
    },
    [onChange, value]
  );

  const autoResize = useCallback(() => {
    const ta = textareaRef.current;
    if (!ta) return;
    ta.style.height = "auto";
    ta.style.height = `${Math.max(80, ta.scrollHeight)}px`;
  }, []);

  useEffect(() => {
    if (expanded) autoResize();
  }, [expanded, value, autoResize]);

  return (
    <div className="bg-white rounded-2xl border border-zinc-200/80 shadow-sm overflow-hidden transition-all hover:shadow-md">
      {/* Header */}
      <button
        type="button"
        onClick={() => setExpanded(!expanded)}
        className="w-full p-5 flex items-center justify-between text-left hover:bg-zinc-50/50 transition-colors"
      >
        <div className="flex items-center gap-3 min-w-0">
          <div
            className="w-10 h-10 rounded-xl flex items-center justify-center shrink-0"
            style={{ backgroundColor: "var(--ks-color-primary-soft)", color: "var(--ks-color-primary-strong)" }}
          >
            <Icon size={20} />
          </div>
          <div className="min-w-0">
            <div className="flex items-center gap-2 flex-wrap">
              <h3 className="font-bold text-[var(--ks-color-brand-dark)] text-sm sm:text-base">
                {def.label}
              </h3>
              {isModified && (
                <span className="px-2 py-0.5 rounded-full bg-amber-100 text-amber-700 text-[10px] font-bold uppercase tracking-wider">
                  Personalizado
                </span>
              )}
            </div>
            <p className="text-xs text-[var(--ks-color-text-muted)] mt-0.5 line-clamp-1 sm:line-clamp-2">
              {def.description}
            </p>
          </div>
        </div>
        <div className="text-[var(--ks-color-text-muted)] shrink-0 ml-2">
          {expanded ? <ChevronUp size={18} /> : <ChevronDown size={18} />}
        </div>
      </button>

      {/* Body */}
      <AnimatePresence initial={false}>
        {expanded && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: "auto", opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            transition={{ duration: 0.25, ease: [0.25, 0.1, 0.25, 1] }}
            className="overflow-hidden"
          >
            <div className="px-5 pb-5 border-t border-zinc-100 pt-4 space-y-4">
              {/* Shortcodes */}
              {def.shortcodes.length > 0 && (
                <div className="space-y-2">
                  <div className="flex items-center gap-1.5 text-xs font-semibold text-[var(--ks-color-text-muted)] uppercase tracking-wider">
                    <Info size={12} />
                    Variáveis disponíveis — Clique para inserir
                  </div>
                  <div className="flex flex-wrap gap-2">
                    {def.shortcodes.map((sc) => (
                      <ShortcodeBadge
                        key={sc.code}
                        code={sc.code}
                        label={sc.label}
                        onInsert={insertShortcode}
                      />
                    ))}
                  </div>
                </div>
              )}

              {/* Textarea */}
              <div className="space-y-1.5">
                <label className="text-xs font-semibold text-[var(--ks-color-text-muted)] uppercase tracking-wider">
                  Mensagem
                </label>
                <textarea
                  ref={textareaRef}
                  value={value}
                  onChange={(e) => onChange(e.target.value)}
                  onInput={autoResize}
                  rows={3}
                  className="w-full px-4 py-3 rounded-xl border border-zinc-200 focus:outline-none focus:ring-2 focus:ring-[var(--ks-color-primary)]/20 focus:border-[var(--ks-color-primary)] bg-white resize-none text-sm text-[var(--ks-color-brand-dark)] font-medium leading-relaxed transition-shadow"
                  placeholder="Digite a mensagem..."
                />
              </div>

              {/* Actions row */}
              <div className="flex items-center justify-between gap-3 flex-wrap">
                <button
                  type="button"
                  onClick={() => onChange(def.defaultValue)}
                  className="inline-flex items-center gap-1.5 text-xs font-medium text-[var(--ks-color-text-muted)] hover:text-[var(--ks-color-brand-dark)] transition-colors"
                >
                  <RotateCcw size={13} />
                  Restaurar padrão
                </button>
                <button
                  type="button"
                  onClick={() => setShowPreview(!showPreview)}
                  className="inline-flex items-center gap-1.5 text-xs font-semibold text-[var(--ks-color-primary-strong)] hover:text-[var(--ks-color-primary)] transition-colors"
                >
                  {showPreview ? <EyeOff size={13} /> : <Eye size={13} />}
                  {showPreview ? "Ocultar prévia" : "Ver prévia"}
                </button>
              </div>

              {/* Preview */}
              <AnimatePresence>
                {showPreview && (
                  <motion.div
                    initial={{ height: 0, opacity: 0 }}
                    animate={{ height: "auto", opacity: 1 }}
                    exit={{ height: 0, opacity: 0 }}
                    transition={{ duration: 0.2 }}
                    className="overflow-hidden"
                  >
                    <div className="rounded-xl border border-emerald-200 bg-emerald-50/50 p-4 space-y-2">
                      <div className="flex items-center gap-2 text-xs font-semibold text-emerald-700 uppercase tracking-wider">
                        <MessageCircle size={13} />
                        Prévia da mensagem
                      </div>
                      <div className="bg-white rounded-lg p-3 border border-emerald-100 shadow-sm">
                        <p className="text-sm text-zinc-700 whitespace-pre-wrap leading-relaxed font-medium">
                          {preview}
                        </p>
                      </div>
                      <p className="text-[10px] text-emerald-600">
                        As variáveis <code className="font-mono">{"{{}}"}</code> serão substituídas pelos valores reais.
                      </p>
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Main page                                                          */
/* ------------------------------------------------------------------ */
export default function WhatsAppPage() {
  const { pode } = usePermissoes();
  const podeMexerNoWhatsapp = pode("whatsapp.manage");

  const [templates, setTemplates] = useState<TemplateConfig>({ ...DEFAULTS });
  const [savedTemplates, setSavedTemplates] = useState<TemplateConfig>({ ...DEFAULTS });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

  const hasChanges = useMemo(
    () => JSON.stringify(templates) !== JSON.stringify(savedTemplates),
    [templates, savedTemplates]
  );

  useEffect(() => {
    fetchTemplates();
  }, []);

  async function fetchTemplates() {
    try {
      const res = await fetch("/api/whatsapp/templates");
      const data = await res.json();
      if (data.templates && typeof data.templates === "object") {
        const merged = { ...DEFAULTS, ...data.templates };
        setTemplates(merged);
        setSavedTemplates(merged);
      }
    } catch {
      // keep defaults
    } finally {
      setLoading(false);
    }
  }

  async function handleSave() {
    setSaving(true);
    setMessage(null);
    try {
      const res = await fetch("/api/whatsapp/templates", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ templates }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error || "Erro ao salvar.");
      if (data.warning) {
        setMessage({
          type: "error",
          text: data.warning,
        });
      } else {
        setSavedTemplates({ ...templates });
        setMessage({ type: "success", text: "Mensagens salvas com sucesso!" });
      }
    } catch (err) {
      setMessage({
        type: "error",
        text: err instanceof Error ? err.message : "Erro ao salvar.",
      });
    } finally {
      setSaving(false);
    }
  }

  function handleResetAll() {
    setTemplates({ ...DEFAULTS });
  }

  const updateTemplate = useCallback(
    (key: keyof TemplateConfig, value: string) => {
      setTemplates((prev) => ({ ...prev, [key]: value }));
      setMessage(null);
    },
    []
  );

  if (loading) {
    return (
      <div className="space-y-6">
        <PageHeader
          eyebrow="WhatsApp"
          title="Mensagens"
          subtitle="Carregando..."
        />
        <div className="flex items-center justify-center h-64">
          <Loader2 size={24} className="animate-spin text-[var(--ks-color-primary)]" />
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <PageHeader
        eyebrow="WhatsApp"
        title="Mensagens"
        subtitle="Personalize as mensagens enviadas pelo WhatsApp aos seus clientes."
        actions={
          <div className="flex items-center gap-3 flex-wrap">
            {podeMexerNoWhatsapp && (<button
              type="button"
              onClick={handleResetAll}
              className="ks-button ks-button-ghost text-sm"
            >
              <RotateCcw size={16} />
              Restaurar tudo
            </button>)}
            {podeMexerNoWhatsapp && (<button
              type="button"
              onClick={handleSave}
              disabled={saving || !hasChanges}
              className="ks-button ks-button-primary text-sm"
            >
              {saving ? <Loader2 size={16} className="animate-spin" /> : <Save size={16} />}
              Salvar alterações
            </button>)}
          </div>
        }
      />

      {/* Info Banner */}
      <div className="rounded-2xl border border-[var(--ks-color-primary)]/15 bg-gradient-to-r from-[var(--ks-color-primary)]/5 to-transparent p-5">
        <div className="flex items-start gap-3">
          <div
            className="w-10 h-10 rounded-xl flex items-center justify-center shrink-0 mt-0.5"
            style={{ backgroundColor: "var(--ks-color-primary-soft)", color: "var(--ks-color-primary-strong)" }}
          >
            <MessageCircle size={20} />
          </div>
          <div>
            <h2 className="text-sm font-bold text-[var(--ks-color-brand-dark)]">
              Como funciona?
            </h2>
            <p className="text-xs text-[var(--ks-color-text-muted)] mt-1 leading-relaxed max-w-2xl">
              Cada mensagem possui <strong>variáveis</strong> (ex:{" "}
              <code className="font-mono text-[11px] bg-white/80 rounded px-1 py-0.5 border border-zinc-200">
                {"{{nome_produto}}"}
              </code>
              ) que serão substituídas automaticamente pelos valores reais na hora do envio.
              Clique nas variáveis disponíveis para inseri-las no texto, ou digite manualmente.
            </p>
          </div>
        </div>
      </div>

      {/* Feedback */}
      <AnimatePresence>
        {message && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: "auto", opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            transition={{ duration: 0.2 }}
            className="overflow-hidden"
          >
            <div
              className={`p-4 rounded-xl text-sm flex items-center gap-2 font-medium ${
                message.type === "success"
                  ? "bg-emerald-50 text-emerald-700 border border-emerald-100"
                  : "bg-red-50 text-red-700 border border-red-100"
              }`}
            >
              {message.type === "success" ? <CheckCircle2 size={16} /> : <AlertCircle size={16} />}
              {message.text}
            </div>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Template Cards */}
      <div className="space-y-4">
        {/* Section: Catálogo Público */}
        <div className="space-y-3">
          <h3 className="text-xs font-bold text-[var(--ks-color-text-muted)] uppercase tracking-widest flex items-center gap-2 px-1">
            <ShoppingBag size={14} />
            Catálogo Público
          </h3>
          {TEMPLATE_DEFS.filter((d) =>
            ["product_inquiry", "cart_checkout_header", "cart_checkout_footer"].includes(d.key)
          ).map((def) => (
            <TemplateCard
              key={def.key}
              def={def}
              value={templates[def.key]}
              onChange={(v) => updateTemplate(def.key, v)}
            />
          ))}
        </div>

        {/* Section: Orçamentos & Pedidos */}
        <div className="space-y-3 pt-4">
          <h3 className="text-xs font-bold text-[var(--ks-color-text-muted)] uppercase tracking-widest flex items-center gap-2 px-1">
            <FileText size={14} />
            Orçamentos & Pedidos
          </h3>
          {TEMPLATE_DEFS.filter((d) =>
            ["quote_share", "order_status"].includes(d.key)
          ).map((def) => (
            <TemplateCard
              key={def.key}
              def={def}
              value={templates[def.key]}
              onChange={(v) => updateTemplate(def.key, v)}
            />
          ))}
        </div>
      </div>

      {/* Sticky save bar for mobile */}
      <AnimatePresence>
        {hasChanges && (
          <motion.div
            initial={{ y: 80, opacity: 0 }}
            animate={{ y: 0, opacity: 1 }}
            exit={{ y: 80, opacity: 0 }}
            transition={{ duration: 0.25 }}
            className="fixed bottom-0 left-0 right-0 z-50 md:hidden p-4 bg-white/95 backdrop-blur-sm border-t border-zinc-200 shadow-[0_-4px_20px_rgba(0,0,0,0.08)]"
          >
            {podeMexerNoWhatsapp && (<button
              type="button"
              onClick={handleSave}
              disabled={saving}
              className="w-full py-3 rounded-xl font-bold text-white text-sm flex items-center justify-center gap-2 bg-[var(--ks-color-primary)] hover:bg-[var(--ks-color-primary-strong)] disabled:opacity-60 transition-all active:scale-[0.98]"
            >
              {saving ? <Loader2 size={16} className="animate-spin" /> : <Save size={16} />}
              Salvar alterações
            </button>)}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
