import React, { useCallback, useState } from 'react';
import { cn } from '../../utils/classNames';
import SidebarContent from './SidebarContent';

const Sidebar: React.FC = () => {
  const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false);

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

  return (
    // Width animates 280 -> 0 so the chat area reflows to fill the space. The aside
    // is absolutely positioned and slides out, and the toggle handle sits above the
    // chat content (z-30) so it stays clickable.
    <div
      className={cn(
        'relative hidden h-full shrink-0 md:block transition-[width] duration-200 ease-in-out',
        isSidebarCollapsed ? 'w-0' : 'w-[280px]',
      )}
    >
      <aside
        className={cn(
          'absolute inset-y-0 left-0 flex w-[280px] flex-col border-r border-app-border bg-app-surface transition-transform duration-200 ease-in-out',
          isSidebarCollapsed && '-translate-x-full',
        )}
      >
        <SidebarContent />
      </aside>

      <button
        onClick={toggleSidebar}
        aria-label={isSidebarCollapsed ? 'Open sidebar' : 'Collapse sidebar'}
        aria-expanded={!isSidebarCollapsed}
        className="group absolute left-full top-1/2 z-30 flex h-16 w-6 -translate-y-1/2 flex-col items-center justify-center -space-y-1 outline-none"
      >
        <div
          className={cn(
            'h-3 w-1 rounded-full bg-app-border-strong transition-transform duration-100 group-hover:bg-app-muted',
            isSidebarCollapsed ? 'group-hover:-rotate-[20deg]' : 'group-hover:rotate-[20deg]',
          )}
        />
        <div
          className={cn(
            'h-3 w-1 rounded-full bg-app-border-strong transition-transform duration-100 group-hover:bg-app-muted',
            isSidebarCollapsed ? 'group-hover:rotate-[20deg]' : 'group-hover:-rotate-[20deg]',
          )}
        />
      </button>
    </div>
  );
};

export default React.memo(Sidebar);
