'use client'
import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useEstablishment } from '@/context/EstablishmentContext';

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 ${
      active ? 'bg-emerald-50 text-emerald-600' : 'text-gray-600 hover:bg-gray-50'
    }`}
  >
    <Icon size={20} />
    <span>{text}</span>
  </div>
);

function Sidebar({ establishments, currentPage, items, onCloseMobile, onEstablishmentChange }) {
  const router = useRouter();
  const { selectedEstablishmentId, setSelectedEstablishmentId, setProfileRole } = useEstablishment();
  const [selectedItem, setSelectedItem] = useState(currentPage);

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

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

  const handleEstablishmentChange = (e) => {
    const establishmentId = parseInt(e.target.value, 10);
    setSelectedEstablishmentId(establishmentId);
    const role = establishments.find(est => est.id === establishmentId)?.role_type;
    setProfileRole(role);
    onEstablishmentChange(establishmentId);
  };

  return (
    <div className="w-64 bg-white border-r h-full border-gray-200 py-6 px-4">
      <div className="flex items-center mb-8 px-2">
        <select
          value={selectedEstablishmentId || ''}
          onChange={handleEstablishmentChange}
          className="form-select block w-full mt-1"
        >
          {establishments.map(establishment => (
            <option key={establishment.id} value={establishment.id}>
              {establishment.name}
            </option>
          ))}
        </select>
      </div>

      <nav className="space-y-1">
        {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;