import React, { useState, useContext } from 'react';
import { LogOut } from 'lucide-react';
import { disconnect } from '@/app/actions/authAction';
import { getGravatarUrl } from '@/utils/gravatar';
import { useEstablishment } from '@/context/EstablishmentContext';
import { useChatConnection } from '@/context/ChatConnectionContext';
import DropdownMenu from '@/components/DropdownMenu';
import { usePopup } from '@/context/PopupContext';
import { getRightStr } from '@/utils/rights';
import { ChevronDown } from 'lucide-react'; // Import de l'icône
import Image from 'next/image'; // Import du composant Image
import { getSecureFileUrl } from '@/utils/fileUrl';

const ProfileSelector = ({ onRoleChange, className = '', compact = false }) => {
  const {
    establishments,
    selectedRoleId,
    setSelectedRoleId,
    setSelectedEstablishmentId,
    setProfileRole,
    user,
    setSelectedEstablishmentEvaluationFrequency,
    setSelectedEstablishmentTotalCapacity,
    selectedEstablishmentLogo,
    setSelectedEstablishmentLogo,
  } = useEstablishment();
  const { isConnected, connectionStatus } = useChatConnection();
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const { showPopup } = usePopup();

  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;
    const establishmentEvaluationFrequency =
      user.roles[roleId].establishment__evaluation_frequency;
    const establishmentTotalCapacity =
      user.roles[roleId].establishment__total_capacity;
    const establishmentLogo = user.roles[roleId].establishment__logo;
    setProfileRole(role);
    setSelectedEstablishmentId(establishmentId);
    setSelectedEstablishmentEvaluationFrequency(
      establishmentEvaluationFrequency
    );
    setSelectedEstablishmentTotalCapacity(establishmentTotalCapacity);
    setSelectedEstablishmentLogo(establishmentLogo);
    setSelectedRoleId(roleId);
    if (onRoleChange) {
      onRoleChange(roleId);
    }
    setDropdownOpen(false); // Fermer le menu après sélection
  };

  const handleDisconnect = () => {
    setDropdownOpen(false);
    setTimeout(() => {
      showPopup &&
        showPopup(
          'Êtes-vous sûr(e) de vouloir vous déconnecter ?',
          () => disconnect(),
          undefined
        );
    }, 150);
  };

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

  // Fonction pour obtenir la couleur de la bulle de statut
  const getStatusColor = () => {
    switch (connectionStatus) {
      case 'connected':
        return 'bg-green-500';
      case 'connecting':
        return 'bg-yellow-500';
      case 'error':
        return 'bg-red-500';
      case 'disconnected':
      default:
        return 'bg-gray-400';
    }
  };

  // Fonction pour obtenir le titre de la bulle de statut
  const getStatusTitle = () => {
    switch (connectionStatus) {
      case 'connected':
        return 'Chat connecté';
      case 'connecting':
        return 'Connexion au chat...';
      case 'error':
        return 'Erreur de connexion au chat';
      case 'disconnected':
      default:
        return 'Chat déconnecté';
    }
  };

  // Suppression du tronquage JS, on utilise uniquement CSS
  const isSingleRole = establishments && establishments.length === 1;

  const buttonContent = compact ? (
    /* Mode compact : avatar seul pour la topbar mobile */
    <div className="flex items-center gap-1 cursor-pointer px-2 py-1 rounded-md hover:bg-gray-100">
      <div className="relative">
        <Image
          src={
            selectedEstablishmentLogo
              ? getSecureFileUrl(selectedEstablishmentLogo)
              : getGravatarUrl(user?.email)
          }
          alt="Profile"
          className="w-8 h-8 rounded-full object-cover shadow-md"
          width={32}
          height={32}
        />
        <div
          className={`absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full border-2 border-white ${getStatusColor()}`}
          title={getStatusTitle()}
        />
      </div>
      <ChevronDown
        className={`w-4 h-4 text-gray-500 transition-transform duration-200 ${dropdownOpen ? 'rotate-180' : 'rotate-0'}`}
      />
    </div>
  ) : (
    /* Mode normal : avatar + infos texte */
    <div className="flex items-center gap-2 cursor-pointer px-4 bg-white h-24">
      <div className="relative">
        <Image
          src={
            selectedEstablishmentLogo
              ? getSecureFileUrl(selectedEstablishmentLogo)
              : getGravatarUrl(user?.email)
          }
          alt="Profile"
          className="w-16 h-16 rounded-full object-cover shadow-md"
          width={64}
          height={64}
        />
        <div
          className={`absolute -bottom-0.5 -right-0.5 w-3.5 h-3.5 rounded-full border-2 border-white ${getStatusColor()}`}
          title={getStatusTitle()}
        />
      </div>
      <div className="flex-1 min-w-0">
        <div
          className="font-semibold text-base text-gray-900 text-left truncate max-w-full"
          title={user?.email}
        >
          {user?.email}
        </div>
        <div
          className="font-semibold text-base text-secondary text-left truncate max-w-full"
          title={selectedEstablishment?.name || ''}
        >
          {selectedEstablishment?.name || ''}
        </div>
        <div
          className="italic text-sm text-primary text-left truncate max-w-full"
          title={getRightStr(selectedEstablishment?.role_type) || ''}
        >
          {getRightStr(selectedEstablishment?.role_type) || ''}
        </div>
      </div>
      <ChevronDown
        className={`w-5 h-5 transition-transform duration-200 ${dropdownOpen ? 'rotate-180' : 'rotate-0'}`}
      />
    </div>
  );

  return (
    <div className={`relative ${className}`}>
      <DropdownMenu
        buttonContent={buttonContent}
        items={
          isSingleRole
            ? [
                {
                  type: 'item',
                  label: 'Déconnexion',
                  onClick: handleDisconnect,
                  icon: LogOut,
                },
              ]
            : [
                ...establishments.map((establishment) => ({
                  type: 'item',
                  label: (
                    <div className="flex items-center text-left">
                      <Image
                        src={
                          establishment.logo
                            ? getSecureFileUrl(establishment.logo)
                            : getGravatarUrl(user?.email)
                        }
                        alt="Profile"
                        className="w-8 h-8 rounded-full object-cover shadow-md mr-3"
                        width={32}
                        height={32}
                      />
                      <div>
                        <div className="font-bold ext-sm text-gray-500">
                          {establishment.name}
                        </div>
                        <div className="italic text-sm text-gray-500">
                          {getRightStr(establishment.role_type)}
                        </div>
                      </div>
                    </div>
                  ),
                  onClick: () => handleRoleChange(establishment.role_id),
                })),
                {
                  type: 'separator',
                  content: <hr className="my-2 border-gray-200" />,
                },
                {
                  type: 'item',
                  label: 'Déconnexion',
                  onClick: handleDisconnect,
                  icon: LogOut,
                },
              ]
        }
        buttonClassName="w-full"
        menuClassName={
          compact
            ? 'absolute right-0 mt-2 min-w-[200px] bg-white border border-gray-200 rounded shadow-lg z-50'
            : 'absolute mt-2 w-full bg-white border border-gray-200 rounded shadow-lg z-10'
        }
        dropdownOpen={dropdownOpen}
        setDropdownOpen={setDropdownOpen}
      />
    </div>
  );
};

export default ProfileSelector;
