"use client";

import * as React from "react";
import {
  ClipboardText,
  Buildings,
  CreditCard,
  FileText,
  SquaresFour,
  Presentation,
  MagnifyingGlass,
  GearSix,
  TrendUp,
  Users,
  Wallet,
  Wrench,
} from '@/lib/icons';
import Link from "next/link";

import { Logo } from "@/components/logo";
import { NavMain } from "@/components/nav-main";
import { NavUser } from "@/components/nav-user";
import { AcademySidebarBadge } from "@/components/academy/academy-sidebar-badge";
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  useSidebar,
} from "@/components/ui/sidebar";

import type { Icon } from "@/lib/icons";
import type { ShellCompany, ShellRole, ShellUser } from "@/app/(dashboard)/dashboard-shell";

type NavItem = {
  title: string;
  url: string;
  icon?: Icon;
  items?: { title: string; url: string; badge?: number }[];
  minRole?: ShellRole;
};

type NavGroup = { label: string; items: NavItem[] };

const ROLE_RANK: Record<ShellRole, number> = { owner: 3, admin: 2, member: 1 };
function hasAccess(minRole: ShellRole | undefined, userRole: ShellRole): boolean {
  if (!minRole) return true;
  return ROLE_RANK[userRole] >= ROLE_RANK[minRole];
}

const navGroups: NavGroup[] = [
  {
    label: "Genel",
    items: [
      {
        title: "Genel Bakış",
        url: "/dashboard",
        icon: SquaresFour,
      },
    ],
  },
  {
    label: "Portföy",
    items: [
      {
        title: "İlanlar",
        url: "/properties",
        icon: Buildings,
      },
    ],
  },
  {
    label: "İlişkiler",
    items: [
      {
        title: "Müşteriler",
        url: "/customers",
        icon: Users,
        items: [
          { title: "Müşteri Listesi", url: "/customers" },
          { title: "Arama Kriterleri", url: "/customers/searches" },
          { title: "Eşleşmeler", url: "/customers/matches" },
        ],
      },
      {
        title: "Yatırımcılar",
        url: "/investors",
        icon: Wallet,
        minRole: "admin" as ShellRole,
      },
    ],
  },
  {
    label: "Satış",
    items: [
      {
        title: "Sunumlar",
        url: "/presentations",
        icon: Presentation,
      },
      {
        title: "Aktiviteler",
        url: "/activities",
        icon: ClipboardText,
      },
      {
        title: "Finans",
        url: "/finance",
        icon: TrendUp,
      },
    ],
  },
  {
    label: "Araçlar",
    items: [
      {
        title: "Fotoğraf Damgala",
        url: "/tools/watermark",
        icon: Wrench,
      },
    ],
  },
  {
    label: "Hesap",
    items: [
      {
        title: "Çalışma Alanı",
        url: "/settings/workspace",
        icon: GearSix,
        minRole: "admin" as ShellRole,
        items: [
          { title: "Ofis Bilgileri", url: "/settings/workspace" },
          { title: "Ekip Üyeleri", url: "/settings/members" },
        ],
      },
      {
        title: "Profil",
        url: "/settings/account",
        icon: FileText,
      },
      {
        title: "Plan & Faturalama",
        url: "/settings/billing",
        icon: CreditCard,
        minRole: "owner" as ShellRole,
        items: [
          { title: "Plan & Yükseltme", url: "/settings/billing" },
          { title: "Faturalar", url: "/settings/billing/invoices" },
        ],
      },
    ],
  },
];

export function AppSidebar({
  user,
  company,
  pendingMatchCount = 0,
  role = "member",
  ...props
}: React.ComponentProps<typeof Sidebar> & {
  user: ShellUser;
  company: ShellCompany;
  pendingMatchCount?: number;
  role?: ShellRole;
}) {
  const { isMobile, setOpenMobile } = useSidebar();
  const closeMobile = () => { if (isMobile) setOpenMobile(false) };

  const groups = navGroups
    .map((group) => ({
      ...group,
      items: group.items
        .filter((item) => hasAccess(item.minRole, role))
        .map((item) => ({
          ...item,
          items: item.items?.map((sub) =>
            sub.url === "/customers/matches" && pendingMatchCount > 0
              ? { ...sub, badge: pendingMatchCount }
              : sub,
          ),
        })),
    }))
    .filter((group) => group.items.length > 0);

  return (
    <Sidebar {...props}>
      <SidebarHeader>
        <SidebarMenu>
          <SidebarMenuItem>
            <SidebarMenuButton size="lg" asChild>
              <Link href="/dashboard" onClick={closeMobile}>
                {company.logoUrl ? (
                  <div className="bg-background flex aspect-square size-8 items-center justify-center overflow-hidden rounded-lg border">
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img
                      src={company.logoUrl}
                      alt={`${company.name} logo`}
                      className="size-full object-contain"
                    />
                  </div>
                ) : (
                  <div className="bg-primary text-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg">
                    <Logo size={20} className="text-current" />
                  </div>
                )}
                <div className="grid flex-1 text-left text-sm leading-tight">
                  <span className="truncate font-medium">KovakEmlak</span>
                  <span className="text-muted-foreground truncate text-xs">{company.name}</span>
                </div>
              </Link>
            </SidebarMenuButton>
          </SidebarMenuItem>
        </SidebarMenu>
      </SidebarHeader>
      <SidebarContent>
        {groups.map((group) => (
          <NavMain
            key={group.label}
            label={group.label}
            items={group.items.map(({ minRole: _minRole, ...rest }) => rest)}
          />
        ))}
      </SidebarContent>
      <SidebarFooter>
        <AcademySidebarBadge />
        <NavUser user={user} />
      </SidebarFooter>
    </Sidebar>
  );
}
