import React, { useState, useEffect } from 'react';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import { useLanguage } from '../contexts/LanguageContext';
import { useSidebarLayout } from '../contexts/SidebarLayoutContext';
import { useTranslation } from 'react-i18next';
import {
  Menu,
  X,
  FolderOpen,
  LayoutDashboard,
  List,
  ClipboardList,
  Clock,
  Tags,
  FileStack,
  UserCircle,
} from 'lucide-react';
import { FaChevronDown, FaChevronUp } from 'react-icons/fa';

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

interface SidebarProps {
  userEmail?: string;
}

function useLgUp(): boolean {
  const [lg, setLg] = useState(() =>
    typeof window !== 'undefined' ? window.matchMedia('(min-width: 1024px)').matches : false
  );
  useEffect(() => {
    const mq = window.matchMedia('(min-width: 1024px)');
    const onChange = () => setLg(mq.matches);
    mq.addEventListener('change', onChange);
    return () => mq.removeEventListener('change', onChange);
  }, []);
  return lg;
}

const Sidebar: React.FC<SidebarProps> = () => {
  const [isCollapsed, setIsCollapsed] = useState(false);
  const [isProjectsExpanded, setIsProjectsExpanded] = useState(true);
  const location = useLocation();
  const navigate = useNavigate();
  const isLgUp = useLgUp();
  const { isRTL } = useLanguage();
  const { t } = useTranslation();
  const { mobileSidebarOpen, closeMobileSidebar } = useSidebarLayout();

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

  const edgeBorderClass = isRTL
    ? 'border-l border-gray-200 dark:border-gray-700'
    : 'border-r border-gray-200 dark:border-gray-700';
  const activeEdgeBorderClass = isRTL ? 'border-r-4 border-white' : 'border-l-4 border-white';

  const baseUrl = import.meta.env.BASE_URL || '/assets/project_management/pm_app/';
  const backgroundImageUrl = `${baseUrl}${baseUrl.endsWith('/') ? '' : '/'}sidebar-background.jpg`;
  const logoVersion = '?v=1781183030';

  const mainLinks: SidebarLink[] = [
    { id: 'hub', title: t('sidebar.projects', { defaultValue: 'Project Management' }), icon: <FolderOpen size={20} />, path: '/projects' },
    { id: 'reports', title: 'Dashboard', icon: <LayoutDashboard size={20} />, path: '/projects/reports' },
    { id: 'list', title: 'Projects', icon: <List size={20} />, path: '/projects/list' },
    { id: 'tasks', title: 'Tasks', icon: <ClipboardList size={20} />, path: '/projects/tasks' },
    { id: 'timesheets', title: 'Timesheets', icon: <Clock size={20} />, path: '/projects/timesheets' },
    { id: 'activity-types', title: 'Activity Types', icon: <Tags size={20} />, path: '/projects/activity-types' },
    { id: 'templates', title: 'Templates', icon: <FileStack size={20} />, path: '/projects/templates' },
    { id: 'profile', title: t('sidebar.userProfile', { defaultValue: 'User Profile' }), icon: <UserCircle size={20} />, path: '/user-profile' },
  ];

  const isActive = (path: string) =>
    location.pathname === path || location.pathname.startsWith(`${path}/`);

  const isProjectsActive =
    location.pathname === '/projects' || location.pathname.startsWith('/projects/');

  const mobileDrawerShell = mobileSidebarOpen
    ? `fixed inset-y-0 ${isRTL ? 'right-0' : 'left-0'} z-50 lg:static lg:z-auto`
    : `fixed inset-y-0 ${isRTL ? 'right-0' : 'left-0'} z-50 -translate-x-full lg:static lg:translate-x-0 lg:z-auto`;

  return (
    <>
      {mobileSidebarOpen && (
        <div
          className="pm-app-sidebar-backdrop fixed inset-0 z-40 bg-black/50 lg:hidden"
          onClick={closeMobileSidebar}
          aria-label={t('common.close', { defaultValue: 'Close menu' })}
        />
      )}
      <div
        className={`pm-app-sidebar h-screen transition-all duration-300 ease-in-out flex flex-col shadow-xl ${edgeBorderClass} ${isCollapsed ? 'w-16' : 'w-64'} ${mobileDrawerShell}`}
        style={{
          backgroundImage: `url(${backgroundImageUrl})`,
          backgroundSize: 'cover',
          backgroundPosition: 'center',
          backgroundRepeat: 'no-repeat',
        }}
      >
        <div className="absolute inset-0 bg-black/60 dark:bg-black/70 z-0" />
        <div className="relative z-10 flex flex-col h-full">
          <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 rounded-lg p-1 backdrop-blur-sm">
                  <img
                    src={`${baseUrl}${baseUrl.endsWith('/') ? '' : '/'}seera-logo.png${logoVersion}`}
                    alt="Project Management"
                    className="w-full h-full object-contain"
                  />
                </div>
                <h1 className="text-white text-lg font-semibold drop-shadow-lg">
                  {t('sidebar.pmTitle', { defaultValue: 'Project Management' })}
                </h1>
              </div>
            )}
            <button
              type="button"
              onClick={() => {
                if (isLgUp) setIsCollapsed(!isCollapsed);
                else closeMobileSidebar();
              }}
              className="text-white hover:bg-white/20 p-2 rounded-lg transition-colors"
            >
              {isLgUp ? (isCollapsed ? <Menu size={20} /> : <X size={20} />) : <X size={20} />}
            </button>
          </div>

          <nav className="flex-1 overflow-y-auto py-4">
            <button
              type="button"
              onClick={() => {
                if (isCollapsed) {
                  navigate('/projects');
                  afterNav();
                  return;
                }
                setIsProjectsExpanded((v) => !v);
              }}
              className={`w-full flex items-center px-4 py-3 text-white hover:bg-white/20 transition-all duration-200 ${isProjectsActive ? `bg-white/30 ${activeEdgeBorderClass}` : ''} ${isCollapsed ? 'justify-center' : ''}`}
            >
              <FolderOpen size={20} />
              {!isCollapsed && (
                <>
                  <span className={`${isRTL ? 'mr-4' : 'ml-4'} font-medium flex-1 text-left`}>
                    {t('sidebar.projects', { defaultValue: 'Project Management' })}
                  </span>
                  <span className="opacity-80">
                    {isProjectsExpanded ? <FaChevronUp size={12} /> : <FaChevronDown size={12} />}
                  </span>
                </>
              )}
            </button>

            {!isCollapsed && isProjectsExpanded && (
              <div className={`${isRTL ? 'pr-6' : 'pl-6'} pb-2`}>
                {mainLinks.map((link) => (
                  <Link
                    key={link.id}
                    to={link.path}
                    onClick={afterNav}
                    className={`flex items-center gap-2 px-4 py-2 text-white/90 hover:text-white hover:bg-white/15 rounded-lg transition-colors ${isActive(link.path) ? 'bg-white/20' : ''}`}
                  >
                    <span className="shrink-0">{link.icon}</span>
                    <span className="text-sm font-medium">{link.title}</span>
                  </Link>
                ))}
              </div>
            )}
          </nav>
        </div>
      </div>
    </>
  );
};

export default Sidebar;
