"use client"
import { useEffect, useCallback, memo } from 'react';
import { useAtom } from 'jotai';
import { GitCommitHorizontal, GitCommitVertical } from 'lucide-react';
import { cn } from './utils';
import ChatUserList from './ChatUserList';
import ChatDetail from './ChatDetail';
import { ChatUser } from './types';
import {
  leftOpenAtom,
  isMobileAtom,
  anyMobileSidebarOpenAtom,
  selectedUserAtom,
  chatDetailOpenAtom,
  toggleLeftSidebarAtom,
  goBackToListAtom,
  mobileSidebarPriorityAtom
} from './store';

const SidebarLeft = () => {
  // State management with Jotai
  const [leftOpen, setLeftOpen] = useAtom(leftOpenAtom);
  const [isMobile, setIsMobile] = useAtom(isMobileAtom);
  const [anyMobileSidebarOpen] = useAtom(anyMobileSidebarOpenAtom);
  const [selectedUser] = useAtom(selectedUserAtom);
  const [chatDetailOpen] = useAtom(chatDetailOpenAtom);
  const [, toggleLeftSidebar] = useAtom(toggleLeftSidebarAtom);
  const [, goBackToList] = useAtom(goBackToListAtom);
  const [, manageMobileSidebars] = useAtom(mobileSidebarPriorityAtom);

  // Detect mobile screen size
  useEffect(() => {
    const handleResize = () => {
      const wasMobile = isMobile;
      const newIsMobile = typeof window !== 'undefined' && window.innerWidth < 768;

      // Set the new mobile state
      setIsMobile(newIsMobile);

      // Apply mobile sidebar priority rules
      manageMobileSidebars(wasMobile);
    };

    // Set initial value
    handleResize();

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

    // Clean up on unmount
    return () => {
      if (typeof window !== 'undefined') {
        window.removeEventListener('resize', handleResize);
      }
    };
  }, [isMobile, setIsMobile, manageMobileSidebars]);

  // Handler for toggling sidebar
  const handleToggleSidebar = useCallback(() => {
    if (isMobile) {
      toggleLeftSidebar();
    } else {
      setLeftOpen(!leftOpen);
    }
  }, [isMobile, leftOpen, setLeftOpen, toggleLeftSidebar]);

  // Handler for selecting a user
  const handleSelectUser = useCallback((user: ChatUser) => {
    // Selection is handled by the ChatUserList component
  }, []);

  // Handler for going back to the user list
  const handleBackToList = useCallback(() => {
    goBackToList();
  }, [goBackToList]);

  // If any mobile sidebar is open but not this one, don't render
  if (isMobile && anyMobileSidebarOpen && !leftOpen) {
    return null;
  }

  // Desktop view with chat detail open
  if (!isMobile && chatDetailOpen && selectedUser && leftOpen) {
    return (
      <div className="flex h-full w-full">
        {/* Sidebar (narrower in chat view) */}
        <div className={cn(
          'bg-gray-200 transition-all duration-300 relative h-full',
          'w-64 border-r border-gray-300'
        )}>
          <div className="h-full flex flex-col">
            <div className="flex-1 overflow-hidden">
              <ChatUserList onSelectUser={handleSelectUser} />
            </div>
          </div>
          <button
            onClick={handleToggleSidebar}
            className={cn(
              "absolute top-1/2 -right-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={leftOpen ? "Close left sidebar" : "Open left sidebar"}
          >
            {leftOpen ? <GitCommitVertical size={16} /> : <GitCommitHorizontal size={16} />}
          </button>
        </div>

        {/* Chat detail (takes remaining space) */}
        <div className={cn(
          'bg-white transition-all duration-300 h-full flex-1'
        )}>
          {selectedUser && (
            <ChatDetail user={selectedUser} onBack={handleBackToList} />
          )}
        </div>
      </div>
    );
  }

  // Mobile or regular sidebar view
  return (
    <div className={cn(
      'bg-gray-200 transition-all duration-300 relative h-full',
      leftOpen ? (isMobile ? 'w-full fixed left-0 top-0 z-50' : 'w-64') : 'w-0',
      isMobile && leftOpen && 'overflow-hidden'
    )}>
      {leftOpen && (
        <div className="h-full flex flex-col">
          {/* Show either chat list or chat detail based on state */}
          {isMobile && chatDetailOpen && selectedUser ? (
            <div className="h-full w-full">
              <ChatDetail user={selectedUser} onBack={handleBackToList} />
            </div>
          ) : (
            <div className="h-full w-full">
              <ChatUserList onSelectUser={handleSelectUser} />
            </div>
          )}
        </div>
      )}

      {/* Toggle button */}
      <button
        onClick={handleToggleSidebar}
        className={cn(
          "absolute top-1/2 -right-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={leftOpen ? "Close left sidebar" : "Open left sidebar"}
      >
        {leftOpen ? <GitCommitVertical size={16} /> : <GitCommitHorizontal size={16} />}
      </button>
    </div>
  );
};

export default memo(SidebarLeft);