'use client';

/**
 * PortalSidebar — vertical sidebar navigation for the Client Portal.
 *
 * Renders navigation items vertically in a fixed left sidebar below the TopNav.
 * "Analítica" is a collapsible section with sub-items (Overview, Top Songs,
 * Income Groups, Territories, Exploitation Sources).
 *
 * Features:
 * - Fixed left sidebar (200px) on desktop (≥1024px)
 * - Active item highlighted with accent left border + accent text + accent bg
 * - Collapsible "Analítica" section with smooth animation
 * - Icons for each tab and sub-item
 * - Mobile hamburger menu + overlay drawer for viewports below 1024px
 */

import { useState } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { PORTAL_TABS, PORTAL_ANALYTICS_SUBITEMS } from '@/lib/constants/portal-navigation';
import { usePortalSidebarStore } from '@/lib/stores/portal-sidebar-store';

// ── Icon components ──────────────────────────────────────────────────────────

function HomeIcon({ className }: { className?: string }) {
  return (
    <svg className={className ?? 'h-5 w-5'} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
      <polyline points="9 22 9 12 15 12 15 22" />
    </svg>
  );
}

function ChartIcon({ className }: { className?: string }) {
  return (
    <svg className={className ?? 'h-5 w-5'} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <line x1="18" y1="20" x2="18" y2="10" />
      <line x1="12" y1="20" x2="12" y2="4" />
      <line x1="6" y1="20" x2="6" y2="14" />
    </svg>
  );
}

function MusicIcon({ className }: { className?: string }) {
  return (
    <svg className={className ?? 'h-5 w-5'} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M9 18V5l12-2v13" />
      <circle cx="6" cy="18" r="3" />
      <circle cx="18" cy="16" r="3" />
    </svg>
  );
}

function DocumentIcon({ className }: { className?: string }) {
  return (
    <svg className={className ?? 'h-5 w-5'} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
      <polyline points="14 2 14 8 20 8" />
      <line x1="16" y1="13" x2="8" y2="13" />
      <line x1="16" y1="17" x2="8" y2="17" />
      <polyline points="10 9 9 9 8 9" />
    </svg>
  );
}

function ChartOverviewIcon({ className }: { className?: string }) {
  return (
    <svg className={className ?? 'h-4 w-4'} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="3" width="7" height="7" />
      <rect x="14" y="3" width="7" height="7" />
      <rect x="3" y="14" width="7" height="7" />
      <rect x="14" y="14" width="7" height="7" />
    </svg>
  );
}

function TopSongsIcon({ className }: { className?: string }) {
  return (
    <svg className={className ?? 'h-4 w-4'} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M9 18V5l12-2v13" />
      <circle cx="6" cy="18" r="3" />
      <circle cx="18" cy="16" r="3" />
      <polygon points="18 2 22 6 18 10" fill="currentColor" opacity="0.3" />
    </svg>
  );
}

function IncomeGroupsIcon({ className }: { className?: string }) {
  return (
    <svg className={className ?? 'h-4 w-4'} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="M21.21 15.89A10 10 0 1 1 8 2.83" />
      <path d="M22 12A10 10 0 0 0 12 2v10z" />
    </svg>
  );
}

function TerritoriesIcon({ className }: { className?: string }) {
  return (
    <svg className={className ?? 'h-4 w-4'} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <circle cx="12" cy="12" r="10" />
      <line x1="2" y1="12" x2="22" y2="12" />
      <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" />
    </svg>
  );
}

function SourcesIcon({ className }: { className?: string }) {
  return (
    <svg className={className ?? 'h-4 w-4'} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <polygon points="12 2 2 7 12 12 22 7 12 2" />
      <polyline points="2 17 12 22 22 17" />
      <polyline points="2 12 12 17 22 12" />
    </svg>
  );
}

function ChevronIcon({ expanded, className }: { expanded: boolean; className?: string }) {
  return (
    <svg
      className={`h-4 w-4 transition-transform duration-200 ${expanded ? 'rotate-90' : 'rotate-0'} ${className ?? ''}`}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <polyline points="9 18 15 12 9 6" />
    </svg>
  );
}

