import { useState } from 'react';
import { NavLink, useNavigate, useLocation } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import {
  LayoutDashboard,
  CheckSquare,
  Calendar,
  Bell,
  FolderKanban,
  Users,
  MapPin,
  Settings,
  ChevronLeft,
  ChevronRight,
  ChevronDown,
  X,
  LogOut,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useAuth } from '@/hooks/useAuth';
import { Button } from '@/components/ui/button';
import api from '@/lib/api';
import type { Project } from '@/types';

const navItems = [
  { to: '/dashboard', icon: LayoutDashboard, label: 'Dashboard' },
  { to: '/todos', icon: CheckSquare, label: 'Todos' },
  { to: '/calendar', icon: Calendar, label: 'Calendar' },
  { to: '/reminders', icon: Bell, label: 'Reminders' },
  { to: '/people', icon: Users, label: 'People' },
  { to: '/locations', icon: MapPin, label: 'Locations' },
];

interface SidebarProps {
  collapsed: boolean;
  onToggle: () => void;
  mobileOpen: boolean;
  onMobileClose: () => void;
}

export default function Sidebar({ collapsed, onToggle, mobileOpen, onMobileClose }: SidebarProps) {
  const navigate = useNavigate();
  const location = useLocation();
  const { logout } = useAuth();
  const [projectsExpanded, setProjectsExpanded] = useState(false);

  const { data: trackedProjects } = useQuery({
    queryKey: ['projects', 'tracked'],
    queryFn: async () => {
      const { data } = await api.get<Project[]>('/projects?tracked=true');
      return data;
    },
    staleTime: 60_000,
    select: (data) => data.map(({ id, name }) => ({ id, name })),
  });

  const handleLogout = async () => {
    await logout();
    navigate('/login');
  };

  const isProjectsActive = location.pathname.startsWith('/projects');
  const showExpanded = !collapsed || mobileOpen;

  const navLinkClass = ({ isActive }: { isActive: boolean }) =>
    cn(
      'flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-all duration-200',
      isActive
        ? 'bg-accent/15 text-accent border-l-2 border-accent'
        : 'text-muted-foreground hover:bg-accent/10 hover:text-accent border-l-2 border-transparent'
    );

  const projectsSection = (
    <div>
      <div
        className={cn(
          'flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-all duration-200 border-l-2',
          isProjectsActive
            ? 'bg-accent/15 text-accent border-accent'
            : 'text-muted-foreground hover:bg-accent/10 hover:text-accent border-transparent'
        )}
      >
        <FolderKanban
          className="h-5 w-5 shrink-0 cursor-pointer"
          onClick={() => {
            navigate('/projects');
            if (mobileOpen) onMobileClose();
          }}
        />
        {showExpanded && (
          <>
            <span
              className="flex-1 cursor-pointer"
              onClick={() => {
                navigate('/projects');
                if (mobileOpen) onMobileClose();
              }}
            >
              Projects
            </span>
            {trackedProjects && trackedProjects.length > 0 && (
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  setProjectsExpanded(!projectsExpanded);
                }}
                className="p-0.5 rounded hover:bg-accent/10 transition-colors"
              >
                <ChevronDown
                  className={cn(
                    'h-3.5 w-3.5 transition-transform duration-200',
                    projectsExpanded ? 'rotate-0' : '-rotate-90'
                  )}
                />
              </button>
            )}
          </>
        )}
      </div>
      {showExpanded && projectsExpanded && trackedProjects && trackedProjects.length > 0 && (
        <div className="mt-0.5 space-y-0.5">
          {trackedProjects.map((project) => {
            const isActive = location.pathname === `/projects/${project.id}`;
            return (
              <button
                key={project.id}
                onClick={() => {
                  navigate(`/projects/${project.id}`);
                  if (mobileOpen) onMobileClose();
                }}
                className={cn(
                  'flex items-center w-full text-left pl-9 pr-3 py-1.5 text-xs rounded-md transition-colors duration-150 truncate',
                  isActive
                    ? 'text-accent bg-accent/10'
                    : 'text-muted-foreground hover:text-foreground hover:bg-card-elevated'
                )}
              >
                <span className="truncate">{project.name}</span>
              </button>
            );
          })}
        </div>
      )}
    </div>
  );

  const sidebarContent = (
    <>
      <div className="flex h-16 items-center justify-between border-b px-4">
        {!collapsed && <h1 className="font-heading text-xl font-bold tracking-tight text-accent">UMBRA</h1>}
        <Button
          variant="ghost"
          size="icon"
          onClick={mobileOpen ? onMobileClose : onToggle}
          className="ml-auto"
        >
          {mobileOpen ? (
            <X className="h-5 w-5" />
          ) : collapsed ? (
            <ChevronRight className="h-5 w-5" />
          ) : (
            <ChevronLeft className="h-5 w-5" />
          )}
        </Button>
      </div>

      <nav className="flex-1 space-y-1 p-2">
        {navItems.map((item) => (
          <NavLink
            key={item.to}
            to={item.to}
            onClick={mobileOpen ? onMobileClose : undefined}
            className={navLinkClass}
          >
            <item.icon className="h-5 w-5 shrink-0" />
            {showExpanded && <span>{item.label}</span>}
          </NavLink>
        ))}
        {projectsSection}
      </nav>

      <div className="border-t p-2 space-y-1">
        <NavLink
          to="/settings"
          onClick={mobileOpen ? onMobileClose : undefined}
          className={navLinkClass}
        >
          <Settings className="h-5 w-5 shrink-0" />
          {showExpanded && <span>Settings</span>}
        </NavLink>
        <button
          onClick={handleLogout}
          className="flex w-full items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive"
        >
          <LogOut className="h-5 w-5 shrink-0" />
          {showExpanded && <span>Logout</span>}
        </button>
      </div>
    </>
  );

  return (
    <>
      {/* Desktop sidebar */}
      <aside
        className={cn(
          'hidden md:flex flex-col border-r bg-card transition-all duration-300',
          collapsed ? 'w-16' : 'w-64'
        )}
      >
        {sidebarContent}
      </aside>

      {/* Mobile overlay */}
      {mobileOpen && (
        <div className="fixed inset-0 z-40 md:hidden">
          <div className="absolute inset-0 bg-background/80 backdrop-blur-sm" onClick={onMobileClose} />
          <aside className="relative z-50 flex flex-col w-64 h-full bg-card border-r">
            {sidebarContent}
          </aside>
        </div>
      )}
    </>
  );
}
