import { Link, useLocation, useNavigate } from 'react-router-dom';
import { cn, getInitials } from '@/lib/utils';
import { NAVIGATION_GROUPS } from '@/constants';
import { ChevronLeft, ChevronRight, LogOut, User, Settings, Building2 } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { toast } from 'sonner';
import { useAuth } from '@/context/AuthContext';
import { useApp } from '@/context/AppContext';

interface SidebarProps {
  isCollapsed: boolean;
  setIsCollapsed: (value: boolean) => void;
}

export function Sidebar({ isCollapsed, setIsCollapsed }: SidebarProps) {
  const location = useLocation();
  const navigate = useNavigate();
  const { profile, logout, hasPermission } = useAuth();
  const { companySettings } = useApp();

  const handleLogout = async () => {
    try {
      logout();
      toast.success('Logged out successfully');
      navigate('/login');
    } catch (error) {
      toast.error('Failed to log out');
      console.error(error);
    }
  };

  return (
    <aside
      className={cn(
        "fixed left-0 top-0 z-40 h-screen border-r border-border bg-card transition-all duration-300 ease-in-out flex flex-col",
        isCollapsed ? "w-16" : "w-64"
      )}
    >
      <div className="flex h-16 items-center gap-3 px-3 border-b border-border shrink-0">
        <div className="h-9 w-9 rounded-xl bg-primary flex items-center justify-center overflow-hidden shadow-sm ring-1 ring-primary/10 shrink-0">
          {companySettings.logo ? (
            <img 
              src={companySettings.logo} 
              alt="Logo" 
              className="h-full w-full object-contain"
              referrerPolicy="no-referrer"
            />
          ) : (
            <span className="text-primary-foreground font-bold text-lg">
              {getInitials(companySettings.name) || 'M'}
            </span>
          )}
        </div>
        
        <AnimatePresence mode="wait">
          {!isCollapsed && (
            <motion.div 
              initial={{ opacity: 0, x: -10 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: -10 }}
              className="flex flex-1 items-center justify-between min-w-0"
            >
              <span className="text-lg font-bold tracking-tight text-primary truncate mr-2">
                {companySettings.name}
              </span>
              <button
                onClick={() => setIsCollapsed(!isCollapsed)}
                className="rounded-md p-1.5 hover:bg-accent hover:text-accent-foreground transition-colors shrink-0"
              >
                <ChevronLeft size={18} />
              </button>
            </motion.div>
          )}
        </AnimatePresence>

        {isCollapsed && (
          <button
            onClick={() => setIsCollapsed(!isCollapsed)}
            className="rounded-md p-1.5 hover:bg-accent hover:text-accent-foreground transition-colors mx-auto"
          >
            <ChevronRight size={18} />
          </button>
        )}
      </div>

      <nav className="flex-1 overflow-y-auto py-4 scrollbar-thin scrollbar-thumb-border">
        {NAVIGATION_GROUPS.map((group, idx) => {
          const visibleItems = group.items.filter(item => !item.permission || hasPermission(item.permission));
          
          if (visibleItems.length === 0) return null;

          return (
            <div key={group.label} className={cn("mb-6", idx === 0 && "mt-0")}>
              {!isCollapsed && (
                <h3 className="px-6 mb-2 text-[10px] font-bold uppercase tracking-wider text-muted-foreground/70">
                  {group.label}
                </h3>
              )}
              <div className="px-3 space-y-1">
                {visibleItems.map((item) => {
                  const isActive = location.pathname === item.href;
                  return (
                    <Link
                      key={item.href}
                      to={item.href}
                      className={cn(
                        "flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-all group relative",
                        isActive 
                          ? "bg-primary/10 text-primary" 
                          : "text-muted-foreground hover:bg-accent hover:text-accent-foreground",
                        isCollapsed && "justify-center px-2"
                      )}
                      title={isCollapsed ? item.title : undefined}
                    >
                      <item.icon 
                        size={20} 
                        className={cn(
                          "shrink-0 transition-colors",
                          isActive ? "text-primary" : "group-hover:text-accent-foreground"
                        )} 
                      />
                      {!isCollapsed && (
                        <span className="truncate">{item.title}</span>
                      )}
                      {isActive && !isCollapsed && (
                        <motion.div 
                          layoutId="active-nav-indicator"
                          className="absolute left-0 w-1 h-6 bg-primary rounded-r-full"
                        />
                      )}
                    </Link>
                  );
                })}
              </div>
              {idx < NAVIGATION_GROUPS.length - 1 && !isCollapsed && (
                <div className="mx-6 mt-4 border-t border-border/50" />
              )}
            </div>
          );
        })}
      </nav>

      <div className="shrink-0 border-t border-border p-4 bg-card/50 backdrop-blur-sm">
        <div className={cn(
          "flex items-center gap-3",
          isCollapsed ? "justify-center" : "justify-between"
        )}>
          <div className="flex items-center gap-3">
            <div className="h-9 w-9 rounded-full bg-accent flex items-center justify-center border border-border overflow-hidden">
              {profile?.photoURL ? (
                <img 
                  src={profile.photoURL} 
                  alt={profile.name}
                  className="h-full w-full object-cover"
                  referrerPolicy="no-referrer"
                />
              ) : (
                <User size={18} className="text-muted-foreground" />
              )}
            </div>
            {!isCollapsed && (
              <div className="flex flex-col min-w-0">
                <span className="text-sm font-semibold truncate">{profile?.name || 'User'}</span>
                <span className="text-[10px] text-muted-foreground truncate">{profile?.role || 'Member'}</span>
              </div>
            )}
          </div>
          {!isCollapsed && (
            <div className="flex items-center gap-1">
              <Link
                to="/settings"
                className="p-1.5 rounded-md hover:bg-accent text-muted-foreground hover:text-foreground transition-colors"
                title="System Settings"
              >
                <Settings size={18} />
              </Link>
              <button 
                onClick={handleLogout}
                className="p-1.5 rounded-md hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-colors"
                title="Logout"
              >
                <LogOut size={18} />
              </button>
            </div>
          )}
        </div>
      </div>
    </aside>
  );
}