/** Map sub-item href to its icon component */
function SubItemIcon({ href, className }: { href: string; className?: string }) {
  switch (href) {
    case '/portal/analytics':
      return <ChartOverviewIcon className={className} />;
    case '/portal/analytics/top-songs':
      return <TopSongsIcon className={className} />;
    case '/portal/analytics/income-groups':
      return <IncomeGroupsIcon className={className} />;
    case '/portal/analytics/territories':
      return <TerritoriesIcon className={className} />;
    case '/portal/analytics/sources':
      return <SourcesIcon className={className} />;
    default:
      return <ChartOverviewIcon className={className} />;
  }
}

/** Map tab href to its icon component */
function TabIcon({ href, className }: { href: string; className?: string }) {
  switch (href) {
    case '/portal':
      return <HomeIcon className={className} />;
    case '/portal/analytics':
      return <ChartIcon className={className} />;
    case '/portal/songs':
      return <MusicIcon className={className} />;
    case '/portal/documents':
      return <DocumentIcon className={className} />;
    default:
      return <HomeIcon className={className} />;
  }
}

// ── Helper: check if current path is within analytics section ─────────────────

function isAnalyticsPath(pathname: string): boolean {
  return pathname.startsWith('/portal/analytics');
}

// ── PortalSidebar component ──────────────────────────────────────────────────

