'use client';

import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useState } from 'react';
import { Menu } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';

import { getVisibleNavItems, type AppRole } from './nav-items';

export function MobileSidebar({ role }: { role: AppRole }) {
  const [open, setOpen] = useState(false);
  const pathname = usePathname();
  const items = getVisibleNavItems(role);

  return (
    <div className="ajet-mobile-sidebar-trigger">
      <Button size="icon" variant="ghost" onClick={() => setOpen(true)}>
        <Menu className="h-5 w-5" />
      </Button>
      {open && (
        <div className="fixed inset-0 z-50 bg-black/40" onClick={() => setOpen(false)}>
          <div
            className="h-full w-80 max-w-[86vw] border-r bg-background p-4 shadow-xl"
            onClick={(event) => event.stopPropagation()}
          >
            <div className="mb-4 flex items-center justify-between">
              <Link
                className="flex items-center gap-2 font-semibold"
                href="/"
                onClick={() => setOpen(false)}
              >
                <span className="ajet-mobile-logo" aria-hidden="true">
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img src="/brand/ajet-mark-white.png" alt="" />
                </span>
                AJet360
              </Link>
              <Button size="sm" variant="outline" onClick={() => setOpen(false)}>
                Kapat
              </Button>
            </div>
            <nav className="space-y-1">
              {items.map((item) => {
                const Icon = item.icon;
                const active =
                  pathname === item.href || (item.href !== '/' && pathname.startsWith(item.href));

                return (
                  <Link
                    key={item.href}
                    className={cn(
                      'flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium text-muted-foreground',
                      active && 'bg-primary text-primary-foreground',
                    )}
                    href={item.href}
                    onClick={() => setOpen(false)}
                  >
                    <Icon className="h-4 w-4" />
                    {item.title}
                  </Link>
                );
              })}
            </nav>
          </div>
        </div>
      )}
    </div>
  );
}
