"use client";

import {
  IconArrowUp,
  IconBolt,
  IconDashboard,
  IconFlask,
  IconHelp,
  IconFileDescription,
  IconPlus,
  IconSettings,
  IconShield,
  IconWorld,
} from "@tabler/icons-react";
import { useTranslations } from "next-intl";
import * as React from "react";
import { useState } from "react";
import { toast } from "sonner";

import { LocaleSwitcher } from "@/components/locale-switcher";
import { NavUser } from "@/components/nav-user";
import { OrgSwitcher } from "@/components/org/org-switcher";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarGroupContent,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
} from "@/components/ui/sidebar";
import { useSitesQuery, useAddSiteMutation } from "@/data/sites/hooks";
import { Link, usePathname, useRouter } from "@/i18n/navigation";

export function AppSidebar({
  user,
  organizations,
  activeOrganizationId,
  currentPlan,
  isOwner,
  ...props
}: React.ComponentProps<typeof Sidebar> & {
  user: { name: string; email: string; role?: string | null };
  organizations: { id: string; name: string; role: "owner" | "admin" | "member" }[];
  activeOrganizationId: string | null;
  currentPlan: string;
  isOwner: boolean;
}) {
  const isAdmin = user.role === "admin";
  const router = useRouter();
  const pathname = usePathname();
  const t = useTranslations("Nav");
  const [dialogOpen, setDialogOpen] = useState(false);
  const [url, setUrl] = useState("");
  const addSite = useAddSiteMutation();
  const { data: sites } = useSitesQuery();

  // Detect current site from URL
  const currentSiteId = pathname.match(/\/dashboard\/sites\/([^/]+)/)?.[1] ?? "";

  // Navigation items — Stitch style
  const navItems = [
    { title: t("dashboard"), url: "/dashboard", icon: IconDashboard },
    {
      title: t("webVitals"),
      url: currentSiteId ? `/dashboard/sites/${currentSiteId}` : "/dashboard",
      icon: IconFlask,
    },
    { title: t("labData"), url: "/dashboard/tests", icon: IconWorld },
    // Alerts page not built yet — hide the nav item until /dashboard/alerts exists.
    // { title: t("alerts"), url: "/dashboard/alerts", icon: IconBell },
    { title: t("settings"), url: "/dashboard/settings", icon: IconSettings },
    ...(isAdmin ? [{ title: t("admin"), url: "/admin", icon: IconShield }] : []),
  ];

  // Pick the single best-matching nav item for the current pathname.
  // We compare against item.url with a trailing "/" boundary so that
  // /dashboard/alerts does not accidentally match /dashboard, and we keep
  // the most specific (longest) match to handle items that share a prefix.
  const activeIndex = navItems.reduce<number>((bestIdx, item, idx) => {
    const matches = pathname === item.url || pathname.startsWith(`${item.url}/`);
    if (!matches) return bestIdx;
    if (bestIdx === -1) return idx;
    return item.url.length > navItems[bestIdx]!.url.length ? idx : bestIdx;
  }, -1);

  return (
    <Sidebar collapsible="offcanvas" {...props}>
      <SidebarHeader>
        <SidebarMenu>
          <SidebarMenuItem>
            <SidebarMenuButton asChild className="data-[slot=sidebar-menu-button]:p-1.5!">
              <Link href="/dashboard">
                <IconBolt className="size-5!" />
                <span className="text-base font-semibold">Eleva Speed</span>
              </Link>
            </SidebarMenuButton>
          </SidebarMenuItem>
        </SidebarMenu>

        {/* Org Switcher */}
        <div className="px-2 pt-2">
          <OrgSwitcher organizations={organizations} activeOrganizationId={activeOrganizationId} />
        </div>

        {/* Add New Site */}
        <div className="px-2 pt-2">
          <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
            <DialogTrigger asChild>
              <Button className="w-full gap-2 rounded-xl bg-primary text-xs font-bold tracking-wider text-primary-foreground uppercase">
                <IconPlus className="size-4" />
                {t("addNewSite")}
              </Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>{t("addSiteTitle")}</DialogTitle>
                <DialogDescription>{t("addSiteDescription")}</DialogDescription>
              </DialogHeader>
              <form
                onSubmit={(e) => {
                  e.preventDefault();
                  const trimmed = url.trim();
                  if (!trimmed) return;
                  addSite.mutate(trimmed, {
                    onSuccess: (site) => {
                      setDialogOpen(false);
                      setUrl("");
                      router.push(`/dashboard/sites/${site.id}`);
                    },
                    onError: (err) => toast.error(err.message),
                  });
                }}
              >
                <Input
                  placeholder={t("addSitePlaceholder")}
                  value={url}
                  onChange={(e) => setUrl(e.target.value)}
                  required
                  autoFocus
                />
                <DialogFooter className="mt-4">
                  <Button type="submit" disabled={addSite.isPending}>
                    {addSite.isPending ? t("adding") : t("addNewSite")}
                  </Button>
                </DialogFooter>
              </form>
            </DialogContent>
          </Dialog>
        </div>

        {/* Site Selector */}
        {sites && sites.length > 0 && (
          <div className="px-2 pt-3">
            <Select
              value={currentSiteId}
              onValueChange={(siteId) => router.push(`/dashboard/sites/${siteId}`)}
            >
              <SelectTrigger className="w-full border-[#45464d]/15 bg-surface-container text-sm">
                <SelectValue placeholder={t("sitePlaceholder")} />
              </SelectTrigger>
              <SelectContent>
                {sites.map((site) => (
                  <SelectItem key={site.id} value={site.id}>
                    <div className="flex items-center gap-2">
                      <IconWorld className="size-3 text-muted-foreground" />
                      <span>{site.hostname}</span>
                      {site.latestTest?.performanceScore != null && (
                        <span
                          className="ml-auto text-[10px] font-bold tabular-nums"
                          style={{
                            color:
                              site.latestTest.performanceScore >= 90
                                ? "#0cce6b"
                                : site.latestTest.performanceScore >= 50
                                  ? "#ffa400"
                                  : "#ff4e42",
                          }}
                        >
                          {site.latestTest.performanceScore}
                        </span>
                      )}
                    </div>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        )}
      </SidebarHeader>

      <SidebarContent>
        {/* Nav items — Stitch style */}
        <SidebarGroup>
          <SidebarGroupContent>
            <SidebarMenu>
              {navItems.map((item, idx) => {
                const isActive = idx === activeIndex;
                return (
                  <SidebarMenuItem key={item.title}>
                    <SidebarMenuButton asChild isActive={isActive} tooltip={item.title}>
                      <Link href={item.url}>
                        <item.icon />
                        <span className="text-xs font-medium tracking-wide uppercase">
                          {item.title}
                        </span>
                      </Link>
                    </SidebarMenuButton>
                  </SidebarMenuItem>
                );
              })}
            </SidebarMenu>
          </SidebarGroupContent>
        </SidebarGroup>

        {/* Bottom links */}
        <SidebarGroup className="mt-auto">
          <SidebarGroupContent>
            <SidebarMenu>
              <SidebarMenuItem>
                <SidebarMenuButton asChild tooltip={t("support")}>
                  <a
                    href="mailto:bastien@elevaseo.com?subject=Support%20Eleva%20Speed"
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    <IconHelp />
                    <span className="text-[10px] font-bold tracking-widest uppercase">
                      {t("support")}
                    </span>
                  </a>
                </SidebarMenuButton>
              </SidebarMenuItem>
              <SidebarMenuItem>
                <SidebarMenuButton tooltip={t("documentation")}>
                  <IconFileDescription />
                  <span className="text-[10px] font-bold tracking-widest uppercase">
                    {t("documentation")}
                  </span>
                </SidebarMenuButton>
              </SidebarMenuItem>
            </SidebarMenu>
          </SidebarGroupContent>
        </SidebarGroup>
      </SidebarContent>

      <SidebarFooter>
        {currentPlan === "free" && isOwner && (
          <div className="px-2 py-3">
            <Button
              asChild
              className="w-full gap-2 bg-primary text-primary-foreground hover:bg-primary/90"
            >
              <Link href="/settings/billing">
                <IconArrowUp className="size-4" />
                {t("upgradeSidebar")}
              </Link>
            </Button>
          </div>
        )}
        <div className="px-2 pb-2">
          <LocaleSwitcher />
        </div>
        <NavUser user={user} />
      </SidebarFooter>
    </Sidebar>
  );
}
