"use client";

import { Box, Drawer } from "@mantine/core";
import { useDisclosure } from "@mantine/hooks";
import { useQuery } from "@tanstack/react-query";
import { PremiumBackground } from "@/components/motion/PremiumBackground";
import { DashboardSidebar } from "@/components/dashboard/DashboardSidebar";
import { DashboardTopbar } from "@/components/dashboard/DashboardTopbar";
import { useBrandColors } from "@/hooks/useBrandColors";
import { defaultPeriodSelection } from "@/lib/dashboardPeriod";
import { adminDashboardService } from "@/services/adminDashboardService";
import { useAuthStore } from "@/store/authStore";

interface DashboardLayoutProps {
  children: React.ReactNode;
  title: string;
  executive?: boolean;
}

export function DashboardLayout({ children, title, executive }: DashboardLayoutProps) {
  const [mobileNav, { toggle, close }] = useDisclosure();
  const c = useBrandColors();
  const token = useAuthStore((s) => s.token);
  const role = useAuthStore((s) => s.user?.role);

  const layoutPeriod = defaultPeriodSelection();
  const { data: overviewPeek } = useQuery({
    queryKey: ["admin-dashboard-overview", "layout-badge"],
    queryFn: () => adminDashboardService.overview(token!, layoutPeriod).then((r) => r.data),
    enabled: Boolean(token) && role === "admin",
    staleTime: 60_000,
  });

  const openTickets = overviewPeek?.stats.openTickets ?? 0;

  return (
    <Box
      pos="relative"
      className="noga-grid-bg noga-dashboard-shell"
      style={{ minHeight: "100vh", background: c.bgMain, color: c.text }}
    >
      <PremiumBackground variant="dashboard" showParticles={false} />

      <Box display={{ base: "none", md: "block" }} pos="relative" style={{ zIndex: 1 }}>
        <Box style={{ display: "flex" }}>
          <DashboardSidebar openTicketsCount={openTickets} />
          <Box style={{ flex: 1, minWidth: 0 }}>
            <DashboardTopbar
              title={title}
              executive={executive}
              openTicketsCount={openTickets}
            />
            <Box p={executive ? "md" : "lg"} px={{ base: "md", md: "lg" }}>
              {children}
            </Box>
          </Box>
        </Box>
      </Box>

      <Box hiddenFrom="md" pos="relative" style={{ zIndex: 1 }}>
        <DashboardTopbar
          title={title}
          executive={executive}
          openTicketsCount={openTickets}
          onMenuToggle={toggle}
        />
        <Drawer
          opened={mobileNav}
          onClose={close}
          size="xs"
          styles={{ content: { background: c.bgSecondary } }}
        >
          <DashboardSidebar openTicketsCount={openTickets} />
        </Drawer>
        <Box p="md">{children}</Box>
      </Box>
    </Box>
  );
}
