import React, { useEffect, useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { useLanguage } from '../contexts/LanguageContext';
import { useSidebarLayout } from '../contexts/SidebarLayoutContext';
import { useTranslation } from 'react-i18next';
import useRoleProfile from '../hooks/useRoleProfile';
import {
  isEndUserRole,
  isTechnicianRole,
  isSidebarLinkVisible,
  type SidebarLinkId,
} from '../utils/roleAccess';
import { 
  LayoutDashboard,
  Package,
  Menu,
  X,
  ClipboardList,
  Calendar,
  CalendarCheck,
  Map,
  Users,
  ShoppingCart,
  FileText,
  HelpCircle,
} from 'lucide-react';

interface SidebarLink {
  id: string;
  title: string;
  icon: React.ReactNode;
  path: string;
  visible: boolean;
}

interface SidebarProps {
  userEmail?: string;
}

function useLgUp(): boolean {
  const [isLgUp, setIsLgUp] = useState(() =>
    typeof window !== 'undefined' ? window.matchMedia('(min-width: 1024px)').matches : true
  );

  useEffect(() => {
    const mq = window.matchMedia('(min-width: 1024px)');
    const handleChange = () => setIsLgUp(mq.matches);
    handleChange();
    mq.addEventListener('change', handleChange);
    return () => mq.removeEventListener('change', handleChange);
  }, []);

  return isLgUp;
}

const Sidebar: React.FC<SidebarProps> = ({ userEmail }) => {
  const [isCollapsed, setIsCollapsed] = useState(false);
  const location = useLocation();
  const { isRTL } = useLanguage();
  const { t } = useTranslation();
  const { closeMobileSidebar } = useSidebarLayout();
  const isLgUp = useLgUp();
  const { roleProfile } = useRoleProfile();
  const isRoleRestricted = isEndUserRole(roleProfile) || isTechnicianRole(roleProfile);

  // Get base URL for assets (handles both dev and production)
  // BASE_URL in Vite already includes trailing slash in production, but not in dev
  const baseUrl = import.meta.env.BASE_URL || '/';
  // Add cache-busting query parameter to force browser to reload updated images
  // Version is automatically updated by build script based on file modification time
  const imageVersion = import.meta.env.DEV 
    ? `?v=${Date.now()}` 
    : `?v=1785757497`; // Auto-updated by build script
  const logoVersion = import.meta.env.DEV 
    ? `?v=${Date.now()}` 
    : `?v=1785757497`; // Auto-updated by build script
  const backgroundImageUrl = baseUrl.endsWith('/') 
    ? `${baseUrl}sidebar-background.jpg${imageVersion}`
    : `${baseUrl}/sidebar-background.jpg${imageVersion}`;

  const isFinanceManager = userEmail === 'financemanager@gmail.com';

  const getDefaultLinkVisibility = (linkId: SidebarLinkId): boolean => {
    switch (linkId) {
      case 'assets':
      case 'work-orders':
      case 'ppm-planner':
      case 'maintenance-calendar':
        return !isFinanceManager;
      default:
        return true;
    }
  };

  const links: SidebarLink[] = [
    {
      id: 'dashboard',
      title: t('common.dashboard'),
      icon: <LayoutDashboard size={20} />,
      path: '/dashboard',
      visible: isRoleRestricted
        ? isSidebarLinkVisible('dashboard', roleProfile)
        : getDefaultLinkVisibility('dashboard')
    },
    {
      id: 'assets',
      title: t('common.assets'),
      icon: <Package size={20} />,
      path: '/assets',
      visible: isRoleRestricted
        ? isSidebarLinkVisible('assets', roleProfile)
        : getDefaultLinkVisibility('assets')
    },
    {
      id: 'inventory',
      title: 'Inventory',
      icon: <Package size={20} />,
      path: '/inventory',
      visible: isRoleRestricted
        ? isSidebarLinkVisible('inventory', roleProfile)
        : getDefaultLinkVisibility('inventory')
    },
    {
      id: 'work-orders',
      title: t('common.workOrders'),
      icon: <ClipboardList size={20} />,
      path: '/work-orders',
      visible: isRoleRestricted
        ? isSidebarLinkVisible('work-orders', roleProfile)
        : getDefaultLinkVisibility('work-orders')
    },
    // {
    //   id: 'maintenance',
    //   title: t('common.maintenance'),
    //   icon: <Wrench size={20} />,
    //   path: '/maintenance',
    //   visible: showPreventiveMaintenance
    // },
    // {
    //   id: 'ppm',
    //   title: t('common.ppm'),
    //   icon: <Calendar size={20} />,
    //   path: '/ppm',
    //   visible: showPreventiveMaintenance
    // },
    {
      id: 'ppm-planner',
      title: 'PPM Planner',
      icon: <CalendarCheck size={20} />,
      path: '/ppm-planner',
      visible: isRoleRestricted
        ? isSidebarLinkVisible('ppm-planner', roleProfile)
        : getDefaultLinkVisibility('ppm-planner')
    },
    {
      id: 'maintenance-calendar',
      title: 'Maintenance Calendar',
      icon: <Calendar size={20} />,
      path: '/maintenance-calendar',
      visible: isRoleRestricted
        ? isSidebarLinkVisible('maintenance-calendar', roleProfile)
        : getDefaultLinkVisibility('maintenance-calendar')
    },
    {
      id: 'active-map',
      title: 'Active Map',
      icon: <Map size={20} />,
      path: '/active-map',
      visible: isRoleRestricted
        ? isSidebarLinkVisible('active-map', roleProfile)
        : getDefaultLinkVisibility('active-map')
    },
    {
      id: 'maintenance-teams',
      title: 'Maintenance Team',
      icon: <Users size={20} />,
      path: '/maintenance-teams',
      visible: isRoleRestricted
        ? isSidebarLinkVisible('maintenance-teams', roleProfile)
        : getDefaultLinkVisibility('maintenance-teams')
    },
    {
      id: 'procurement',
      title: 'Procurement',
      icon: <ShoppingCart size={20} />,
      path: '/procurement',
      visible: isRoleRestricted
        ? isSidebarLinkVisible('procurement', roleProfile)
        : getDefaultLinkVisibility('procurement')
    },
    {
      id: 'sla',
      title: 'Service Level Agreement (SLA)',
      icon: <FileText size={20} />,
      path: '/sla',
      visible: isRoleRestricted
        ? isSidebarLinkVisible('sla', roleProfile)
        : getDefaultLinkVisibility('sla')
    },
    {
      id: 'support',
      title: 'Support',
      icon: <HelpCircle size={20} />,
      path: '/support',
      visible: isRoleRestricted
        ? isSidebarLinkVisible('support', roleProfile)
        : getDefaultLinkVisibility('support')
    },
    
    // {
    //   id: 'vendors',
    //   title: 'Vendors',
    //   icon: <Truck size={20} />,
    //   path: '/vendors',
    //   visible: showSupplierDashboard
    // },
    // {
    //   id: 'dashboard-view',
    //   title: 'Dashboard',
    //   icon: <BarChart3 size={20} />,
    //   path: '/dashboard-view',
    //   visible: showProjectDashboard
    // },
    // {
    //   id: 'sites',
    //   title: 'Sites',
    //   icon: <Building2 size={20} />,
    //   path: '/sites',
    //   visible: showSiteDashboards
    // },
    // {
    //   id: 'active-map',
    //   title: 'Active Map',
    //   icon: <MapPin size={20} />,
    //   path: '/active-map',
    //   visible: showSiteInfo
    // },
    // {
    //   id: 'users',
    //   title: 'Users',
    //   icon: <Users size={20} />,
    //   path: '/users',
    //   visible: showAMTeam
    // },
    // {
    //   id: 'account',
    //   title: 'Account',
    //   icon: <FileText size={20} />,
    //   path: '/account',
    //   visible: showSLA
    // }
  ];

  const visibleLinks = links.filter(link => link.visible);

  const isActive = (path: string) => {
    return location.pathname === path;
  };

  const afterNav = () => {
    if (!isLgUp) {
      closeMobileSidebar();
    }
  };

  return (
    <div 
      className={`
        relative
        h-screen 
        transition-all 
        duration-300 
        ease-in-out
        flex 
        flex-col
        shadow-xl
        border-r border-gray-200 dark:border-gray-700
        w-64
        ${isCollapsed ? 'lg:w-16' : 'lg:w-64'}
      `}
      style={{
        backgroundImage: `url(${backgroundImageUrl})`, 
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat'
      }}
    >
      {/* Black Overlay */}
      <div className="absolute inset-0 bg-black/60 dark:bg-black/70 z-0"></div>
      
      {/* Content Container - Above Overlay */}
      <div className="relative z-10 flex flex-col h-full bg-white/0 dark:bg-white/0">
      {/* Sidebar Header */}
        <div className="flex items-center justify-between p-4 border-b border-gray-200/30 dark:border-gray-700/30">
        {!isCollapsed && (
          <div className="flex items-center space-x-3">
            <div className="w-10 h-10 flex items-center justify-center bg-white/20 dark:bg-white/20 rounded-lg p-1 backdrop-blur-sm">
              {/* Seera Arabia Logo */}
              <img 
                src={`${baseUrl}${baseUrl.endsWith('/') ? '' : '/'}seera-logo.png${logoVersion}`}
                alt="Seera-ASM" 
                className="w-full h-full object-contain"
                onError={(e) => {
                  // Fallback to SVG if image not found
                  e.currentTarget.style.display = 'none';
                  e.currentTarget.nextElementSibling?.classList.remove('hidden');
                }}
              />
              <svg className="w-6 h-6 hidden" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M12 2L2 7L12 12L22 7L12 2Z" fill="#6366F1" fillOpacity="0.9"/>
                <path d="M2 17L12 22L22 17V12L12 17L2 12V17Z" fill="#8B5CF6" fillOpacity="0.7"/>
                <path d="M12 12V17" stroke="#A855F7" strokeWidth="2" strokeLinecap="round"/>
              </svg>
            </div>
            <h1 className="text-white dark:text-white text-lg font-semibold drop-shadow-lg">{t('sidebar.title')}</h1>
          </div>
        )}
        {isCollapsed && (
          <div className="w-8 h-8 flex items-center justify-center bg-white dark:bg-gray-700 rounded-lg p-1">
            <img 
              src={`${baseUrl}${baseUrl.endsWith('/') ? '' : '/'}seera-logo.png?v=1765198405${logoVersion}`}
              alt="Seera-ASM" 
              className="w-full h-full object-contain"
              onError={(e) => {
                e.currentTarget.style.display = 'none';
                e.currentTarget.nextElementSibling?.classList.remove('hidden');
              }}
            />
            <svg className="w-5 h-5 hidden" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M12 2L2 7L12 12L22 7L12 2Z" fill="#6366F1" fillOpacity="0.9"/>
              <path d="M2 17L12 22L22 17V12L12 17L2 12V17Z" fill="#8B5CF6" fillOpacity="0.7"/>
              <path d="M12 12V17" stroke="#A855F7" strokeWidth="2" strokeLinecap="round"/>
            </svg>
          </div>
        )}
        <button
          onClick={() => setIsCollapsed(!isCollapsed)}
          className="hidden lg:inline-flex text-white dark:text-white hover:bg-white/20 dark:hover:bg-white/20 p-2 rounded-lg transition-colors"
        >
          {isCollapsed ? <Menu size={20} /> : <X size={20} />}
        </button>
      </div>

      {/* Navigation Links */}
      <nav className="flex-1 overflow-y-auto py-4">
        {visibleLinks.map((link) => (
          <Link
            key={link.id}
            to={link.path}
            onClick={afterNav}
            className={`
              flex 
              items-center 
              px-4 
              py-3 
              text-white dark:text-white 
              hover:bg-white/20 dark:hover:bg-white/20 
              hover:text-white dark:hover:text-white 
              transition-all 
              duration-200
              ${isActive(link.path) ? 'bg-white/30 dark:bg-white/30 text-white dark:text-white border-l-4 border-white' : ''}
              ${isCollapsed ? 'justify-center' : ''}
            `}
            title={isCollapsed ? link.title : ''}
          >
             <span>{link.icon}</span>
            {!isCollapsed && (
              <span className={`${isRTL ? 'mr-4' : 'ml-4'} font-medium`}>{link.title}</span>
            )}
          </Link>
        ))}
      </nav>

      {/* Version (Bottom) */}
      <div className={`${isCollapsed ? 'p-2' : 'p-4'} border-t border-white/10 backdrop-blur-sm bg-white/5 relative z-10`}>
        {!isCollapsed && (
          <div className="text-xs text-white/70 dark:text-white/70 text-center">
            {t('sidebar.version')}
          </div>
        )}
      </div>
      </div>
    </div>
  );
};

export default Sidebar;