export default function PortalSidebar() {
  const pathname = usePathname();
  const { isMobileOpen, closeMobile, toggleMobile } = usePortalSidebarStore();
  const [analyticsExpanded, setAnalyticsExpanded] = useState(true);

  // Filter out the "Analítica" tab — it becomes a section header
  const mainTabs = PORTAL_TABS.filter((tab) => tab.href !== '/portal/analytics');

  const renderNavContent = (onItemClick?: () => void) => (
    <>
      {/* Inicio */}
      {mainTabs
        .filter((tab) => tab.href === '/portal')
        .map((tab) => {
          const isActive = pathname === tab.href;
          return (
            <Link
              key={tab.href}
              href={tab.href}
              onClick={onItemClick}
              className={`
                relative flex items-center gap-3 rounded-lg px-3 py-2.5
                transition-colors duration-150
                ${
                  isActive
                    ? 'bg-divisi-accent/10 text-divisi-accent'
                    : 'text-divisi-text-secondary hover:text-divisi-text-primary hover:bg-white/5'
                }
              `}
              aria-current={isActive ? 'page' : undefined}
            >
              {isActive && (
                <span className="absolute left-0 top-1/2 -translate-y-1/2 h-6 w-[3px] rounded-r-full bg-divisi-accent" />
              )}
              <span className="flex-shrink-0">
                <TabIcon href={tab.href} />
              </span>
              <span className="text-sm font-medium">{tab.label}</span>
            </Link>
          );
        })}

      {/* Analítica collapsible section */}
      <div className="mt-2">
        <button
          type="button"
          onClick={() => setAnalyticsExpanded((prev) => !prev)}
          className={`
            flex w-full items-center justify-between rounded-lg px-3 py-2.5
            transition-colors duration-150
            ${
              isAnalyticsPath(pathname) && !analyticsExpanded
                ? 'text-divisi-accent'
                : 'text-divisi-text-secondary hover:text-divisi-text-primary hover:bg-white/5'
            }
          `}
          aria-expanded={analyticsExpanded}
        >
          <div className="flex items-center gap-3">
            <span className="flex-shrink-0">
              <ChartIcon />
            </span>
            <span className="text-sm font-medium">Analítica</span>
          </div>
          <ChevronIcon expanded={analyticsExpanded} />
        </button>

        {/* Collapsible sub-items */}
        <div
          className="overflow-hidden transition-all duration-300 ease-in-out"
          style={{
            maxHeight: analyticsExpanded ? `${PORTAL_ANALYTICS_SUBITEMS.length * 40}px` : '0px',
            opacity: analyticsExpanded ? 1 : 0,
          }}
        >
          <div className="flex flex-col gap-0.5 pl-4 mt-0.5">
            {PORTAL_ANALYTICS_SUBITEMS.map((item) => {
              const isActive = pathname === item.href;
              return (
                <Link
                  key={item.href}
                  href={item.href}
                  onClick={onItemClick}
                  className={`
                    relative flex items-center gap-2.5 rounded-lg px-3 py-2
                    transition-colors duration-150
                    ${
                      isActive
                        ? 'bg-divisi-accent/10 text-divisi-accent'
                        : 'text-divisi-text-secondary hover:text-divisi-text-primary hover:bg-white/5'
                    }
                  `}
                  aria-current={isActive ? 'page' : undefined}
                >
                  {isActive && (
                    <span className="absolute left-0 top-1/2 -translate-y-1/2 h-5 w-[3px] rounded-r-full bg-divisi-accent" />
                  )}
                  <span className="flex-shrink-0">
                    <SubItemIcon href={item.href} />
                  </span>
                  <span className="text-xs font-medium">{item.label}</span>
                </Link>
              );
            })}
          </div>
        </div>
      </div>

      {/* Canciones & Documentos */}
      {mainTabs
        .filter((tab) => tab.href !== '/portal')
        .map((tab) => {
          const isActive = pathname === tab.href;
          return (
            <Link
              key={tab.href}
              href={tab.href}
              onClick={onItemClick}
              className={`
                relative flex items-center gap-3 rounded-lg px-3 py-2.5
                transition-colors duration-150
                ${
                  isActive
                    ? 'bg-divisi-accent/10 text-divisi-accent'
                    : 'text-divisi-text-secondary hover:text-divisi-text-primary hover:bg-white/5'
                }
              `}
              aria-current={isActive ? 'page' : undefined}
            >
              {isActive && (
                <span className="absolute left-0 top-1/2 -translate-y-1/2 h-6 w-[3px] rounded-r-full bg-divisi-accent" />
              )}
              <span className="flex-shrink-0">
                <TabIcon href={tab.href} />
              </span>
              <span className="text-sm font-medium">{tab.label}</span>
            </Link>
          );
        })}
    </>
  );

  return (
    <>
      {/* ─── Desktop sidebar (≥1024px) ─────────────────────────────────── */}
      <aside
        className="
          hidden lg:flex flex-col
          fixed top-14 left-0 bottom-0 z-20
          w-[200px]
          border-r border-divisi-border bg-divisi-card
          py-4 overflow-y-auto
        "
      >
        <nav className="flex flex-col gap-0.5 px-2">
          {renderNavContent()}
        </nav>
      </aside>

      {/* ─── Mobile hamburger button (visible below lg) ───────────────── */}
      <button
        type="button"
        onClick={toggleMobile}
        className="
          fixed top-3 left-3 z-50
          lg:hidden
          flex items-center justify-center
          h-10 w-10 rounded-lg
          bg-divisi-card border border-divisi-border
          text-divisi-text-primary
        "
        aria-label={isMobileOpen ? 'Close navigation menu' : 'Open navigation menu'}
        aria-expanded={isMobileOpen}
      >
        {isMobileOpen ? (
          <svg className="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <line x1="18" y1="6" x2="6" y2="18" />
            <line x1="6" y1="6" x2="18" y2="18" />
          </svg>
        ) : (
          <svg className="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <line x1="3" y1="12" x2="21" y2="12" />
            <line x1="3" y1="6" x2="21" y2="6" />
            <line x1="3" y1="18" x2="21" y2="18" />
          </svg>
        )}
      </button>

      {/* ─── Mobile overlay + drawer (below lg) ───────────────────────── */}
      {isMobileOpen && (
        <>
          {/* Backdrop */}
          <div
            className="fixed inset-0 z-40 bg-black/60 lg:hidden"
            onClick={closeMobile}
            aria-hidden="true"
          />

          {/* Drawer */}
          <aside
            className="
              fixed inset-y-0 left-0 z-40
              w-[240px] lg:hidden
              flex flex-col
              bg-divisi-card border-r border-divisi-border
              pt-16 py-4
              animate-slide-in
            "
          >
            <nav className="flex flex-col gap-0.5 px-2">
              {renderNavContent(closeMobile)}
            </nav>
          </aside>
        </>
      )}
    </>
  );
}
