"use client";

import { useState, useSyncExternalStore } from "react";
import { usePathname } from "next/navigation";

import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import { useTheme } from "@mui/material/styles";

import { dashboardAssets } from "@/components/dashboard/dashboard-assets";
import type { TranslationKey } from "@/components/layout/header/header-data";
import { useAppLanguage } from "@/components/providers/app-language-provider";
import {
  isAdminRole,
  isCdcGpsfRole,
  isCdcRole,
  isCefpRole,
  isMinistryRole,
  ROLE_CDC,
  ROLE_CDC_GPSF,
  ROLE_CEFP,
  ROLE_MINISTRY,
} from "@/features/auth/auth-data";
import { usePermissions } from "@/features/auth/hook/use-permissions";
import { getClientAuthRole } from "@/features/auth/service/auth-service";

type SidebarBrandProps = {
  showBottomBorder?: boolean;
};

function isCdcSidebarPath(pathname: string) {
  return pathname.startsWith("/cdc") && !pathname.startsWith("/cdc-gpsf");
}

function getBrandTitleFromPathname(
  pathname: string,
  t: (key: TranslationKey) => string,
) {
  if (pathname.startsWith("/ministry")) return ROLE_MINISTRY;
  if (pathname.startsWith("/cdc-gpsf")) return ROLE_CDC_GPSF;
  if (isCdcSidebarPath(pathname)) return ROLE_CDC;
  if (pathname.startsWith("/cefp")) return ROLE_CEFP;
  return t("agricultureAgroIndustry");
}

function getAccountSettingBrandTitle(role: string | null) {
  if (isMinistryRole(role)) return ROLE_MINISTRY;
  if (isCdcGpsfRole(role)) return ROLE_CDC_GPSF;
  if (isCdcRole(role)) return ROLE_CDC;
  if (isCefpRole(role)) return ROLE_CEFP;
  return null;
}

export function SidebarBrand({ showBottomBorder = false }: SidebarBrandProps) {
  const pathname = usePathname();
  const theme = useTheme();
  const { t } = useAppLanguage();
  const { role: sessionRole } = usePermissions();
  const [cookieRole] = useState(() => getClientAuthRole());
  const isClient = useSyncExternalStore(
    () => () => undefined,
    () => true,
    () => false,
  );
  const role = sessionRole ?? cookieRole;

  const isAdminAccountSetting =
    pathname === "/account-setting" && isAdminRole(role);
  const isAdminSidebar = pathname.startsWith("/admin") || isAdminAccountSetting;

  const brandTitle =
    pathname === "/account-setting" && isClient
      ? (getAccountSettingBrandTitle(role) ??
        getBrandTitleFromPathname(pathname, t))
      : getBrandTitleFromPathname(pathname, t);
  const brandLogo = isAdminSidebar
    ? dashboardAssets.gpsfLogo
    : dashboardAssets.gpsfLogo;

  return (
    <Box
      sx={{
        height: 64,
        display: "flex",
        alignItems: "center",
        px: 2.5,
        bgcolor: theme.palette.background.paper,
        borderBottom: showBottomBorder
          ? `1px solid ${theme.palette.divider}`
          : "none",
      }}
    >
      <Box
        sx={{
          width: "100%",
          display: "flex",
          alignItems: "center",
          justifyContent: isAdminSidebar ? "center" : "flex-start",
          gap: 0.75,
        }}
      >
        <Box
          aria-label={isAdminSidebar ? "CAPRED logo" : "G-PSF logo"}
          sx={{
            width: isAdminSidebar ? 181 : 96,
            height: 50,
            flexShrink: 0,
            backgroundImage: `url(${brandLogo})`,
            backgroundRepeat: "no-repeat",
            backgroundPosition: "center",
            backgroundSize: "contain",
          }}
        />

        {isAdminSidebar ? null : (
          <Typography
            sx={{
              color: theme.palette.primary.main,
              maxWidth: 150,
              fontSize: 11,
              fontWeight: 500,
              lineHeight: 1.2,
            }}
          >
            {brandTitle}
          </Typography>
        )}
      </Box>
    </Box>
  );
}
