
import React, { useState, useRef, useEffect } from 'react';
import { mdiOfficeBuilding, mdiStore, mdiChevronDown, mdiChevronUp, mdiAccountGroup } from '@mdi/js';
import BaseIcon from './BaseIcon';
import { useAppDispatch, useAppSelector } from '../stores/hooks';
import { fetchAvailableContexts, setActiveContext } from '../stores/contextSlice';

export default function ContextSwitcher() {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const dispatch = useAppDispatch();
  const { activeContext, availableMerchants, availableFirms } = useAppSelector((state) => state.context);
  const { currentUser } = useAppSelector((state) => state.auth);

  useEffect(() => {
    if (currentUser) {
      dispatch(fetchAvailableContexts());
    }
  }, [dispatch, currentUser]);

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    }
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  if (!activeContext && availableMerchants.length === 0 && availableFirms.length === 0) {
    return null;
  }

  const handleSelect = (entity: any) => {
    dispatch(setActiveContext(entity));
    setIsOpen(false);
  };

  return (
    <div className="relative" ref={dropdownRef}>
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center space-x-3 px-4 py-2 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-2xl shadow-sm hover:border-indigo-400 transition-colors focus:outline-none"
      >
        <div className={`w-10 h-10 rounded-xl flex items-center justify-center ${activeContext?.type === 'merchant' ? 'bg-blue-50 text-blue-600' : 'bg-amber-50 text-amber-600'}`}>
          <BaseIcon path={activeContext?.type === 'merchant' ? mdiStore : mdiOfficeBuilding} size={20} />
        </div>
        <div className="flex flex-col items-start min-w-[150px]">
          <span className="text-sm font-bold text-slate-800 dark:text-white truncate max-w-[200px]">
            {activeContext?.name || 'Select Entity'}
          </span>
          <span className="text-[10px] text-slate-500 uppercase tracking-wider font-semibold">
            {activeContext?.type === 'merchant' ? 'Merchant' : 'Accounting Firm'}
          </span>
        </div>
        <BaseIcon path={isOpen ? mdiChevronUp : mdiChevronDown} size={20} className="text-slate-400" />
      </button>

      {isOpen && (
        <div className="absolute top-full left-0 mt-2 w-[320px] bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-2xl shadow-2xl z-50 overflow-hidden animate-fade-in-up">
          <div className="max-h-[400px] overflow-y-auto aside-scrollbars">
            
            {availableMerchants.length > 0 && (
              <div className="py-2">
                <div className="px-4 py-2 text-[10px] font-bold text-slate-400 uppercase tracking-widest">
                  Merchants
                </div>
                {availableMerchants.map((merchant) => (
                  <button
                    key={merchant.id}
                    onClick={() => handleSelect(merchant)}
                    className={`w-full flex items-center space-x-3 px-4 py-3 hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors ${activeContext?.id === merchant.id ? 'bg-indigo-50 dark:bg-indigo-900/20' : ''}`}
                  >
                    <div className="w-8 h-8 rounded-lg bg-blue-100 dark:bg-blue-900/40 text-blue-600 flex items-center justify-center">
                      <BaseIcon path={mdiStore} size={18} />
                    </div>
                    <div className="flex flex-col items-start overflow-hidden">
                      <span className={`text-sm font-bold truncate w-full ${activeContext?.id === merchant.id ? 'text-indigo-600 dark:text-indigo-400' : 'text-slate-700 dark:text-slate-200'}`}>
                        {merchant.name}
                      </span>
                      {merchant.registration && (
                        <span className="text-[10px] text-slate-400 font-medium">
                          TIN: {merchant.registration}
                        </span>
                      )}
                    </div>
                  </button>
                ))}
              </div>
            )}

            {availableFirms.length > 0 && (
              <div className="py-2 border-t border-slate-100 dark:border-slate-800">
                <div className="px-4 py-2 text-[10px] font-bold text-slate-400 uppercase tracking-widest">
                  Firms
                </div>
                {availableFirms.map((firm) => (
                  <button
                    key={firm.id}
                    onClick={() => handleSelect(firm)}
                    className={`w-full flex items-center space-x-3 px-4 py-3 hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors ${activeContext?.id === firm.id ? 'bg-indigo-50 dark:bg-indigo-900/20' : ''}`}
                  >
                    <div className="w-8 h-8 rounded-lg bg-amber-100 dark:bg-amber-900/40 text-amber-600 flex items-center justify-center">
                      <BaseIcon path={mdiOfficeBuilding} size={18} />
                    </div>
                    <div className="flex flex-col items-start overflow-hidden">
                      <span className={`text-sm font-bold truncate w-full ${activeContext?.id === firm.id ? 'text-indigo-600 dark:text-indigo-400' : 'text-slate-700 dark:text-slate-200'}`}>
                        {firm.name}
                      </span>
                      {firm.registration && (
                        <span className="text-[10px] text-slate-400 font-medium">
                          Reg: {firm.registration}
                        </span>
                      )}
                    </div>
                  </button>
                ))}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
