'use client';
import { useEffect, useCallback, memo, useState } from 'react';
import { GitCommitHorizontal, GitCommitVertical, Maximize2, Minimize2 } from 'lucide-react';
import { useAtom } from 'jotai';
import { cn } from './utils';
import {
  rightOpenAtom,
  rightExpandedAtom,
  isMobileAtom,
  anyMobileSidebarOpenAtom,
  isChatFullscreenModeAtom,
  toggleRightSidebarAtom,
  toggleRightExpandedAtom,
} from './store';

// Sidebar content component for memoization
const SidebarRightContent = memo(({ rightExpanded, isMobile, isResizing }: { rightExpanded: boolean; isMobile: boolean; isResizing: boolean }) => {
  return (
    <div className="flex flex-col h-full">
    <p>tt</p>
    </div>
  );
});

SidebarRightContent.displayName = 'SidebarRightContent';

const SidebarRight = () => {
  const [rightOpen, setRightOpen] = useAtom(rightOpenAtom);
  const [rightExpanded, setRightExpanded] = useAtom(rightExpandedAtom);
  const [isMobile, setIsMobile] = useAtom(isMobileAtom);
  const [anyMobileSidebarOpen] = useAtom(anyMobileSidebarOpenAtom);
  const [isChatFullscreenMode] = useAtom(isChatFullscreenModeAtom);
  const [, toggleRightSidebar] = useAtom(toggleRightSidebarAtom);
  const [, toggleRightExpanded] = useAtom(toggleRightExpandedAtom);
  const [isResizing, setIsResizing] = useState(false);

  // Detect mobile screen size
  useEffect(() => {
    const handleResize = () => {
      setIsMobile(window.innerWidth < 768);
    };

    // Initial check
    handleResize();

    // Add event listener with passive option for better performance
    window.addEventListener('resize', handleResize, { passive: true });

    // Clean up on unmount
    return () => window.removeEventListener('resize', handleResize);
  }, [setIsMobile]);

  // Handler for toggling sidebar
  const handleToggleSidebar = useCallback(() => {
    if (isMobile) {
      toggleRightSidebar();
    } else {
      setRightOpen(!rightOpen);
      // Reset expanded state when closing
      if (rightOpen) {
        setRightExpanded(false);
      }
    }
  }, [isMobile, rightOpen, setRightOpen, toggleRightSidebar, setRightExpanded]);

  // Handler for toggling expanded state
  const handleToggleExpanded = useCallback(() => {
    setIsResizing(true);
    toggleRightExpanded();

    // Show loading state for a short time to allow the SplineScene to adjust
    setTimeout(() => {
      setIsResizing(false);
    }, 800);
  }, [toggleRightExpanded]);

  // If any mobile sidebar is open but not this one, don't render
  // Or if chat is in fullscreen mode, don't render
  if (
    (isMobile && anyMobileSidebarOpen && !rightOpen) ||
    isChatFullscreenMode
  ) {
    return null;
  }

  return (
    <div
      className={cn(
        'bg-gray-200 transition-all duration-300 relative h-full',
        rightOpen
          ? isMobile
            ? 'w-full fixed right-0 top-0 z-50'
            : rightExpanded
              ? 'w-full fixed right-0 top-0 z-50'
              : 'w-64'
          : 'w-0',
        (isMobile || rightExpanded) && rightOpen && 'overflow-hidden'
      )}
    >
      {rightOpen && (
        <div className="p-4 overflow-y-auto h-full flex flex-col">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-lg font-semibold">Helpi</h2>
            {!isMobile && (
              <div className="flex space-x-2">
                <button
                  onClick={handleToggleExpanded}
                  className={cn(
                    'p-1.5 rounded-md hover:bg-gray-300 transition-colors',
                    'focus:outline-none focus:ring-2 focus:ring-blue-500'
                  )}
                  aria-label={rightExpanded ? 'Minimize sidebar' : 'Maximize sidebar'}
                >
                  {rightExpanded ? <Minimize2 size={18} /> : <Maximize2 size={18} />}
                </button>
              </div>
            )}
          </div>
          <SidebarRightContent rightExpanded={rightExpanded} isMobile={isMobile} isResizing={isResizing} />
        </div>
      )}

      <button
        onClick={handleToggleSidebar}
        className={cn(
          'absolute top-1/2 -left-4 transform -translate-y-1/2',
          'bg-black text-white rounded-full p-2 shadow-md z-50',
          'hover:bg-gray-800 hover:scale-110',
          'focus:outline-none focus:ring-2 focus:ring-blue-500',
          'transition-all duration-200'
        )}
        aria-label={rightOpen ? 'Close right sidebar' : 'Open right sidebar'}
      >
        {rightOpen ? (
          <GitCommitVertical size={16} />
        ) : (
          <GitCommitHorizontal size={16} />
        )}
      </button>
    </div>
  );
};

export default memo(SidebarRight);
