import type { ReactNode } from "react";
import Link from "next/link";
import type { LucideIcon } from "lucide-react";

import { Separator } from "@/components/ui/separator";
import { cn } from "@/lib/utils";

type DashboardSidebarItem = {
  label: string;
  href: string;
  icon: LucideIcon;
  active?: boolean;
  children?: DashboardSidebarItem[];
};

type DashboardSidebarProps = {
  items: DashboardSidebarItem[];
  iconSrc?: string;
  top?: ReactNode;
  footer?: ReactNode;
};

export function DashboardSidebar({ items, iconSrc, top, footer }: DashboardSidebarProps) {
  function renderItem(item: DashboardSidebarItem, nested = false) {
    const Icon = item.icon;

    return (
      <div key={item.href} className="space-y-1">
        <Link
          href={item.href}
          className={cn(
            "flex items-center gap-3 rounded-lg px-3 py-2 text-sm transition-colors",
            item.active
              ? "bg-primary text-primary-foreground"
              : "text-muted-foreground hover:bg-muted hover:text-foreground",
            nested ? "ml-4" : undefined,
          )}
        >
          <Icon className="h-4 w-4" />
          <span>{item.label}</span>
        </Link>
        {item.children?.length ? item.children.map((child) => renderItem(child, true)) : null}
      </div>
    );
  }

  return (
    <div className="flex h-full flex-col bg-sidebar/40">
      <div className="flex items-center gap-3 px-4 py-5">
        <div className="overflow-hidden rounded-xl border border-border/70 bg-background shadow-sm">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img
            src={iconSrc || "/favicon.ico"}
            alt="Mohs Admin"
            className="h-9 w-9 object-cover"
          />
        </div>
        <div className="min-w-0">
          <p className="truncate text-sm font-semibold text-foreground">Mohs Admin</p>
          <p className="truncate text-xs text-muted-foreground">Website owner workspace</p>
        </div>
      </div>

      {top ? <div className="px-4">{top}</div> : null}

      <Separator className="my-4" />

      <div className="flex-1 space-y-6 overflow-y-auto px-4 pb-4">
        <nav className="space-y-1">{items.map((item) => renderItem(item))}</nav>
      </div>

      {footer ? (
        <>
          <Separator />
          <div className="space-y-2 p-4">{footer}</div>
        </>
      ) : null}
    </div>
  );
}
