import React, { useCallback } 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,
  useIsMobileSidebarOpen,
  useSetIsMobileSidebarOpen,
} from '../../contexts/UIContext';
import useRenderTracker from '../../hooks/useRenderTracker';
import QuickLinks from './QuickLinks';
import { TARGET_ENV, IS_WORDPRESS } from '../../constants';

const MobileSidebar: 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 isMobileSidebarOpen = useIsMobileSidebarOpen();
  const setIsMobileSidebarOpen = useSetIsMobileSidebarOpen();

  useRenderTracker('MobileSidebar');

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

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

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

  return (
    <>
      {/* Overlay */}
      {isMobileSidebarOpen && (
        <div
          className={[
            "fixed z-40 md:hidden bg-black/50",
            TARGET_ENV === 'wordpress'
              ? "left-0 right-0 bottom-0 top-[var(--actionpanel-ai-admin-bar-h)]"
              : "inset-0",
          ].join(' ')}
          onClick={() => setIsMobileSidebarOpen(false)}
        />
      )}

      {/* Sidebar */}
      <aside
        className={[
          "fixed left-0 z-50 md:hidden w-[240px]",
          // WP: start below the admin bar and extend to bottom; Web: full viewport
          TARGET_ENV === 'wordpress'
            ? "top-[var(--actionpanel-ai-admin-bar-h)] bottom-0"
            : "top-0 bottom-0",
          "overflow-y-auto bg-background-light dark:bg-background-dark",
          "bg-gradient-to-r from-background-light to-gray-300/10",
          "dark:from-background-dark dark:to-gray-600/5",
          "border-r border-gray-200 dark:border-gray-700",
          "transition-transform duration-200 ease-in-out",
          isMobileSidebarOpen ? "translate-x-0" : "-translate-x-full",
        ].join(' ')}
      >
        <div className="p-4 flex flex-col h-full min-h-0">
          <div className="flex justify-between items-center pb-2">
            <span className="px-1">
              <WPAssistantLogo size={20} />
            </span>
            <div className="relative flex items-center">
              <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>
            </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);
                  setIsMobileSidebarOpen(false);
                }} 
              > 
                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);
                  setIsMobileSidebarOpen(false);
                }}
                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>
    </>
  );
};

export default React.memo(MobileSidebar); 
