import React, { useCallback, useState } from 'react';
import { NewChatIcon } from '../../assets/icons';
import { WPAssistantLogo } from '../Logos/WPAssistantLogo';
import ConversationGroup from './ConversationGroup';
import { useTheme } from '../../contexts/ThemeContext';
import useGroupedConversations from '../../hooks/useGroupedConversations';
import { useAuth } from '../../contexts/AuthContext';
import { 
  useCurrentConversationId, 
  useConversations,
  useSetCurrentConversationId,
} from '../../contexts/ChatContext';
import { 
  useSetIsLoginModalOpen,
  useSetIsConfirmDeleteModalOpen,
  useSetConfirmDeleteConversationId,
  useSetConfirmDeleteConversationName,
  useSetIsSettingsModalOpen
} from '../../contexts/UIContext';
import useRenderTracker from '../../hooks/useRenderTracker';
import QuickLinks from './QuickLinks';
import { IS_WORDPRESS } from '../../constants';

const Sidebar: React.FC = () => {

  const setIsLoginModalOpen = useSetIsLoginModalOpen();
  const setIsConfirmDeleteModalOpen = useSetIsConfirmDeleteModalOpen();
  const setConfirmDeleteConversationId = useSetConfirmDeleteConversationId();
  const setIsSettingsModalOpen = useSetIsSettingsModalOpen();
  const setConfirmDeleteConversationName = useSetConfirmDeleteConversationName();

  const { effectiveTheme, setTheme } = useTheme();
  const { isLoggedIn } = useAuth();
  const currentConversationId = useCurrentConversationId();
  const setCurrentConversationId = useSetCurrentConversationId();
  const conversations = useConversations();
  const groupedConversations = useGroupedConversations({ conversations });

  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);


  useRenderTracker('Sidebar', {
    setIsLoginModalOpen,
    setIsConfirmDeleteModalOpen,
    setConfirmDeleteConversationId,
    setIsSettingsModalOpen,
    setConfirmDeleteConversationName,
    effectiveTheme,
    setTheme,
    isLoggedIn,
    conversations,
    groupedConversations,
    currentConversationId,
    setCurrentConversationId,
  });

  const toggleSidebar = useCallback(() => {
    setIsSidebarCollapsed((prev) => !prev);
  }, [setIsSidebarCollapsed]);

  const handleNewChat = useCallback(() => {
    setCurrentConversationId(null);
  }, [setCurrentConversationId, currentConversationId]);

  const handleSelectConversation = useCallback(
    (conversationId: string) => {
      setCurrentConversationId(conversationId);
    },
    [setCurrentConversationId]
  );

  const onDeleteConversation = useCallback(
    (conversationName: string, conversationId: string) => {
      setConfirmDeleteConversationName(conversationName);
      setConfirmDeleteConversationId(conversationId);
      setIsConfirmDeleteModalOpen(true);
    },
    [
      setConfirmDeleteConversationName,
      setConfirmDeleteConversationId,
      setIsConfirmDeleteModalOpen,
    ]
  );

  return (
    <div className="relative hidden md:block h-full">
      <aside
        className={`transition-all duration-200 ease-in-out bg-gradient-to-r from-background-light to-gray-300/10 dark:from-background-dark dark:to-gray-600/5 rounded-xl w-[280px] bg-card text-card-foreground h-full border-r-1 border-gray-200 dark:border-gray-700 ${
          isSidebarCollapsed ? 'ml-[-280px]' : 'ml-0'
        }`}
      >
        <div className="p-4 flex flex-col h-full min-h-0">
          <div className="flex justify-between items-center pb-12">
            <span className="px-1">
              <WPAssistantLogo size={20} />
            </span>
            <div className="relative flex items-center group">
              <button
                onClick={handleNewChat}
                className="p-1 rounded-md transition-colors duration-0 hover:bg-primary/10 dark:hover:bg-primary/40 flex items-center"
                aria-label="New Chat"
              >
                <NewChatIcon />
              </button>
              <span
                className="absolute z-10 -bottom-12 left-1/2 transform -translate-x-1/2 bg-black text-white px-3 py-1.5 rounded text-sm opacity-0 delay-0 group-hover:opacity-100 transition-opacity group-hover:delay-200 whitespace-nowrap shadow-xl pointer-events-none"
              >
                New Chat
              </span>
            </div>
          </div>

          <nav className="flex-1 min-h-0 overflow-y-auto space-y-4 pr-3 -mr-4 scrollbar-custom">
            {groupedConversations.map(({ category, conversations }) => (
              <ConversationGroup
                key={category}
                category={category}
                conversations={conversations}
                currentConversationId={currentConversationId}
                onSelectConversation={handleSelectConversation}
                onDeleteConversation={onDeleteConversation}
              />
            ))}
          </nav>

          <div className="mt-auto pt-4 border-t border-border border-gray-200 dark:border-gray-700">
            {!isLoggedIn && (
              <button 
                className="w-full text-sm text-left py-2 px-3 mb-1 rounded-lg dark:text-gray-400 text-gray-500 hover:text-foreground dark:hover:bg-secondary/40 hover:bg-secondary/10 transition-colors duration-0"
                onClick={() => setIsLoginModalOpen(true)} 
              > 
                Login / Sign Up
              </button>
            )}
            {!isLoggedIn && (
              <button
                onClick={() => setTheme(effectiveTheme === 'dark' ? 'light' : 'dark')}
                className="w-full text-sm text-left py-2 px-3 mb-1 rounded-lg dark:text-gray-400 text-gray-500 hover:text-foreground dark:hover:bg-secondary/40 hover:bg-secondary/10 transition-colors duration-0"
              >
                {effectiveTheme === 'dark' ? 'Light Mode' : 'Dark Mode'}
              </button>
            )}
            {isLoggedIn && (
              <button
                onClick={() => setIsSettingsModalOpen(true)}
                className="w-full text-sm text-left py-2 px-3 mb-1 rounded-lg dark:text-gray-400 text-gray-500 hover:text-foreground dark:hover:bg-secondary/40 hover:bg-secondary/10 transition-colors duration-0"
              >
                Settings
              </button>
            )}
            {!IS_WORDPRESS && (
              <a 
                className="w-full text-sm text-left py-2 px-3 mb-1 rounded-lg dark:text-gray-400 text-gray-500 hover:text-foreground dark:hover:bg-secondary/40 hover:bg-secondary/10 transition-colors duration-0 block"
                href="https://wpassistant.ai/human-wordpress-help/"
                target="_blank"
                rel="noopener"
              >
                <span className="text-gradient-gray">Human WordPress Help</span>
              </a>
            )}
            <QuickLinks />
          </div>
        </div>
      </aside>

      <button
        onClick={toggleSidebar}
          className={`absolute top-1/2 -translate-y-1/2 z-10 transition-all duration-100 group flex h-16 w-6 flex-col items-center justify-center -space-y-1 outline-none pr-1 ${
            isSidebarCollapsed ? 'left-0' : 'left-[278px]'
          }`}
        >
          <div
            className={`h-3 w-1 rounded-full bg-gray-200 dark:bg-gray-700 transition-transform duration-0 ${
              isSidebarCollapsed ? 'group-hover:-rotate-[20deg]' : 'group-hover:rotate-[20deg]'
            }`}
          />
          <div
            className={`h-3 w-1 rounded-full bg-gray-200 dark:bg-gray-700 transition-transform duration-0 ${
              isSidebarCollapsed ? 'group-hover:rotate-[20deg]' : 'group-hover:-rotate-[20deg]'
            }`}
          />
        </button>
    </div>
  );
};

export default React.memo(Sidebar);
