import React, { useState } from 'react';
import {
  Files,
  Search,
  Bookmark,
  Settings,
  Trash2,
  LogOut,
} from 'lucide-react';
import { useEditorStore, SETTINGS_TAB_FILE_ID } from '@/core/store';
import { useAuth } from '@/contexts/AuthContext';
import { useNavigate } from 'react-router-dom';
import type { SidebarPanel } from '@/core/types';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';

interface ActivityItem {
  id: SidebarPanel | string;
  icon: React.ReactNode;
  label: string;
  shortcut?: string;
}

const activityItems: ActivityItem[] = [
  { id: 'explorer', icon: <Files className="w-5 h-5" />, label: 'Explorer', shortcut: 'Ctrl+Shift+E' },
  { id: 'search', icon: <Search className="w-5 h-5" />, label: 'Search', shortcut: 'Ctrl+Shift+F' },
  { id: 'bookmarks', icon: <Bookmark className="w-5 h-5" />, label: 'Bookmarks', shortcut: 'Ctrl+Shift+B' },
];

const bottomItems: ActivityItem[] = [
  { id: 'trash', icon: <Trash2 className="w-5 h-5" />, label: 'Trash' },
  { id: 'settings', icon: <Settings className="w-5 h-5" />, label: 'Settings', shortcut: 'Ctrl+,' },
  { id: 'logout', icon: <LogOut className="w-5 h-5" />, label: 'Logout' },
];

export const ActivityBar: React.FC = () => {
  const { activeSidebarPanel, setActiveSidebarPanel, isSidebarOpen, toggleSidebar, openSettingsTab, activeTabId, openTabs } = useEditorStore();
  const isSettingsTabActive = Boolean(activeTabId && openTabs.find((t) => t.id === activeTabId)?.fileId === SETTINGS_TAB_FILE_ID);
  const { logout } = useAuth();
  const navigate = useNavigate();
  const [logoutDialogOpen, setLogoutDialogOpen] = useState(false);

  const handleClick = (id: string) => {
    if (id === 'logout') {
      setLogoutDialogOpen(true);
      return;
    }
    if (id === 'settings') {
      openSettingsTab();
      setActiveSidebarPanel('explorer');
      return;
    }
    if (id === 'explorer' || id === 'search' || id === 'bookmarks' || id === 'trash') {
      if (activeSidebarPanel === id && isSidebarOpen) {
        toggleSidebar();
      } else {
        setActiveSidebarPanel(id as SidebarPanel);
      }
    }
  };

  return (
    <TooltipProvider delayDuration={300}>
      <div className="w-12 bg-activitybar flex flex-col items-center py-2 border-r border-sidebar-border">
        <div className="flex flex-col gap-1">
          {activityItems.map((item) => {
            const isActive = activeSidebarPanel === item.id && isSidebarOpen;
            return (
              <Tooltip key={item.id}>
                <TooltipTrigger asChild>
                  <button
                    type="button"
                    className={`relative w-10 h-10 flex items-center justify-center rounded-lg ${
                      isActive
                        ? 'text-primary bg-primary/10'
                        : 'text-activitybar-foreground hover:text-foreground hover:bg-white/5'
                    }`}
                    onClick={() => handleClick(item.id)}
                  >
                    {isActive && (
                      <div
                        className="absolute left-0 top-1/2 -translate-y-1/2 w-0.5 h-6 bg-primary rounded-r"
                        style={{ boxShadow: '0 0 8px hsl(var(--primary))' }}
                      />
                    )}
                    {item.icon}
                  </button>
                </TooltipTrigger>
                <TooltipContent side="right" className="flex items-center gap-2">
                  <span>{item.label}</span>
                  {item.shortcut && (
                    <kbd className="text-[10px] font-mono bg-muted px-1 py-0.5 rounded">
                      {item.shortcut}
                    </kbd>
                  )}
                </TooltipContent>
              </Tooltip>
            );
          })}
        </div>

        <div className="flex-1" />

        <div className="flex flex-col gap-1">
          {bottomItems.map((item) => {
            const isActive = item.id === 'settings' ? isSettingsTabActive : (activeSidebarPanel === item.id && isSidebarOpen);
            return (
              <Tooltip key={item.id}>
                <TooltipTrigger asChild>
                  <button
                    type="button"
                    className={`relative w-10 h-10 flex items-center justify-center rounded-lg ${
                      isActive
                        ? 'text-primary bg-primary/10'
                        : 'text-activitybar-foreground hover:text-foreground hover:bg-white/5'
                    }`}
                    onClick={() => handleClick(item.id)}
                  >
                    {item.icon}
                  </button>
                </TooltipTrigger>
                <TooltipContent side="right" className="flex items-center gap-2">
                  <span>{item.label}</span>
                  {item.shortcut && (
                    <kbd className="text-[10px] font-mono bg-muted px-1 py-0.5 rounded">
                      {item.shortcut}
                    </kbd>
                  )}
                </TooltipContent>
              </Tooltip>
            );
          })}
        </div>
      </div>

      {/* Logout Confirmation Dialog */}
      <AlertDialog open={logoutDialogOpen} onOpenChange={setLogoutDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Logout?</AlertDialogTitle>
            <AlertDialogDescription>
              Are you sure you want to logout? You'll need to sign in again to access your notes.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => {
                logout();
                navigate('/login');
                setLogoutDialogOpen(false);
              }}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              Logout
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </TooltipProvider>
  );
};

export default ActivityBar;
