import { Link } from "@tanstack/react-router";
import { ArrowUpRight, Heart, Stethoscope, Building2, Handshake, Mic2, CalendarCheck, X, Globe } from "lucide-react";
import { useEffect, useState, type ReactNode } from "react";

type Item = {
  to: string;
  label: string;
  description: string;
  icon: ReactNode;
  accent: string; // css var name
  tone: "soft" | "gold";
};

const items: Item[] = [
  {
    to: "/solucoes/mind-family",
    label: "Mind Family",
    description:
      "Plataforma de autoconhecimento, saúde emocional e bem-estar para fortalecer pessoas, famílias e organizações.",
    icon: <Heart className="h-5 w-5" />,
    accent: "--mind-b",
    tone: "soft",
  },
  {
    to: "/acesso/empresa",
    label: "Safe Company / Empresas / RH",
    description:
      "Transforme a NR-1 em prevenção com gestão inteligente dos riscos psicossociais.",
    icon: <Building2 className="h-5 w-5" />,
    accent: "--safe",
    tone: "soft",
  },
  {
    to: "/solucoes/palestras",
    label: "Palestras / Workshops",
    description:
      "Leve conhecimento, prevenção e mudança de comportamento para sua equipe.",
    icon: <Mic2 className="h-5 w-5" />,
    accent: "--safe-gold",
    tone: "soft",
  },
  {
    to: "/acesso/parceiro",
    label: "Parceiro Comercial",
    description:
      "Cadastre empresas, acompanhe oportunidades e impulsione seus resultados.",
    icon: <Handshake className="h-5 w-5" />,
    accent: "--partner",
    tone: "soft",
  },
  {
    to: "/acesso/profissional-saude",
    label: "Profissionais de Saúde",
    description:
      "Portal exclusivo para gestão de pacientes, atendimentos e ferramentas clínicas.",
    icon: <Stethoscope className="h-5 w-5" />,
    accent: "--life",
    tone: "soft",
  },
  {
    to: "/acesso/colaborador",
    label: "Marcação de Consultas",
    description:
      "Escolha o profissional, agende seu atendimento e cuide da sua saúde com praticidade.",
    icon: <CalendarCheck className="h-5 w-5" />,
    accent: "--life-soft",
    tone: "soft",
  },
];

type Props = {
  triggerClassName?: string;
  mobile?: boolean;
};

