import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Moon, Settings, SquarePen, Sun, UserPlus } from 'lucide-react';
import { WPAssistantLogo } from '../Logos/WPAssistantLogo';
import ConversationGroup from './ConversationGroup';
import { MenuItem } from '../ui';
import { cn } from '../../utils/classNames';
import { useTheme } from '../../contexts/ThemeContext';
import useGroupedConversations from '../../hooks/useGroupedConversations';
import { useAuth } from '../../contexts/AuthContext';
import {
  useCurrentConversationId,
  useConversations,
  useConversationsLoading,
  useHasMoreConversations,
  useIsFetchingMoreConversations,
  useLoadMoreConversations,
} from '../../contexts/ChatContext';
import ConversationsSkeleton from './ConversationsSkeleton';
import {
  useSetConfirmDeleteConversationId,
  useSetConfirmDeleteConversationName,
  useSetIsConfirmDeleteModalOpen,
  useSetIsLoginModalOpen,
  useSetIsSettingsModalOpen,
} from '../../contexts/UIContext';
import useRenderTracker from '../../hooks/useRenderTracker';
import QuickLinks from './QuickLinks';
import { IS_WORDPRESS } from '../../constants';
import { useAppRoute } from '../../hooks/useAppRoute';

interface SidebarContentProps {
  onActionComplete?: () => void;
}

const SidebarContent: React.FC<SidebarContentProps> = ({ onActionComplete }) => {
  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 conversations = useConversations();
  const conversationsLoading = useConversationsLoading();
  const hasMoreConversations = useHasMoreConversations();
  const isFetchingMoreConversations = useIsFetchingMoreConversations();
  const loadMoreConversations = useLoadMoreConversations();
  const groupedConversations = useGroupedConversations({ conversations });

  // Show a subtle top fade only once the conversation list is scrolled down.
  const navRef = useRef<HTMLElement>(null);
  const loadMoreRef = useRef<HTMLDivElement>(null);
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const el = navRef.current;
    if (!el) return;
    const onScroll = () => setScrolled(el.scrollTop > 4);
    onScroll();
    el.addEventListener('scroll', onScroll, { passive: true });
    return () => el.removeEventListener('scroll', onScroll);
  }, [conversationsLoading, groupedConversations]);

  useEffect(() => {
    const root = navRef.current;
    const target = loadMoreRef.current;
    if (!root || !target || !hasMoreConversations || isFetchingMoreConversations) return;

    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry?.isIntersecting) {
          void loadMoreConversations();
        }
      },
      {
        root,
        rootMargin: '160px 0px',
      },
    );

    observer.observe(target);
    return () => observer.disconnect();
  }, [
    conversations.length,
    hasMoreConversations,
    isFetchingMoreConversations,
    loadMoreConversations,
  ]);

  const { openConversationRoute, openHomeRoute, openSettingsRoute } = useAppRoute();

  useRenderTracker('SidebarContent', {
    effectiveTheme,
    isLoggedIn,
    conversations,
    groupedConversations,
    currentConversationId,
  });

  const completeAction = useCallback(() => {
    onActionComplete?.();
  }, [onActionComplete]);

  const handleNewChat = useCallback(() => {
    openHomeRoute();
    completeAction();
  }, [completeAction, openHomeRoute]);

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

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

  return (
    <div className="flex h-full min-h-0 flex-col py-3">
      <div className="flex items-center justify-between px-4 py-2">
        <WPAssistantLogo size={20} />
      </div>

      <button
        onClick={handleNewChat}
        className="mx-2 mb-4 mt-5 flex items-center gap-2 rounded-lg bg-app-surface-muted px-3 py-2.5 text-sm font-semibold text-app-muted-strong transition-colors hover:bg-app-surface-hover hover:text-app-text focus:outline-none focus-visible:ring-2 focus-visible:ring-brand"
      >
        <SquarePen size={16} className="text-brand" />
        New chat
      </button>

      {/* Full-width scroll area so the scrollbar sits flush to the sidebar edge;
          rows pad themselves. A bottom fade hints at more content below. */}
      <div className="relative min-h-0 flex-1">
        <nav
          ref={navRef}
          aria-label="Conversations"
          aria-busy={conversationsLoading}
          className="h-full overflow-y-auto scrollbar-custom"
        >
          {conversationsLoading ? (
            <ConversationsSkeleton />
          ) : (
            <div className="animate-fade-in space-y-4 pb-10">
              {groupedConversations.map(({ category, conversations }) => (
                <ConversationGroup
                  key={category}
                  category={category}
                  conversations={conversations}
                  currentConversationId={currentConversationId}
                  onSelectConversation={handleSelectConversation}
                  onDeleteConversation={onDeleteConversation}
                />
              ))}
              {isFetchingMoreConversations && (
                <ConversationsSkeleton />
              )}
              {hasMoreConversations && !isFetchingMoreConversations && (
                <div ref={loadMoreRef} className="h-10" aria-hidden="true" />
              )}
            </div>
          )}
        </nav>
        {/* Subtle top fade, just below the sticky group header, only when scrolled. */}
        <div
          aria-hidden
          className={cn(
            'pointer-events-none absolute inset-x-0 top-7 h-4 bg-gradient-to-b from-app-surface to-transparent transition-opacity duration-200',
            scrolled ? 'opacity-100' : 'opacity-0',
          )}
        />
        <div
          aria-hidden
          className="pointer-events-none absolute inset-x-0 bottom-0 h-10 bg-gradient-to-t from-app-surface to-transparent"
        />
      </div>

      <div className="mt-auto mx-2 space-y-0.5 border-t border-app-border pt-3">
        {!isLoggedIn && (
          <MenuItem
            icon={<UserPlus size={16} />}
            onClick={() => {
              setIsLoginModalOpen(true);
              completeAction();
            }}
          >
            Login / Sign Up
          </MenuItem>
        )}
        {!isLoggedIn && (
          <MenuItem
            icon={effectiveTheme === 'dark' ? <Sun size={16} /> : <Moon size={16} />}
            onClick={() => setTheme(effectiveTheme === 'dark' ? 'light' : 'dark')}
          >
            {effectiveTheme === 'dark' ? 'Light Mode' : 'Dark Mode'}
          </MenuItem>
        )}
        {(isLoggedIn || IS_WORDPRESS) && (
          <MenuItem
            icon={<Settings size={16} />}
            onClick={() => {
              setIsSettingsModalOpen(true);
              openSettingsRoute(isLoggedIn ? 'account' : 'appearance');
              completeAction();
            }}
          >
            Settings
          </MenuItem>
        )}
        <QuickLinks />
      </div>
    </div>
  );
};

export default React.memo(SidebarContent);
