import React, { useState } from 'react';
import { useEstablishment } from '@/context/EstablishmentContext';
import DropdownMenu from '@/components/DropdownMenu';
import { getRightStr } from '@/utils/rights';
import { ChevronDown } from 'lucide-react'; // Import de l'icône

const ProfileSelector = ({ onRoleChange, className = '' }) => {
  const {
    establishments,
    selectedRoleId,
    setSelectedRoleId,
    setSelectedEstablishmentId,
    setProfileRole,
    user,
  } = useEstablishment();
  const [dropdownOpen, setDropdownOpen] = useState(false);

  const handleRoleChange = (roleId) => {
    // Pas bon quand on a plusieur role pour le même établissement
    const role = user.roles[roleId].role_type;
    const establishmentId = user.roles[roleId].establishment__id;
    setProfileRole(role);
    setSelectedEstablishmentId(establishmentId);
    setSelectedRoleId(roleId);
    if (onRoleChange) {
      onRoleChange(roleId);
    }
    setDropdownOpen(false); // Fermer le menu après sélection
  };

  // Si on a pas de rôle ou un seul rôle, on n'affiche pas le sélecteur
  if (
    !establishments ||
    establishments.length === 0 ||
    establishments.length === 1
  ) {
    return null;
  }

  const selectedEstablishment = establishments.find(
    (est) => est.role_id === selectedRoleId
  );

  return (
    <div className={`relative ${className}`}>
      <DropdownMenu
        buttonContent={
          <div className="h-16 flex items-center gap-2 cursor-pointer px-4 bg-white">
            <div className="flex-1">
              <div className="font-bold text-left">
                {getRightStr(selectedEstablishment?.role_type) || ''}
              </div>
              <div className="text-sm text-gray-500 text-left">
                {selectedEstablishment?.name || 'Sélectionnez un établissement'}
              </div>
            </div>
            {/* Icône ChevronDown avec rotation conditionnelle */}
            <ChevronDown
              className={`w-5 h-5 transition-transform duration-200 ${
                dropdownOpen ? 'rotate-180' : 'rotate-0'
              }`}
            />
          </div>
        }
        items={establishments.map((establishment) => ({
          type: 'item',
          label: (
            <div className="text-left">
              <div className="font-bold">
                {getRightStr(establishment.role_type)}
              </div>
              <div className="text-sm text-gray-500">{establishment.name}</div>
            </div>
          ),
          onClick: () => handleRoleChange(establishment.role_id),
        }))}
        buttonClassName="w-full"
        menuClassName="absolute mt-2 w-full bg-white border border-gray-200 rounded shadow-lg z-10"
        dropdownOpen={dropdownOpen}
        setDropdownOpen={setDropdownOpen}
      />
    </div>
  );
};

export default ProfileSelector;
