'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 }) => (
  <div
    onClick={onClick}
    className={`flex items-center gap-3 px-2 py-2 rounded-md cursor-pointer hover:bg-emerald-100 ${
      active ? 'bg-emerald-50 text-emerald-600' : 'text-gray-600'
    }`}
  >
    <Icon size={20} />
    <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 ">
        <ProfileSelector className="border-none" />
      </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}
            onClick={() => handleItemClick(item.url)}
          />
        ))}
      </nav>
    </div>
  );
}

export default Sidebar;
