import React, { useState, useRef, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { useNavigate } from 'react-router-dom';
import { useTenant } from '../../stores/tenant.store';
import { useSubscription } from '../../api/hooks/subscription';
import { showToast } from '../../utils/toast';
import { ChevronDown, Building2, Check, AlertCircle, Plus, X } from 'lucide-react';

interface TenantSwitcherProps {
  className?: string;
  showLabel?: boolean;
}

export const TenantSwitcher: React.FC<TenantSwitcherProps> = ({
  className = '',
  showLabel = true,
}) => {
  const navigate = useNavigate();
  const [isOpen, setIsOpen] = useState(false);
  const [dropdownPosition, setDropdownPosition] = useState<{
    top: number;
    left: number;
    right?: number;
    width: number;
    isMobile: boolean;
  }>({ top: 0, left: 0, width: 288, isMobile: false });
  const dropdownRef = useRef<HTMLDivElement>(null);
  const buttonRef = useRef<HTMLButtonElement>(null);

  const {
    currentTenant,
    availableTenants,
    isLoading,
    error,
    switchTenant,
    loadUserTenants,
    clearError,
  } = useTenant();

  const { subscriptionInfo } = useSubscription();

  // NOTE: Removed duplicate loadUserTenants() useEffect
  // Tenant loading is already handled by useTenantInitializer at app level (stores/useTenantInitializer.ts)
  // This was causing duplicate /tenants API calls on every dashboard load

  // Handle click outside to close dropdown
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent | TouchEvent) => {
      const target = event.target as Node;
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(target) &&
        !buttonRef.current?.contains(target)
      ) {
        setIsOpen(false);
      }
    };

    const handleEscape = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        setIsOpen(false);
      }
    };

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
      document.addEventListener('touchstart', handleClickOutside);
      document.addEventListener('keydown', handleEscape);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('touchstart', handleClickOutside);
      document.removeEventListener('keydown', handleEscape);
    };
  }, [isOpen]);

  // Recalculate position on window resize
  useEffect(() => {
    const handleResize = () => {
      if (isOpen) {
        calculateDropdownPosition();
      }
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, [isOpen]);

  // Calculate dropdown position
  const calculateDropdownPosition = () => {
    if (!buttonRef.current) return;

    const buttonRect = buttonRef.current.getBoundingClientRect();
    const viewportWidth = window.innerWidth;
    const viewportHeight = window.innerHeight;
    const isMobile = viewportWidth < 768; // md breakpoint

    if (isMobile) {
      // On mobile, use a modal-style overlay
      setDropdownPosition({
        top: 0,
        left: 0,
        width: viewportWidth,
        isMobile: true,
      });
    } else {
      // Desktop positioning - align right edge of dropdown with right edge of button
      const dropdownWidth = 360; // Wider for better content display
      let left = buttonRect.right - dropdownWidth;

      // Ensure dropdown doesn't go off the left edge of the screen
      if (left < 16) {
        left = 16;
      }

      // Ensure dropdown doesn't go off the right edge
      if (left + dropdownWidth > viewportWidth - 16) {
        left = viewportWidth - dropdownWidth - 16;
      }

      setDropdownPosition({
        top: buttonRect.bottom + 8,
        left: left,
        width: dropdownWidth,
        isMobile: false,
      });
    }
  };

  // Handle dropdown open/close
  const toggleDropdown = () => {
    if (!isOpen) {
      calculateDropdownPosition();
    }
    setIsOpen(!isOpen);
  };

  // Handle tenant switch
  const handleTenantSwitch = async (tenantId: string) => {
    if (tenantId === currentTenant?.id) {
      setIsOpen(false);
      return;
    }

    const success = await switchTenant(tenantId);
    setIsOpen(false);

    if (success) {
      const newTenant = availableTenants?.find(t => t.id === tenantId);
      showToast.success(`Switched to ${newTenant?.name}`, {
        title: 'Tenant Switched'
      });
    } else {
      showToast.error(error || 'Failed to switch tenant', {
        title: 'Switch Failed'
      });
    }
  };

  // Handle retry loading tenants
  const handleRetry = () => {
    clearError();
    loadUserTenants();
  };

  // Handle creating new tenant
  const handleCreateNewTenant = () => {
    setIsOpen(false);
    navigate('/app/onboarding?new=true');
  };

  // Don't render for enterprise tier users (they use Premises page instead)
  if (subscriptionInfo?.plan === 'enterprise') {
    return null;
  }

  // Don't render if no tenants available
  if (!availableTenants || availableTenants.length === 0) {
    return null;
  }

  // Don't render if only one tenant
  if (availableTenants.length === 1) {
    return showLabel ? (
      <div className={`flex items-center space-x-2 text-text-secondary ${className}`}>
        <Building2 className="w-4 h-4" />
        <span className="text-sm font-medium">{currentTenant?.name}</span>
      </div>
    ) : null;
  }

  return (
    <div className={`relative ${className}`}>
      {/* Trigger Button */}
      <button
        ref={buttonRef}
        onClick={toggleDropdown}
        disabled={isLoading}
        className={`
          flex items-center justify-between w-full
          ${showLabel ? 'px-3 py-2.5' : 'px-2.5 py-2.5 justify-center'}
          text-sm font-medium text-[var(--text-primary)]
          bg-[var(--bg-secondary)] hover:bg-[var(--bg-tertiary)]
          border border-[var(--border-secondary)]
          rounded-lg transition-all duration-200
          focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]/20
          active:scale-[0.98] active:bg-[var(--bg-tertiary)]
          disabled:opacity-50 disabled:cursor-not-allowed
          min-h-[44px] touch-manipulation
          ${isOpen ? 'ring-2 ring-[var(--color-primary)]/20 bg-[var(--bg-tertiary)]' : ''}
        `}
        aria-expanded={isOpen}
        aria-haspopup="listbox"
        aria-label="Switch tenant"
      >
        <div className="flex items-center space-x-2 min-w-0 flex-1">
          <div className={`
            flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center
            ${currentTenant ? 'bg-[var(--color-primary)]/10' : 'bg-[var(--bg-tertiary)]'}
          `}>
            <Building2 className={`w-4 h-4 ${currentTenant ? 'text-[var(--color-primary)]' : 'text-[var(--text-tertiary)]'}`} />
          </div>
          {showLabel && (
            <div className="flex-1 min-w-0 text-left">
              <div className="text-sm font-medium text-[var(--text-primary)] truncate">
                {currentTenant?.name || 'Select Organization'}
              </div>
              {currentTenant?.city && (
                <div className="text-xs text-[var(--text-secondary)] truncate">
                  {currentTenant.city}
                </div>
              )}
            </div>
          )}
        </div>
        {showLabel && (
          <ChevronDown
            className={`w-4 h-4 text-[var(--text-secondary)] transition-transform duration-200 flex-shrink-0 ml-2 ${
              isOpen ? 'rotate-180' : ''
            }`}
          />
        )}
      </button>

      {/* Dropdown Menu - Rendered in portal to avoid stacking context issues */}
      {isOpen && createPortal(
        <>
          {/* Mobile Backdrop */}
          {dropdownPosition.isMobile && (
            <div
              className="fixed inset-0 bg-black/50 backdrop-blur-sm z-[9998]"
              onClick={() => setIsOpen(false)}
            />
          )}

          {/* Dropdown Content */}
          <div
            ref={dropdownRef}
            className={`
              fixed z-[9999] bg-[var(--bg-primary)] border border-[var(--border-primary)]
              shadow-2xl transition-all duration-300 ease-out
              ${dropdownPosition.isMobile
                ? 'inset-x-0 bottom-0 rounded-t-2xl max-h-[85vh]'
                : 'rounded-xl shadow-xl'
              }
            `}
            style={
              dropdownPosition.isMobile
                ? {}
                : {
                    top: `${dropdownPosition.top}px`,
                    left: `${dropdownPosition.left}px`,
                    width: `${dropdownPosition.width}px`,
                    maxHeight: '400px',
                  }
            }
            role="listbox"
            aria-label="Available tenants"
          >
            {/* Mobile Handle */}
            {dropdownPosition.isMobile && (
              <div className="flex justify-center py-3">
                <div className="w-10 h-1 bg-[var(--border-secondary)] rounded-full" />
              </div>
            )}

            {/* Header */}
            <div className={`
              flex items-center justify-between
              border-b border-[var(--border-primary)]
              ${dropdownPosition.isMobile ? 'px-6 py-4' : 'px-4 py-3'}
            `}>
              <h3 className={`font-semibold text-[var(--text-primary)] ${
                dropdownPosition.isMobile ? 'text-lg' : 'text-sm'
              }`}>
                Organizations
              </h3>
              {dropdownPosition.isMobile && (
                <button
                  onClick={() => setIsOpen(false)}
                  className="p-2 hover:bg-[var(--bg-secondary)] rounded-full transition-colors"
                >
                  <X className="w-5 h-5 text-[var(--text-secondary)]" />
                </button>
              )}
            </div>

            {/* Error State */}
            {error && (
              <div className={`border-b border-[var(--border-primary)] ${
                dropdownPosition.isMobile ? 'px-6 py-4' : 'px-4 py-3'
              }`}>
                <div className="flex items-center space-x-3 text-[var(--color-error)]">
                  <AlertCircle className="w-5 h-5 flex-shrink-0" />
                  <span className="text-sm flex-1">{error}</span>
                  <button
                    onClick={handleRetry}
                    className="text-[var(--color-primary)] hover:text-[var(--color-primary-dark)] underline text-sm font-medium"
                  >
                    Retry
                  </button>
                </div>
              </div>
            )}

            {/* Tenant List */}
            <div className={`
              overflow-y-auto
              ${dropdownPosition.isMobile ? 'max-h-[50vh] px-2 py-2' : 'max-h-72 py-1'}
            `}>
              {availableTenants.map((tenant) => (
                <button
                  key={tenant.id}
                  onClick={() => handleTenantSwitch(tenant.id)}
                  disabled={isLoading}
                  className={`
                    w-full text-left rounded-lg transition-all duration-200
                    hover:bg-[var(--bg-secondary)] focus:bg-[var(--bg-secondary)]
                    active:scale-[0.98] active:bg-[var(--bg-tertiary)]
                    focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]/20
                    disabled:opacity-50 disabled:cursor-not-allowed
                    ${dropdownPosition.isMobile ? 'px-4 py-4 mx-2 my-1 min-h-[60px]' : 'px-3 py-3 mx-1 my-0.5'}
                    ${tenant.id === currentTenant?.id ? 'bg-[var(--color-primary)]/5 ring-1 ring-[var(--color-primary)]/20' : ''}
                  `}
                  role="option"
                  aria-selected={tenant.id === currentTenant?.id}
                >
                  <div className="flex items-center justify-between">
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center space-x-3">
                        <div className={`
                          ${dropdownPosition.isMobile ? 'w-12 h-12' : 'w-10 h-10'}
                          rounded-full flex items-center justify-center flex-shrink-0 transition-colors
                          ${tenant.id === currentTenant?.id
                            ? 'bg-[var(--color-primary)] text-white'
                            : 'bg-[var(--color-primary)]/10 text-[var(--color-primary)]'
                          }
                        `}>
                          <Building2 className={`${dropdownPosition.isMobile ? 'w-6 h-6' : 'w-5 h-5'}`} />
                        </div>
                        <div className="min-w-0 flex-1">
                          <p className={`font-medium text-[var(--text-primary)] truncate ${
                            dropdownPosition.isMobile ? 'text-base' : 'text-sm'
                          }`}>
                            {tenant.name}
                          </p>
                          {tenant.city && (
                            <p className={`text-[var(--text-secondary)] truncate ${
                              dropdownPosition.isMobile ? 'text-sm' : 'text-xs'
                            }`}>
                              {tenant.city}
                            </p>
                          )}
                        </div>
                      </div>
                    </div>

                    {tenant.id === currentTenant?.id && (
                      <Check className={`text-[var(--color-success)] flex-shrink-0 ml-3 ${
                        dropdownPosition.isMobile ? 'w-6 h-6' : 'w-5 h-5'
                      }`} />
                    )}
                  </div>
                </button>
              ))}
            </div>

            {/* Footer */}
            <div className={`
              border-t border-[var(--border-primary)]
              ${dropdownPosition.isMobile ? 'px-6 py-6' : 'px-4 py-3'}
            `}>
              <button
                onClick={handleCreateNewTenant}
                className={`
                  w-full flex items-center justify-center gap-3
                  ${dropdownPosition.isMobile ? 'px-6 py-4 text-base' : 'px-4 py-2.5 text-sm'}
                  text-white font-semibold
                  bg-gradient-to-r from-[var(--color-primary)] to-[var(--color-primary-dark)]
                  hover:from-[var(--color-primary-dark)] hover:to-[var(--color-primary)]
                  shadow-md hover:shadow-lg
                  rounded-lg transition-all duration-200
                  focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)]/30
                  active:scale-[0.98]
                  border border-[var(--color-primary)]/30
                `}
              >
                <Plus className={`${dropdownPosition.isMobile ? 'w-5 h-5' : 'w-4 h-4'}`} />
                <span>Agregar Nueva Organización</span>
              </button>
            </div>
          </div>
        </>,
        document.body
      )}

      {/* Loading Overlay */}
      {isLoading && (
        <div className="absolute inset-0 bg-bg-primary/50 rounded-lg flex items-center justify-center">
          <div className="w-4 h-4 border-2 border-color-primary border-t-transparent rounded-full animate-spin"></div>
        </div>
      )}
    </div>
  );
};