'use client';

import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { ChevronRight, MoreHorizontal, X } from 'lucide-react';
import { usePlatformSidebar } from '@/contexts/platform-sidebar-context';
import { logout, type AuthUser } from '@/lib/auth';
import { cn } from '@/lib/utils';
import type { ShellNavSection } from './platform-nav-data';

export type { ShellNavItem } from './platform-nav-data';

function ShellSubNavLinks({
  items,
  pathname,
  onNavigate,
}: {
  items: { href: string; label: string }[];
  pathname: string;
  onNavigate: () => void;
}) {
  const last = items.length - 1;
  return (
    <div className="relative space-y-0">
      <div
        className="absolute bottom-[22px] left-[30px] top-[22px] z-0 w-0.5 bg-gray-500/20"
        aria-hidden
      />
      {items.map((child, index) => {
        const childActive = pathname === child.href || pathname.startsWith(`${child.href}/`);
        const showDot = index === 0 || index === last;
        return (
          <Link
            key={child.href}
            href={child.href}
            onClick={onNavigate}
            className={cn(
              'relative z-10 block py-2 pl-[50px] text-sm transition-colors',
              childActive ? 'text-primary-light' : 'text-white hover:text-primary-light',
            )}
          >
            {showDot ? (
              <span
                className="absolute left-[27px] top-[14px] z-20 size-2 rounded-full bg-gray-500/20"
                aria-hidden
              />
            ) : null}
            {child.label}
          </Link>
        );
      })}
    </div>
  );
}