export function AccessDrawer({ triggerClassName, mobile }: Props) {
  const [open, setOpen] = useState(false);

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => e.key === "Escape" && setOpen(false);
    if (open) {
      document.addEventListener("keydown", onKey);
      document.body.style.overflow = "hidden";
    }
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open]);

  return (
    <>
      <button
        type="button"
        onClick={() => setOpen(true)}
        className={
          triggerClassName ??
          "group inline-flex items-center gap-2 rounded-full bg-gradient-to-r from-[color:var(--safe)] to-[color:oklch(0.32_0.06_245)] px-5 py-2.5 text-sm font-semibold text-white shadow-[0_8px_24px_-12px_var(--safe)] transition-all hover:shadow-[0_12px_32px_-10px_var(--safe)]"
        }
        aria-haspopup="dialog"
        aria-expanded={open}
      >
        <Globe className="h-4 w-4" />
        Ecossistema
        {!mobile && (
          <span className="ml-1 hidden h-4 w-px bg-white/30 xl:block" aria-hidden />
        )}
      </button>

      {/* Backdrop */}
      <div
        onClick={() => setOpen(false)}
        className={`fixed inset-0 z-[60] bg-[color:var(--safe)]/40 backdrop-blur-sm transition-opacity duration-300 ${
          open ? "opacity-100" : "pointer-events-none opacity-0"
        }`}
        aria-hidden
      />

      {/* Panel */}
      <aside
        role="dialog"
        aria-modal="true"
        aria-label="Áreas de acesso"
        className={`fixed right-0 top-0 z-[70] flex h-[100dvh] w-full max-w-[440px] flex-col bg-background shadow-2xl transition-transform duration-500 ease-[cubic-bezier(0.22,1,0.36,1)] ${
          open ? "translate-x-0" : "translate-x-full"
        }`}
      >
        {/* Header */}
        <div className="relative overflow-hidden bg-gradient-to-br from-[color:var(--safe)] to-[color:oklch(0.22_0.05_245)] px-7 pb-8 pt-7 text-white">
          <div
            className="pointer-events-none absolute -right-10 -top-10 h-48 w-48 rounded-full bg-[color:var(--life)]/30 blur-3xl"
            aria-hidden
          />
          <div
            className="pointer-events-none absolute -bottom-16 left-10 h-40 w-40 rounded-full bg-[color:var(--safe-gold)]/25 blur-3xl"
            aria-hidden
          />
          <button
            onClick={() => setOpen(false)}
            className="absolute right-5 top-5 grid h-9 w-9 place-items-center rounded-full bg-white/10 text-white transition hover:bg-white/20"
            aria-label="Fechar"
          >
            <X className="h-4 w-4" />
          </button>
          <p className="text-[11px] font-semibold uppercase tracking-[0.22em] text-white/70">
            Ecossistema · Instituto Vida Segura
          </p>
          <h2 className="mt-3 font-fraunces text-3xl leading-tight">
            Escolha por onde<br />
            <span className="italic text-[color:var(--life)]">você entra</span>
          </h2>
          <p className="mt-2 text-sm text-white/75">
            Seis caminhos, uma mesma missão: transformar vidas e empresas.
          </p>
        </div>

        {/* Items */}
        <div className="flex-1 overflow-y-auto px-5 py-6">
          <ul className="grid gap-3">
            {items.map((it, i) => {
              const isGold = it.tone === "gold";
              return (
                <li
                  key={it.to + it.label}
                  style={{
                    transitionDelay: open ? `${120 + i * 70}ms` : "0ms",
                  }}
                  className={`transform transition-all duration-500 ${
                    open ? "translate-x-0 opacity-100" : "translate-x-6 opacity-0"
                  }`}
                >
                  <Link
                    to={it.to}
                    onClick={() => setOpen(false)}
                    className={`group relative flex items-start gap-4 overflow-hidden rounded-2xl border p-4 transition-all hover:-translate-y-0.5 ${
                      isGold
                        ? "border-[color:var(--safe-gold)]/40 bg-gradient-to-br from-[color:var(--safe-gold)]/15 to-[color:var(--safe-gold)]/5 hover:border-[color:var(--safe-gold)]/70"
                        : "border-border bg-card hover:border-[color:var(--accent-color)]/60"
                    }`}
                  >
                    <span
                      aria-hidden
                      className="pointer-events-none absolute inset-y-0 left-0 w-1 origin-top scale-y-0 transition-transform duration-300 group-hover:scale-y-100"
                      style={{ background: `var(${it.accent})` }}
                    />
                    <span
                      className="grid h-11 w-11 shrink-0 place-items-center rounded-xl text-white shadow-sm"
                      style={{
                        background: `linear-gradient(135deg, var(${it.accent}), color-mix(in oklab, var(${it.accent}) 70%, white))`,
                      }}
                    >
                      {it.icon}
                    </span>
                    <div className="min-w-0 flex-1">
                      <div className="flex items-center justify-between gap-2">
                        <h3 className="font-fraunces text-lg leading-tight text-foreground">
                          {it.label}
                        </h3>
                        <ArrowUpRight
                          className="h-4 w-4 shrink-0 text-muted-foreground transition-all group-hover:-translate-y-0.5 group-hover:translate-x-0.5"
                          style={{ color: `var(${it.accent})` }}
                        />
                      </div>
                      <p className="mt-1 text-[13px] leading-relaxed text-muted-foreground">
                        {it.description}
                      </p>
                    </div>
                  </Link>
                </li>
              );
            })}
          </ul>

          <div className="mt-6 rounded-2xl border border-dashed border-border bg-muted/30 p-4 text-center">
            <p className="text-xs text-muted-foreground">
              Não sabe por onde começar?{" "}
              <Link
                to="/contato"
                onClick={() => setOpen(false)}
                className="font-semibold text-[color:var(--safe)] underline-offset-2 hover:underline"
              >
                Fale com a gente
              </Link>
            </p>
          </div>
        </div>
      </aside>
    </>
  );
}
