import React, { useState, useEffect } from 'react';
import { ChevronDown, Check, Server, Loader2, AlertCircle, Building2, Plus } from 'lucide-react';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuLabel,
  DropdownMenuSeparator,
} from '@/components/ui/dropdown-menu';
import { cn } from '@/lib/utils';
import { Gateways } from '@/types/gateways';
import { gatewaysStatus, getAllGateways, getSociete } from '@/store/features/gateways/selectors';
import { useAppDispatch, useAppSelector } from '@/store/hooks';
import { selectgateways } from '@/store/features/gateways/slice';
import ModalGateway from '../modal/ModalGateway';
import { Societe } from '@/types/societeType';

interface GatewaySelectorProps {
  className?: string;
  onGatewayChange?: (gateway: Gateways) => void;
  onAddGateway?: () => void;
}

const CompanySelector: React.FC<GatewaySelectorProps> = ({ 
  className, 
  onGatewayChange,
  onAddGateway 
}) => {
  const dispatch = useAppDispatch();
  const societe = useAppSelector(getSociete) as Societe;
  const gateways = useAppSelector(getAllGateways) as Gateways[];
  const status = useAppSelector(gatewaysStatus);

  const [selectedGateway, setSelectedGateway] = useState<Gateways | null>(null);
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);

  useEffect(() => {
    if (status === "succeeded" && gateways.length > 0 && !selectedGateway) {
      const defaultGateway = gateways.find((g) => g.is_default) || gateways[0];
      setSelectedGateway(defaultGateway);
      onGatewayChange?.(defaultGateway);
    }
  }, [status, gateways, selectedGateway, onGatewayChange]);

  const handleSelectGateway = (gateway: Gateways) => {
    dispatch(selectgateways(gateway));
    setSelectedGateway(gateway);
    onGatewayChange?.(gateway);
  };

  const handleAddClick = (e: React.MouseEvent) => {
    setIsCreateModalOpen(true)
    onAddGateway?.();
  };
  

  const handleRefresh = async () => {
    //  await dispatch(getGateways()).unwrap();
    // await dispatch(getSociete()).unwrap();
  };
  

  const getHealthStatusColor = (healthStatus: Gateways['health_status']) => {
    switch (healthStatus) {
      case 'healthy':
        return 'bg-green-500';
      case 'unhealthy':
        return 'bg-red-500';
      default:
        return 'bg-gray-400';
    }
  };

  // Si loading ou idle
  if (status === 'idle' || status === 'loading') {
    return (
      <div className={cn('px-3 py-2', className)}>
        <div className="group w-full flex flex-col items-start px-3 py-2.5 rounded-lg cursor-not-allowed opacity-70">
          <span className="text-[10px] font-bold text-[#6B7280] uppercase tracking-wider mb-1">
            Entreprise
          </span>
          <div className="flex items-center gap-2">
            <Loader2 className="w-4 h-4 animate-spin text-[#6B7280]" />
            <span className="text-[15px] font-bold text-white/60 truncate leading-tight">
              Chargement...
            </span>
          </div>
        </div>
      </div>
    );
  }

  // Si erreur
  if (status === 'failed') {
    return (
      <div className={cn('px-3 py-2', className)}>
        <div className="group w-full flex flex-col items-start px-3 py-2.5 rounded-lg">
          <span className="text-[10px] font-bold text-[#6B7280] uppercase tracking-wider mb-1">
            Entreprise
          </span>
          <div className="flex items-center gap-2 cursor-pointer" onClick={handleRefresh}>
            <AlertCircle className="w-4 h-4 text-red-400" />
            <span className="text-[15px] font-bold text-red-400 truncate leading-tight">
              cliquer pour actualiser
            </span>
          </div>
        </div>
      </div>
    );
  }
  

  // console.log("gateways : ",gateways);
  
  // Si aucune gateway - afficher directement le bouton Ajouter
  if (gateways.length === 0) {
    return (
      <div className={cn('px-3 py-2', className)}>
        <div className="w-full flex flex-col items-start px-3 py-2.5 rounded-lg">
          <span className="text-[10px] font-bold text-[#6B7280] uppercase tracking-wider mb-1">
            Entreprise
          </span>
        </div>

          <div
              className={cn(
                'flex items-center gap-3 px-2 py-2.5 rounded-lg cursor-pointer transition-colors outline-none'
              )}
            >
              <div
                className={cn(
                  'w-8 h-8 rounded-md flex items-center justify-center shrink-0 relative bg-[#2A6F4F] text-white shadow-sm'
                )}
              >
                <Building2 className="w-4 h-4" />
              </div>

              <div className="flex-1 min-w-0">
                <span
                  className={cn(
                    'block text-[14px] truncate uppercase font-bold text-gray-400 '
                  )}
                >
                  {societe?.raison_sociale || ""}
                </span>
                {societe?.forme_juridique && (
                  <span className="block text-[11px] text-gray-400 truncate">
                    {societe.forme_juridique}
                  </span>
                )}
              </div>

              <span className="text-[10px] font-medium text-gray-100 bg-[#007E45] px-1.5 py-0.5 rounded shrink-0">
                  Défaut
              </span>

              
            </div>
        {/* </DropdownMenuContent> */}
        <ModalGateway
          open={isCreateModalOpen}
          onClose={() => setIsCreateModalOpen(false)}
        />
      </div>
    );
  }

  // Affichage normal avec dropdown
  return (
    <div className={cn('px-3 py-2', className)}>
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          
          <div
            className="group w-full flex flex-col items-start px-3 py-2.5 rounded-lg hover:bg-[#1F1F1F] cursor-pointer transition-colors duration-200 outline-none"
            role="button"
            aria-label="Sélectionner une gateway"
          >
            <span className="text-[10px] font-bold text-[#6B7280] uppercase tracking-wider mb-1 group-hover:text-[#9CA3AF] transition-colors">
              Entreprise
            </span>
            <div className="w-full flex items-center justify-between gap-2">
              <div className="flex items-center gap-2 min-w-0">
                <span className="text-[12px] uppercase font-bold text-white truncate leading-tight group-hover:text-white/90 transition-colors">
                  {selectedGateway?.name}
                </span>
              </div>
              <ChevronDown className="w-4 h-4 text-[#6B7280] group-hover:text-white transition-colors shrink-0" />
            </div>
          </div>
        </DropdownMenuTrigger>

        <DropdownMenuContent
          align="start"
          className="w-[280px] bg-white p-1.5 shadow-xl border-gray-100 rounded-xl animate-in fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 z-50 ml-2"
          sideOffset={8}
        >
          <DropdownMenuLabel className="text-[11px] font-semibold text-gray-400 uppercase tracking-wider px-2 py-1.5 select-none">
            Vos organisations
          </DropdownMenuLabel>

          {gateways.map((gateway) => (
            <DropdownMenuItem
              key={gateway.id}
              onClick={() => handleSelectGateway(gateway)}
              className={cn(
                'flex items-center gap-3 px-2 py-2.5 rounded-lg cursor-pointer transition-colors outline-none',
                selectedGateway?.id === gateway.id ? 'bg-green-50/50' : 'hover:bg-gray-50'
              )}
            >
              <div
                className={cn(
                  'w-8 h-8 rounded-md flex items-center justify-center shrink-0 relative',
                  selectedGateway?.id === gateway.id
                    ? 'bg-[#2A6F4F] text-white shadow-sm'
                    : 'bg-gray-100 text-gray-500'
                )}
              >
                <Building2 className="w-4 h-4" />
              </div>

              <div className="flex-1 min-w-0">
                <span
                  className={cn(
                    'block text-[14px] truncate uppercase',
                    selectedGateway?.id === gateway.id
                      ? 'font-bold text-[#1F2937]'
                      : 'font-medium text-gray-600'
                  )}
                >
                  {gateway.name}
                </span>
                {gateway.sage_company && (
                  <span className="block text-[11px] text-gray-400 truncate">
                    {gateway.sage_company}
                  </span>
                )}
              </div>

              {gateway.is_default && selectedGateway?.id !== gateway.id && (
                <span className="text-[10px] font-medium text-gray-400 bg-gray-100 px-1.5 py-0.5 rounded shrink-0">
                  Défaut
                </span>
              )}

              {selectedGateway?.id === gateway.id && (
                <Check className="w-4 h-4 text-[#2A6F4F] ml-auto shrink-0" />
              )}
            </DropdownMenuItem>
          ))}

          {/* Séparateur et bouton Ajouter */}
          <DropdownMenuSeparator className="my-1.5 bg-gray-100" />
          
          {/* <DropdownMenuItem
            onClick={handleAddClick}
            className="flex items-center gap-3 px-2 py-2.5 rounded-lg cursor-pointer transition-colors outline-none hover:bg-emerald-50 group"
          >
            <div className="w-8 h-8 rounded-md flex items-center justify-center shrink-0 bg-emerald-100 text-emerald-600 group-hover:bg-emerald-200 transition-colors">
              <Plus className="w-4 h-4" />
            </div>
            <span className="text-[14px] font-medium text-emerald-600 group-hover:text-emerald-700 transition-colors">
              Ajouter une entreprise
            </span>
          </DropdownMenuItem> */}
        </DropdownMenuContent>
      </DropdownMenu>

       <ModalGateway
          open={isCreateModalOpen}
          onClose={() => setIsCreateModalOpen(false)}
        />

    </div>
  );
};

export default CompanySelector;