'use client';

/**
 * Sidebar Component
 * Pure Tailwind CSS - Clean navigation sidebar
 * - Slide-in/out on mobile
 * - Collapsible on desktop with a toggle button
 */

import { useState } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import {
  LayoutDashboard,
  ShoppingCart,
  Package,
  Warehouse,
  Receipt,
  Users,
  Tag,
  DollarSign,
  // Percent icon removed (was used for Taxes)
  FileText,
  ShoppingBag,
  Settings,
  LogOut,
  TrendingUp,
  ArrowLeftRight,
  Factory,
  Printer,
  FileCheck,
  ChevronLeft,
  ChevronRight,
} from 'lucide-react';
import { useAuth } from '@/contexts/AuthContext';
import { USER_ROLES } from '@/lib/utils/constants';

const navigation = [
  {
    name: 'Dashboard',
    href: '/',
    icon: LayoutDashboard,
    roles: [USER_ROLES.CASHIER, USER_ROLES.MANAGER, USER_ROLES.SYSTEM_ADMIN],
  },
  {
    name: 'POS',
    href: '/pos',
    icon: ShoppingCart,
    roles: [USER_ROLES.CASHIER, USER_ROLES.MANAGER, USER_ROLES.SYSTEM_ADMIN],
  },
  {
    name: 'Products',
    href: '/products',
    icon: Package,
    roles: [USER_ROLES.MANAGER, USER_ROLES.SYSTEM_ADMIN],
  },
  {
    name: 'Inventory',
    href: '/inventory',
    icon: Warehouse,
    roles: [USER_ROLES.MANAGER, USER_ROLES.SYSTEM_ADMIN],
  },
  {
    name: 'Sales',
    href: '/sales',
    icon: Receipt,
    roles: [USER_ROLES.CASHIER, USER_ROLES.MANAGER, USER_ROLES.SYSTEM_ADMIN],
  },
  // Customers removed - customer registration removed, walk-in customers only
  // Keeping /customers page for historical data viewing only (no creation/editing)
  {
    name: 'Categories',
    href: '/categories',
    icon: Tag,
    roles: [USER_ROLES.MANAGER, USER_ROLES.SYSTEM_ADMIN],
  },
  {
    name: 'Pricing',
    href: '/pricing',
    icon: DollarSign,
    roles: [USER_ROLES.MANAGER, USER_ROLES.SYSTEM_ADMIN],
  },
  // Taxes removed - tax functionality removed from system
  {
    name: 'Discounts',
    href: '/discounts',
    icon: TrendingUp,
    roles: [USER_ROLES.MANAGER, USER_ROLES.SYSTEM_ADMIN],
  },
  {
    name: 'Procurement',
    href: '/procurement',
    icon: ShoppingBag,
    roles: [USER_ROLES.MANAGER, USER_ROLES.SYSTEM_ADMIN],
  },
  {
    name: 'Production',
    href: '/production',
    icon: Factory,
    roles: [USER_ROLES.MANAGER, USER_ROLES.SYSTEM_ADMIN],
  },
  {
    name: 'Returns',
    href: '/returns',
    icon: ArrowLeftRight,
    roles: [USER_ROLES.MANAGER, USER_ROLES.SYSTEM_ADMIN],
  },
  {
    name: 'Credit Notes',
    href: '/credit-notes',
    icon: FileCheck,
    roles: [USER_ROLES.MANAGER, USER_ROLES.SYSTEM_ADMIN],
  },
  {
    name: 'Label Printing',
    href: '/label-printing',
    icon: Printer,
    roles: [USER_ROLES.CASHIER, USER_ROLES.MANAGER, USER_ROLES.SYSTEM_ADMIN],
  },
  {
    name: 'Reports',
    href: '/reports',
    icon: TrendingUp,
    roles: [USER_ROLES.MANAGER, USER_ROLES.SYSTEM_ADMIN],
  },
  {
    name: 'Settings',
    href: '/settings',
    icon: Settings,
    roles: [USER_ROLES.CASHIER, USER_ROLES.MANAGER, USER_ROLES.SYSTEM_ADMIN],
  },
];

