"use client";

import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { Popover } from "@/components/ui/popover";
import { useToast } from "@/components/ui/toast";
import { useTheme, type Theme } from "@/components/theme-provider";
import {
  IconActivity,
  IconBuilding,
  IconBug,
  IconCheck,
  IconCreditCard,
  IconDashboard,
  IconFileText,
  IconLogOut,
  IconMonitor,
  IconMoon,
  IconScroll,
  IconSettings,
  IconShield,
  IconSun,
  IconTags,
  IconUsers,
} from "@/components/icons";

type IconComponent = (props: { size?: number; className?: string }) => React.JSX.Element;

const NAV: { href: string; label: string; Icon: IconComponent }[] = [
  { href: "/dashboard",        label: "Tableau de bord",     Icon: IconDashboard },
  { href: "/tenants",          label: "Tenants",             Icon: IconBuilding },
  { href: "/billing",          label: "Abonnements",         Icon: IconCreditCard },
  { href: "/plans",            label: "Plans",               Icon: IconTags },
  { href: "/techniciens",      label: "Techniciens",         Icon: IconUsers },
  { href: "/report-templates", label: "Templates rapports",  Icon: IconFileText },
  { href: "/monitoring",       label: "Monitoring",          Icon: IconActivity },
  { href: "/crashs-mobile",    label: "Crashs mobile",       Icon: IconBug },
  { href: "/activites",        label: "Journal",             Icon: IconScroll },
  { href: "/account/security", label: "Sécurité",            Icon: IconShield },
];

export function BottomDock() {
  const pathname = usePathname();

  return (
    <nav className="mf-dock" aria-label="Navigation principale">
      <div className="mf-dock__inner">
        {NAV.map(({ href, label, Icon }) => {
          const active =
            pathname === href || pathname.startsWith(href + "/");
          return (
            <Link
              key={href}
              href={href}
              className={`mf-dock__item ${active ? "mf-dock__item--active" : ""}`}
              aria-current={active ? "page" : undefined}
            >
              <span className="mf-dock__icon">
                <Icon size={22} />
              </span>
              <span className="mf-dock__label">{label}</span>
            </Link>
          );
        })}
        <AccountDockItem />
      </div>
    </nav>
  );
}

// Bouton "Options" dans le dock — popover thème + déconnexion. Sans ça,
// les actions ne sont accessibles que via le Ctrl+K (palette), ce qui
// rend le panel inutilisable pour qui ne connaît pas le raccourci.
const THEMES: { id: Theme; label: string; Icon: IconComponent }[] = [
  { id: "light", label: "Clair", Icon: IconSun },
  { id: "dark", label: "Sombre", Icon: IconMoon },
  { id: "system", label: "Système", Icon: IconMonitor },
];

function AccountDockItem() {
  const router = useRouter();
  const { toast } = useToast();
  const { theme, setTheme } = useTheme();

  async function handleLogout() {
    try {
      await fetch("/api/auth/logout", { method: "POST" });
    } catch {
      /* on continue */
    }
    toast({ title: "Session terminée", tone: "success", duration: 2000 });
    router.replace("/login");
    router.refresh();
  }

  return (
    <div className="mf-dock__account">
      <Popover
        side="top"
        align="end"
        panelClassName="w-56 mb-1 p-1"
        trigger={
          <span className="mf-dock__item">
            <span className="mf-dock__icon">
              <IconSettings size={22} />
            </span>
            <span className="mf-dock__label">Compte</span>
          </span>
        }
      >
        <div className="px-2 pb-2 pt-1">
          <p className="px-2 py-1 text-[10px] font-medium uppercase tracking-wider text-subtle-foreground">
            Thème
          </p>
          <div className="space-y-0.5">
            {THEMES.map((t) => {
              const active = theme === t.id;
              return (
                <button
                  key={t.id}
                  type="button"
                  onClick={() => setTheme(t.id)}
                  className={[
                    "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm transition-colors",
                    active
                      ? "bg-accent-subtle text-accent"
                      : "text-foreground hover:bg-surface-2",
                  ].join(" ")}
                >
                  <span className={active ? "text-accent" : "text-muted-foreground"}>
                    <t.Icon size={14} />
                  </span>
                  <span className="flex-1 text-left">{t.label}</span>
                  {active && <IconCheck size={14} />}
                </button>
              );
            })}
          </div>
        </div>
        <div className="border-t border-border p-1">
          <Link
            href="/account/security"
            data-popover-close
            className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm text-foreground hover:bg-surface-2 transition-colors"
          >
            <IconSettings size={14} className="text-muted-foreground" />
            Sécurité (2FA)
          </Link>
          <button
            type="button"
            data-popover-close
            onClick={handleLogout}
            className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm text-foreground hover:bg-surface-2 transition-colors"
          >
            <IconLogOut size={14} className="text-muted-foreground" />
            Se déconnecter
          </button>
        </div>
      </Popover>
    </div>
  );
}
