"use client";

import React, { useEffect, useState } from "react";
import { Layout, Menu } from "antd";
import { usePathname } from "@/i18n/routing";

const { Sider } = Layout;

type MenuItem = {
  key: string;
  label: string;
  icon?: React.ReactNode;
  onClick?: () => void;
  children?: MenuItem[];
};

type AppSidebarProps = {
  title?: string;
  menuItems: MenuItem[];
  backgroundColor?: string;
  showTitle?: boolean;
  collapsed?: boolean;
  breakpoint?: "xs" | "sm" | "md" | "lg" | "xl" | "xxl";
};

const AppSidebar: React.FC<AppSidebarProps> = ({
  title = "Sidebar",
  menuItems,
  backgroundColor = "#fff",
  showTitle = true,
  collapsed,
  breakpoint,
}) => {
  const pathname = usePathname();
  const [selectedKey, setSelectedKey] = useState<string>("");

  useEffect(() => {
    const activeItem = menuItems.find((item) =>
      pathname.includes(item.key.replace("app-", "")),
    );
    setSelectedKey(activeItem?.key || "");
  }, [pathname, menuItems]);

  return (
    <Sider
      width={220}
      style={{ backgroundColor }}
      collapsed={collapsed}
      breakpoint={breakpoint || "lg"}
    >
      {showTitle && (
        <div className="p-2 text-xs md:text-lg font-bold text-center text-neutral-800 bg-gray-100">
          {title}
        </div>
      )}
      <Menu
        theme="light"
        mode="inline"
        selectedKeys={[selectedKey]}
        onClick={({ key }) => {
          const item = menuItems.find((menuItem) => menuItem.key === key);
          if (item?.onClick) {
            item.onClick();
          }
        }}
        items={menuItems.map(({ key, label, icon }) => ({
          key,
          label,
          icon,
        }))}
        style={{
          fontSize: "16px",
          borderRight: "1px solid #e8e8e8",
        }}
        className="rounded-md"
      />
    </Sider>
  );
};

export default AppSidebar;