export function ShellSidebar({
  navSections,
  homeHref,
  roleSubtitle,
  user,
  expandedCollapsibleHref,
  setExpandedCollapsibleHref,
  onCloseMobile,
}: {
  navSections: ShellNavSection[];
  homeHref: string;
  roleSubtitle: string;
  user: AuthUser | null;
  expandedCollapsibleHref: string | null;
  setExpandedCollapsibleHref: (v: string | null | ((prev: string | null) => string | null)) => void;
  onCloseMobile: () => void;
}) {
  const pathname = usePathname();
  const { isExpanded, isMobileOpen, isHovered, setIsHovered } = usePlatformSidebar();

  const showLabels = isExpanded || isHovered || isMobileOpen;
  const rail = !isExpanded && !isHovered && !isMobileOpen;
  const wide = isExpanded || isHovered || isMobileOpen;

  return (
    <aside
      className={cn(
        'fixed left-0 top-0 z-50 flex h-screen shrink-0 flex-col bg-primary-darker text-white transition-all duration-300 ease-out',
        'dark:bg-shell-sidebar-dark',
        wide ? 'w-[280px]' : 'w-[88px]',
        isMobileOpen ? 'translate-x-0' : '-translate-x-full lg:translate-x-0',
      )}
      onMouseEnter={() => !isExpanded && setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      <div className="relative flex h-[70px] shrink-0 items-center gap-2 p-4">
        <Link
          href={homeHref}
          onClick={onCloseMobile}
          className={cn(
            'flex items-center gap-3 transition-opacity duration-300',
            showLabels ? 'visible opacity-100' : 'pointer-events-none invisible absolute opacity-0',
          )}
        >
          <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg border border-sky-400/50 bg-white/[0.06] text-sm font-bold tracking-tight text-white">
            V
          </span>
          <div className="min-w-0">
            <p className="truncate font-urbanist text-sm font-semibold leading-tight tracking-tight text-white">
              Vidikid
            </p>
            <p className="mt-0.5 truncate text-xs font-medium leading-tight text-white/55">{roleSubtitle}</p>
          </div>
        </Link>

        <Link
          href={homeHref}
          onClick={onCloseMobile}
          className={cn(
            'absolute left-1/2 flex -translate-x-1/2 items-center justify-center transition-opacity duration-300',
            showLabels ? 'pointer-events-none invisible opacity-0' : 'visible opacity-100',
          )}
          aria-label="Ana sayfa"
        >
          <span className="flex size-10 shrink-0 items-center justify-center rounded-lg border border-sky-400/50 bg-white/[0.06] text-sm font-bold text-white">
            V
          </span>
        </Link>

        <button
          type="button"
          onClick={onCloseMobile}
          className="absolute right-4 top-1/2 -translate-y-1/2 rounded-md p-1 text-white hover:bg-white/10 lg:hidden"
          aria-label="Menüyü kapat"
        >
          <X className="size-6" strokeWidth={2} />
        </button>
      </div>

      <div className="custom-scrollbar-white flex flex-1 flex-col overflow-y-auto overflow-x-hidden p-4 pb-10">
        {navSections.map((section, sectionIndex) => (
          <div key={section.sectionTitle} className={cn('mb-6', sectionIndex === navSections.length - 1 && 'mb-0')}>
            <div
              className={cn(
                'mb-3 px-4 text-sm font-medium uppercase tracking-wider text-warning-light transition-all duration-300',
                rail && 'flex justify-center px-0',
              )}
            >
              {showLabels ? (
                <span className="whitespace-nowrap">{section.sectionTitle}</span>
              ) : (
                <MoreHorizontal className="size-4 opacity-80" strokeWidth={2} aria-hidden />
              )}
            </div>
            <div className="space-y-1">
              {section.items.map((item) => {
                const hasChildren = Boolean(item.children?.length);
                const childActive =
                  hasChildren &&
                  item.children!.some((c) => pathname === c.href || pathname.startsWith(`${c.href}/`));
                const selfActive =
                  !hasChildren && (pathname === item.href || pathname.startsWith(`${item.href}/`));
                const active = Boolean(childActive || selfActive);
                const isDashboard = item.href === homeHref && !hasChildren;
                const expanded = expandedCollapsibleHref === item.href;

                return (
                  <div key={item.href}>
                    {hasChildren && showLabels ? (
                      <>
                        <button
                          type="button"
                          onClick={() =>
                            setExpandedCollapsibleHref((prev) => (prev === item.href ? null : item.href))
                          }
                          className={cn(
                            'shell-nav-collapsible w-full',
                            expanded && 'shell-nav-collapsible-open',
                          )}
                        >
                          <div className="flex min-w-0 items-center gap-3">
                            <span className="shell-nav-icon text-white">{item.icon}</span>
                            <span className="shell-nav-text">{item.label}</span>
                          </div>
                          <ChevronRight
                            className={cn(
                              'size-4 shrink-0 text-white/55 transition-transform duration-200',
                              expanded && 'rotate-90',
                            )}
                            strokeWidth={2}
                          />
                        </button>
                        <div
                          className={cn(
                            'grid transition-all duration-300 ease-in-out',
                            expanded
                              ? 'mt-2 grid-rows-[1fr] opacity-100'
                              : 'mt-0 grid-rows-[0fr] opacity-0',
                          )}
                        >
                          <div className="min-h-0 overflow-hidden">
                            <ShellSubNavLinks
                              items={item.children!}
                              pathname={pathname}
                              onNavigate={onCloseMobile}
                            />
                          </div>
                        </div>
                      </>
                    ) : hasChildren && rail ? (
                      <Link
                        href={item.href}
                        onClick={onCloseMobile}
                        className="shell-nav-collapsible w-full justify-center lg:justify-center"
                        title={item.label}
                      >
                        <span
                          className={cn(
                            'shell-nav-icon',
                            active ? 'text-white' : 'text-white/65 hover:text-white',
                          )}
                        >
                          {item.icon}
                        </span>
                      </Link>
                    ) : isDashboard ? (
                      <Link
                        href={item.href}
                        onClick={onCloseMobile}
                        className={cn(
                          'shell-nav-dashboard',
                          active ? 'shell-nav-dashboard-active' : 'shell-nav-dashboard-inactive',
                          rail && 'justify-center px-2',
                        )}
                      >
                        <span className="shell-nav-icon text-white">{item.icon}</span>
                        {showLabels ? <span className="shell-nav-text">{item.label}</span> : null}
                      </Link>
                    ) : (
                      <Link
                        href={item.href}
                        onClick={onCloseMobile}
                        className={cn(
                          'shell-nav-row-link group',
                          active && 'shell-nav-row-link-active',
                          rail && 'justify-center px-2',
                        )}
                        title={!showLabels ? item.label : undefined}
                      >
                        <div className="flex min-w-0 items-center gap-3">
                          <span
                            className={cn(
                              'shell-nav-icon',
                              active ? 'text-white' : 'text-white/65 group-hover:text-white',
                            )}
                          >
                            {item.icon}
                          </span>
                          {showLabels ? <span className="shell-nav-text">{item.label}</span> : null}
                        </div>
                      </Link>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        ))}
      </div>

      <div className="border-t border-white/10 p-3 lg:p-4">
        <div className={cn('flex items-center rounded-xl bg-white/[0.06] px-2 py-2.5', rail ? 'justify-center' : 'gap-3')}>
          <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-white/15 text-[12px] font-semibold text-white ring-1 ring-white/20">
            {user?.name?.[0]?.toUpperCase() || 'K'}
          </div>
          {showLabels ? (
            <div className="min-w-0 flex-1">
              <p className="truncate text-sm font-semibold text-white">{user?.name || 'Kullanıcı'}</p>
              <p className="truncate text-xs text-white/50">{user?.email}</p>
            </div>
          ) : null}
          {showLabels ? (
            <button
              type="button"
              onClick={() => logout()}
              className="shrink-0 rounded-xl p-2 text-white/45 transition hover:bg-white/10 hover:text-white"
              title="Çıkış"
            >
              <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"
                />
              </svg>
            </button>
          ) : null}
        </div>
      </div>
    </aside>
  );
}
