'use client';
import { useState, useRef, useEffect, useCallback } from 'react';
import { useAtom } from 'jotai';
import { cn } from './utils';
import { topOpenAtom, isMobileAtom, anyMobileSidebarOpenAtom, isChatFullscreenModeAtom } from './store';
// Simple SVG icons to replace Lucide React icons
const UserRoundIcon = ({ size = 20, className = '' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
    <circle cx="12" cy="8" r="5"/>
    <path d="M20 21a8 8 0 1 0-16 0"/>
  </svg>
);

const SearchIcon = ({ size = 20, className = '' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
    <circle cx="11" cy="11" r="8"/>
    <path d="m21 21-4.35-4.35"/>
  </svg>
);

const ShoppingCartIcon = ({ size = 20, className = '' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
    <circle cx="8" cy="21" r="1"/>
    <circle cx="19" cy="21" r="1"/>
    <path d="M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"/>
  </svg>
);

const HeartIcon = ({ size = 20, className = '' }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
    <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
  </svg>
);

const GitCommitHorizontalIcon = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="12" cy="12" r="3"/>
    <line x1="3" x2="9" y1="12" y2="12"/>
    <line x1="15" x2="21" y1="12" y2="12"/>
  </svg>
);

const GitCommitVerticalIcon = ({ size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <circle cx="12" cy="12" r="3"/>
    <line x1="12" x2="12" y1="3" y2="9"/>
    <line x1="12" x2="12" y1="15" y2="21"/>
  </svg>
);

// Simple dropdown component
const SelectDropdown = ({ options = ['default'] }: { options?: string[] }) => {
  return (
    <select className="px-4 py-2 rounded border">
      {options.map(option => (
        <option key={option}>{option}</option>
      ))}
    </select>
  );
};

const SidebarTop = () => {
  const [topOpen, setTopOpen] = useAtom(topOpenAtom);
  const [searchOpen, setSearchOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const searchRef = useRef<HTMLDivElement>(null);
  const [isMobile, setIsMobile] = useAtom(isMobileAtom);
  const [anyMobileSidebarOpen] = useAtom(anyMobileSidebarOpenAtom);
  const [isChatFullscreenMode] = useAtom(isChatFullscreenModeAtom);

  // Detect mobile screen size
  useEffect(() => {
    const handleResize = () => {
      setIsMobile(typeof window !== 'undefined' && window.innerWidth < 768);
    };
    
    // Initial check
    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);
      }
    };
  }, [setIsMobile]);

  // Close search when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        searchRef.current &&
        !searchRef.current.contains(event.target as Node)
      ) {
        setSearchOpen(false);
      }
    };

    if (typeof document !== 'undefined') {
      document.addEventListener('mousedown', handleClickOutside, { passive: true });
    }
    return () => {
      if (typeof document !== 'undefined') {
        document.removeEventListener('mousedown', handleClickOutside);
      }
    };
  }, []);

  // Focus input when search opens
  useEffect(() => {
    if (searchOpen && searchRef.current) {
      const input = searchRef.current.querySelector('input');
      if (input) input.focus();
    }
  }, [searchOpen]);

  // Toggle sidebar handler
  const handleToggleSidebar = useCallback(() => {
    setTopOpen(!topOpen);
  }, [topOpen, setTopOpen]);

  // Clear search handler
  const handleClearSearch = useCallback(() => {
    setSearchQuery('');
  }, []);

  // Toggle search handler
  const handleToggleSearch = useCallback(() => {
    setSearchOpen(!searchOpen);
  }, [searchOpen]);

  // Hide in mobile if any sidebar is open or in desktop when chat detail is open
  if ((isMobile && anyMobileSidebarOpen) || isChatFullscreenMode) {
    return null;
  }

  return (
    <div
      className={cn(
        'bg-blue-100 transition-all duration-300 relative w-full',
        topOpen ? 'h-20' : 'h-0'
      )}
    >
      {topOpen && (
        <div className="p-4 mt-2 flex justify-center items-center">
          <div className="flex items-center space-x-6">
            <div className='hidden lg:flex items-center space-x-4'> 
              <SelectDropdown />
              <SelectDropdown />
              <SelectDropdown />
            </div>
            
            {/* User Icon */}
            <button className="p-2 rounded-full hover:bg-blue-200 transition-all duration-200">
              <UserRoundIcon size={20} className="text-gray-600" />
            </button>

            {/* Search */}
            <div ref={searchRef} className="relative">
              {searchOpen ? (
                <div className="flex items-center">
                  <div className="relative">
                    <input
                      type="text"
                      placeholder="Search..."
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                      className="px-4 py-2 pl-10 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition duration-200 w-64 shadow-sm"
                    />
                    <div className="absolute left-3 top-2.5 text-gray-400">
                      <SearchIcon size={18} />
                    </div>
                    {searchQuery && (
                      <button
                        onClick={handleClearSearch}
                        className="absolute right-3 top-2.5 text-gray-400 hover:text-gray-600"
                      >
                        &times;
                      </button>
                    )}
                  </div>
                </div>
              ) : (
                <button
                  onClick={handleToggleSearch}
                  className="p-2 rounded-full hover:bg-blue-200 transition-colors duration-200"
                >
                  <SearchIcon size={20} className="text-gray-600" />
                </button>
              )}
            </div>

            {/* Shopping Cart */}
            <button className="p-2 rounded-full hover:bg-blue-200 transition-colors duration-200">
              <ShoppingCartIcon size={20} className="text-gray-600" />
            </button>

            {/* Favorites */}
            <button className="p-2 rounded-full hover:bg-blue-200 transition-colors duration-200">
              <HeartIcon size={20} className="text-gray-600" />
            </button>
          </div>
        </div>
      )}

      <button
        onClick={handleToggleSidebar}
        className={cn(
          "absolute bottom-0 left-1/2 transform -translate-x-1/2 translate-y-1/2",
          "bg-black text-white rounded-full p-2 shadow-md z-10",
          "hover:bg-gray-800 hover:scale-110",
          "focus:outline-none focus:ring-2 focus:ring-blue-500",
          "transition-all duration-200"
        )}
        aria-label={topOpen ? "Close top sidebar" : "Open top sidebar"}
      >
        {topOpen ? <GitCommitHorizontalIcon size={16} /> : <GitCommitVerticalIcon size={16} />}
      </button>
    </div>
  );
};

export default SidebarTop;
