import React, { useState, useEffect } from 'react';
import { Link, useLocation } from 'react-router-dom';
import { 
  LayoutDashboard, 
  BarChart3,
  ChevronLeft,
  ChevronRight,
  LogOut,
  Menu,
  X,
  CreditCard,
  Receipt,
  User,
  BookOpen,
  CheckCircle2,
  FileText,
  Shield,
  FileCheck,
  Monitor
} from 'lucide-react';
import useAuthStore from '../../store/useAuthStore';
import { useResponsive } from '../../hooks';
import { logger } from '../utils/logger';

interface SidebarAccountantProps {
  isCollapsed?: boolean;
  onToggle?: () => void;
}

const SidebarAccountant: React.FC<SidebarAccountantProps> = ({ 
  isCollapsed: controlledCollapsed,
  onToggle 
}) => {
  const [internalCollapsed, setInternalCollapsed] = useState(false);
  const [isMobileOpen, setIsMobileOpen] = useState(false);
  const location = useLocation();
  const { logout } = useAuthStore();
  const { isMobile, isDesktop } = useResponsive();
  
  const handleLogout = async () => {
    try {
      await logout();
      // Logout function will redirect to homepage
      if (isMobile) {
        setIsMobileOpen(false);
      }
    } catch (error) {
      logger.error('Logout error', error);
    }
  };
  
  // Close mobile menu when screen becomes desktop
  useEffect(() => {
    if (isDesktop) {
      setIsMobileOpen(false);
    }
  }, [isDesktop]);
  
  const isCollapsed = 
    controlledCollapsed !== undefined 
      ? controlledCollapsed 
      : internalCollapsed;
  
  const handleToggle = () => {
    if (onToggle) {
      onToggle();
    } else {
      setInternalCollapsed(!internalCollapsed);
    }
  };

  const handleMobileToggle = () => {
    setIsMobileOpen(!isMobileOpen);
  };

  const handleLinkClick = () => {
    if (isMobile) {
      setIsMobileOpen(false);
    }
  };

  // Menu items for accountant
  const menuItems = [
    { 
      path: '/accountant/dashboard', 
      icon: LayoutDashboard, 
      label: 'Dashboard' 
    },
    { 
      path: '/accountant/payments', 
      icon: CreditCard, 
      label: 'Payments' 
    },
    { 
      path: '/accountant/invoices', 
      icon: Receipt, 
      label: 'Invoices' 
    },
    { 
      path: '/accountant/gl', 
      icon: BookOpen, 
      label: 'General Ledger' 
    },
    { 
      path: '/accountant/approvals', 
      icon: CheckCircle2, 
      label: 'Approvals' 
    },
    { 
      path: '/accountant/reports', 
      icon: BarChart3, 
      label: 'Financial Reports' 
    },
    { 
      path: '/accountant/reconciliation', 
      icon: FileCheck, 
      label: 'Reconciliation' 
    },
    { 
      path: '/accountant/audit-trail', 
      icon: FileText, 
      label: 'Audit Trail' 
    },
    { 
      path: '/accountant/security', 
      icon: Shield, 
      label: 'Security' 
    },
    { 
      path: '/accountant/profile', 
      icon: User, 
      label: 'My Profile' 
    },
    { 
      path: '/accountant/sessions', 
      icon: Monitor, 
      label: 'Session Management' 
    },
  ];

  const isActive = (path: string) => {
    // Exact match
    if (location.pathname === path) return true;
    // Sub-path match
    return location.pathname.startsWith(`${path}/`);
  };

  return (
    <>
      {/* Mobile menu button */}
      {isMobile && (
        <button
          onClick={handleMobileToggle}
          className="fixed top-4 left-4 z-50 lg:hidden p-3 bg-gradient-to-r from-emerald-900 to-emerald-800 text-white rounded-xl shadow-2xl border border-emerald-700 hover:from-emerald-800 hover:to-emerald-700 transition-all duration-200"
          aria-label="Toggle menu"
        >
          {isMobileOpen ? (
            <X className="w-6 h-6" />
          ) : (
            <Menu className="w-6 h-6" />
          )}
        </button>
      )}

      {/* Mobile overlay */}
      {isMobile && isMobileOpen && (
        <div
          className="fixed inset-0 bg-black/60 backdrop-blur-sm z-40 lg:hidden"
          onClick={handleMobileToggle}
        />
      )}

      {/* Sidebar */}
      <aside 
        className={`
          fixed lg:static inset-y-0 left-0 z-40
          bg-gradient-to-b from-emerald-900 via-emerald-800 to-emerald-900
          text-white shadow-2xl
          transition-all duration-300 ease-in-out flex flex-col
          ${isMobile 
            ? (isMobileOpen ? 'translate-x-0' : '-translate-x-full')
            : ''
          }
          ${!isMobile && (isCollapsed ? 'w-20' : 'w-72')}
          ${isMobile ? 'w-72' : ''}
          border-r border-emerald-700/50
        `}
      >
        {/* Header */}
        <div className="p-6 border-b border-emerald-700/50 flex items-center justify-between bg-gradient-to-r from-emerald-800/50 to-emerald-900/50 backdrop-blur-sm">
          {!isCollapsed && (
            <div className="flex items-center gap-3">
              <div className="h-1 w-12 bg-gradient-to-r from-emerald-400 to-emerald-600 rounded-full"></div>
              <h2 className="text-xl font-bold bg-gradient-to-r from-emerald-100 to-emerald-200 bg-clip-text text-transparent">
                Accountant Panel
              </h2>
            </div>
          )}
          {isCollapsed && !isMobile && (
            <div className="w-full flex justify-center">
              <div className="h-8 w-8 bg-gradient-to-br from-emerald-400 to-emerald-600 rounded-xl flex items-center justify-center shadow-lg">
                <span className="text-white font-bold text-sm">A</span>
              </div>
            </div>
          )}
          {!isMobile && (
            <button
              onClick={handleToggle}
              className="p-2.5 rounded-xl bg-emerald-800/50 hover:bg-emerald-700/50 border border-emerald-700/50 hover:border-emerald-500/50 transition-all duration-200 ml-auto shadow-lg hover:shadow-xl"
              aria-label="Toggle sidebar"
            >
              {isCollapsed ? (
                <ChevronRight className="w-5 h-5 text-emerald-200" />
              ) : (
                <ChevronLeft className="w-5 h-5 text-emerald-200" />
              )}
            </button>
          )}
        </div>

        {/* Navigation */}
        <nav className="flex-1 overflow-y-auto py-4 px-3 custom-scrollbar">
          <ul className="space-y-2">
            {menuItems.map((item) => {
              const Icon = item.icon;
              const active = isActive(item.path);
              
              return (
                <li key={item.path}>
                  <Link
                    to={item.path}
                    onClick={handleLinkClick}
                    className={`
                      flex items-center 
                      space-x-3 px-4 py-3.5 rounded-xl 
                      transition-all duration-200 group relative
                      ${active 
                        ? 'bg-gradient-to-r from-emerald-500/20 to-emerald-600/20 text-emerald-100 shadow-lg border border-emerald-500/30' 
                        : 'text-emerald-300 hover:bg-emerald-800/50 hover:text-emerald-100 border border-transparent hover:border-emerald-700/50'
                      }
                      ${isCollapsed && !isMobile ? 'justify-center' : ''}
                    `}
                    title={isCollapsed && !isMobile ? item.label : undefined}
                  >
                    {active && (
                      <div className="absolute left-0 top-1/2 -translate-y-1/2 w-1 h-8 bg-gradient-to-b from-emerald-400 to-emerald-600 rounded-r-full"></div>
                    )}
                    <Icon className={`
                      flex-shrink-0 transition-transform duration-200
                      ${active ? 'text-emerald-400' : 'text-emerald-400 group-hover:text-emerald-300'}
                      ${isCollapsed && !isMobile ? 'w-6 h-6' : 'w-5 h-5'}
                    `} />
                    {(!isCollapsed || isMobile) && (
                      <span className={`
                        font-semibold transition-all duration-200
                        ${active ? 'text-emerald-100' : 'group-hover:text-emerald-100'}
                      `}>
                        {item.label}
                      </span>
                    )}
                    {active && !isCollapsed && (
                      <div className="ml-auto w-2 h-2 bg-emerald-400 rounded-full animate-pulse"></div>
                    )}
                  </Link>
                </li>
              );
            })}
          </ul>
        </nav>

        {/* Logout Button */}
        <div className="p-4 border-t border-emerald-700/50">
          <button
            onClick={handleLogout}
            className={`
              w-full flex items-center 
              space-x-3 px-4 py-3.5 rounded-xl 
              transition-all duration-200 group relative
              text-emerald-300 hover:bg-gradient-to-r hover:from-rose-600/20 hover:to-rose-700/20 
              hover:text-rose-100 border border-transparent hover:border-rose-500/30
              ${isCollapsed && !isMobile ? 'justify-center' : ''}
            `}
            title={isCollapsed && !isMobile ? 'Logout' : undefined}
          >
            <LogOut className={`
              flex-shrink-0 transition-transform duration-200
              text-emerald-400 group-hover:text-rose-400 group-hover:rotate-12
              ${isCollapsed && !isMobile ? 'w-6 h-6' : 'w-5 h-5'}
            `} />
            {(!isCollapsed || isMobile) && (
              <span className="font-semibold transition-all duration-200 group-hover:text-rose-100">
                Logout
              </span>
            )}
          </button>
        </div>

        {/* Footer */}
        <div className="p-4 border-t border-emerald-700/50 bg-gradient-to-r from-emerald-800/50 to-emerald-900/50 backdrop-blur-sm">
          {(!isCollapsed || isMobile) ? (
            <div className="text-xs text-emerald-400 text-center space-y-1">
              <p className="font-semibold text-emerald-200/80">Accountant Dashboard</p>
              <p className="text-emerald-500">
                © {new Date().getFullYear()} Luxury Hotel
              </p>
            </div>
          ) : (
            <div className="flex justify-center">
              <div className="w-3 h-3 bg-gradient-to-br from-emerald-400 to-emerald-600 rounded-full shadow-lg animate-pulse"></div>
            </div>
          )}
        </div>
      </aside>
    </>
  );
};

export default SidebarAccountant;

