'use client';
import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import ProfileSelector from '@/components/ProfileSelector';

const SidebarItem = ({ icon: Icon, text, active, url, onClick, badge }) => (
  <div
    onClick={onClick}
    className={`flex items-center gap-3 px-2 py-2 rounded-md cursor-pointer hover:bg-primary/10 ${
      active ? 'bg-primary/5 text-primary' : 'text-gray-600'
    }`}
  >
    <div className="relative shrink-0">
      <Icon size={20} />
      {badge > 0 && (
        <span className="absolute -top-1.5 -right-1.5 min-w-[16px] h-4 px-0.5 bg-red-500 text-white text-[10px] font-label font-semibold rounded-full flex items-center justify-center leading-none">
          {badge > 99 ? '99+' : badge}
        </span>
      )}
    </div>
    <span>{text}</span>
  </div>
);

function Sidebar({ currentPage, items, onCloseMobile }) {
  const router = useRouter();

  const [selectedItem, setSelectedItem] = useState(currentPage);

  useEffect(() => {
    setSelectedItem(currentPage);
  }, [currentPage]);

  const handleItemClick = (url) => {
    setSelectedItem(url);
    router.push(url);
    if (onCloseMobile) {
      onCloseMobile();
    }
  };

  return (
    <div className="w-64 bg-stone-50 border-r h-full border-gray-200">
      <div className="border-b border-gray-200 hidden md:block">
        <ProfileSelector className="border-none h-24" />
      </div>
      <nav className="space-y-1 px-4 py-6">
        {items.map((item) => (
          <SidebarItem
            key={item.id}
            icon={item.icon}
            text={item.name}
            active={item.id === selectedItem}
            url={item.url}
            badge={item.badge}
            onClick={() => handleItemClick(item.url)}
          />
        ))}
      </nav>
    </div>
  );
}

export default Sidebar;
