import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { supabase } from "@/integrations/supabase/client";

export const Route = createFileRoute("/_authenticated/painel")({
  head: () => ({
    meta: [
      { title: "Painel de contatos — Pilates Vida Leve" },
      { name: "description", content: "Lista de pessoas que pediram os 7 dias grátis." },
      { property: "og:title", content: "Painel de contatos — Pilates Vida Leve" },
      { property: "og:description", content: "Lista de contatos." },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary" },
      { name: "robots", content: "noindex" },
    ],
  }),
  component: Painel,
});

const MSG = (n: string) => `Olá, ${n.split(" ")[0]}! Aqui é do Pilates Vida Leve 😊 Vi que você pediu os 7 dias grátis de Pilates em casa. Vou te enviar o arquivo da promoção!`;

function waLink(phone: string, name: string) {
  const d = phone.replace(/\D/g, "");
  const full = d.length <= 11 ? `55${d}` : d;
  return `https://wa.me/${full}?text=${encodeURIComponent(MSG(name))}`;
}
function fmtPhone(p: string) {
  const d = p.replace(/\D/g, "").replace(/^55(?=\d{10,11}$)/, "");
  return d.length === 11 ? `(${d.slice(0, 2)}) ${d.slice(2, 7)}-${d.slice(7)}` : d.length === 10 ? `(${d.slice(0, 2)}) ${d.slice(2, 6)}-${d.slice(6)}` : p;
}

function Painel() {
  const qc = useQueryClient();
  const navigate = useNavigate();
  const { data: isAdmin } = useQuery({
    queryKey: ["isAdmin"],
    queryFn: async () => {
      const { data: u } = await supabase.auth.getUser();
      const { data } = await supabase.from("user_roles").select("role").eq("user_id", u.user!.id).eq("role", "admin");
      return (data?.length ?? 0) > 0;
    },
  });
  const { data: leads = [], isLoading } = useQuery({
    queryKey: ["leads"],
    enabled: isAdmin === true,
    queryFn: async () => {
      const { data, error } = await supabase.from("trial_leads").select("*").order("created_at", { ascending: false });
      if (error) throw error;
      return data;
    },
  });

  async function toggle(id: string, contacted: boolean) {
    await supabase.from("trial_leads").update({ contacted }).eq("id", id);
    qc.invalidateQueries({ queryKey: ["leads"] });
  }
  async function remove(id: string) {
    if (!confirm("Excluir este contato?")) return;
    await supabase.from("trial_leads").delete().eq("id", id);
    qc.invalidateQueries({ queryKey: ["leads"] });
  }
  async function signOut() {
    await qc.cancelQueries(); qc.clear();
    await supabase.auth.signOut();
    navigate({ to: "/auth", replace: true });
  }

  const pending = leads.filter((l) => !l.contacted).length;

  return (
    <main className="mx-auto min-h-screen max-w-3xl px-5 py-8">
      <header className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-primary">Meus contatos</h1>
          {isAdmin && <p className="mt-1 text-muted-foreground">{leads.length} no total · <b className="text-accent">{pending} para chamar</b></p>}
        </div>
        <button onClick={signOut} className="rounded-full border px-4 py-2 text-sm font-semibold">Sair</button>
      </header>

      {isAdmin === false && <p className="mt-10 rounded-2xl bg-card p-6 text-muted-foreground">Esta conta não tem acesso ao painel.</p>}
      {isAdmin && isLoading && <p className="mt-10 text-muted-foreground">Carregando...</p>}
      {isAdmin && !isLoading && leads.length === 0 && <p className="mt-10 rounded-2xl bg-card p-6 text-muted-foreground">Ainda ninguém preencheu o formulário. Os contatos aparecem aqui.</p>}

      <ul className="mt-8 space-y-3">
        {leads.map((l) => (
          <li key={l.id} className={`rounded-2xl border bg-card p-5 shadow-sm ${l.contacted ? "opacity-60" : ""}`}>
            <div className="flex flex-wrap items-start justify-between gap-3">
              <div>
                <p className="text-lg font-bold">{l.name}</p>
                <p className="text-muted-foreground">{fmtPhone(l.phone)}</p>
                <p className="text-xs text-muted-foreground">{new Date(l.created_at).toLocaleString("pt-BR", { dateStyle: "short", timeStyle: "short" })}</p>
              </div>
              {l.contacted && <span className="rounded-full bg-secondary px-3 py-1 text-xs font-bold text-secondary-foreground">Já chamei</span>}
            </div>
            <div className="mt-4 flex flex-wrap gap-2">
              <a href={waLink(l.phone, l.name)} target="_blank" rel="noopener noreferrer" onClick={() => !l.contacted && toggle(l.id, true)}
                className="rounded-full bg-whatsapp px-5 py-2.5 text-sm font-bold text-whatsapp-foreground">Chamar no WhatsApp</a>
              <button onClick={() => toggle(l.id, !l.contacted)} className="rounded-full border px-4 py-2.5 text-sm font-semibold">
                {l.contacted ? "Marcar como não chamado" : "Marcar como chamado"}
              </button>
              <button onClick={() => remove(l.id)} className="rounded-full px-4 py-2.5 text-sm font-semibold text-destructive">Excluir</button>
            </div>
          </li>
        ))}
      </ul>
    </main>
  );
}