export default function Sidebar({ isOpen = true, onClose }) {
  const pathname = usePathname();
  const { user, logout, hasAnyRole } = useAuth();
  const [collapsed, setCollapsed] = useState(false);

  const filteredNavigation = navigation.filter((item) =>
    hasAnyRole(item.roles)
  );

  return (
    <>
      {/* Mobile backdrop */}
      {isOpen && (
        <div
          className="fixed inset-0 bg-black/50 z-40 lg:hidden backdrop-blur-sm"
          onClick={onClose}
        />
      )}

      {/* Sidebar */}
      <aside
        className={`
          fixed top-0 left-0 z-50 h-screen w-64
          bg-white dark:bg-gray-900
          border-r border-gray-200 dark:border-gray-800
          flex flex-col
          transform transition-transform duration-300 ease-out
          ${isOpen ? 'translate-x-0' : '-translate-x-full'}
          lg:translate-x-0 lg:static lg:z-auto
          shadow-lg lg:shadow-none
          ${collapsed ? 'lg:w-20' : 'lg:w-64'}
        `}
      >
        {/* Logo/Brand + desktop collapse toggle */}
        <div className="h-16 flex items-center justify-between border-b border-gray-200 dark:border-gray-800 px-4">
          <h1
            className={`
              font-bold text-gray-900 dark:text-white
              transition-all duration-200
              ${collapsed ? 'hidden lg:block lg:text-sm lg:opacity-0 lg:w-0' : 'text-xl'}
            `}
          >
            XYZ POS
          </h1>
          {collapsed && (
            <div className="hidden lg:flex items-center justify-center w-10 h-10 rounded-xl bg-gradient-to-br from-blue-600 to-indigo-600 text-white font-bold">
              X
            </div>
          )}
          <button
            type="button"
            onClick={() => setCollapsed((prev) => !prev)}
            className="
              hidden lg:flex items-center justify-center
              w-8 h-8 rounded-lg
              text-gray-500 hover:text-gray-900
              dark:text-gray-400 dark:hover:text-gray-100
              hover:bg-gray-100 dark:hover:bg-gray-800
              transition-colors
            "
            aria-label={collapsed ? 'Expand sidebar' : 'Collapse sidebar'}
          >
            {collapsed ? (
              <ChevronRight className="w-4 h-4" />
            ) : (
              <ChevronLeft className="w-4 h-4" />
            )}
          </button>
        </div>

        {/* Navigation */}
        <nav className="flex-1 overflow-y-auto py-4 px-3">
          <ul className="space-y-1">
            {filteredNavigation.map((item) => {
              const isActive = pathname === item.href;
              const Icon = item.icon;

              return (
                <li key={item.name}>
                  <Link
                    href={item.href}
                    className={`
                      flex items-center px-3 py-2.5 rounded-lg
                      text-sm font-medium
                      transition-all duration-200
                      ${
                        isActive
                          ? 'bg-blue-600 text-white shadow-sm'
                          : 'text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800'
                      }
                    `}
                    onClick={() => {
                      if (window.innerWidth < 1024 && onClose) {
                        onClose();
                      }
                    }}
                  >
                    <Icon className="w-5 h-5 mr-3 flex-shrink-0" />
                    <span
                      className={`
                        transition-all duration-200
                        ${collapsed ? 'hidden lg:inline-block lg:opacity-0 lg:w-0' : 'inline-block'}
                      `}
                    >
                      {item.name}
                    </span>
                  </Link>
                </li>
              );
            })}
          </ul>
        </nav>

        {/* User section */}
        <div className="border-t border-gray-200 dark:border-gray-800 p-4">
          {user && (
            <div
              className={`
                mb-3 rounded-lg bg-gray-50 dark:bg-gray-800/50
                ${collapsed ? 'px-0 py-0 flex justify-center' : 'px-3 py-2'}
              `}
              title={collapsed ? `${user.full_name || user.username} • ${user.role}` : undefined}
            >
              {collapsed ? (
                <div className="hidden lg:flex items-center justify-center w-10 h-10 rounded-full bg-blue-600 text-white font-semibold text-sm">
                  {(user.full_name || user.username)?.charAt(0).toUpperCase() || 'U'}
                </div>
              ) : (
                <>
                  <p className="text-sm font-medium text-gray-900 dark:text-white">
                    {user.full_name || user.username}
                  </p>
                  <p className="text-xs text-gray-500 dark:text-gray-400 capitalize">
                    {user.role}
                  </p>
                </>
              )}
            </div>
          )}
          <button
            onClick={logout}
            className={`
              w-full flex items-center rounded-lg
              text-sm font-medium
              text-gray-700 hover:bg-gray-100
              dark:text-gray-300 dark:hover:bg-gray-800
              transition-colors duration-200
              ${collapsed ? 'justify-center px-2 py-2' : 'px-3 py-2'}
            `}
            title={collapsed ? 'Logout' : undefined}
          >
            <LogOut className={`w-5 h-5 ${collapsed ? '' : 'mr-3'}`} />
            {!collapsed && <span>Logout</span>}
          </button>
        </div>
      </aside>
    </>
  );
}
