import { useContext, useState } from 'react';
import { HouseholdContext } from '../../context/HouseholdContext';
import '../../styles/components/HouseholdSwitcher.css';
import CreateJoinHousehold from '../manage/CreateJoinHousehold';

export default function HouseholdSwitcher() {
  const { households, activeHousehold, setActiveHousehold, loading } = useContext(HouseholdContext);
  const [isOpen, setIsOpen] = useState(false);
  const [showCreateJoin, setShowCreateJoin] = useState(false);

  if (!activeHousehold || households.length === 0) {
    return null;
  }

  const handleSelect = (household) => {
    setActiveHousehold(household);
    setIsOpen(false);
  };

  return (
    <div className="household-switcher">
      <button
        className="household-switcher-toggle"
        onClick={() => setIsOpen(!isOpen)}
        disabled={loading}
      >
        <span className="household-name">{activeHousehold.name}</span>
        <span className={`dropdown-icon ${isOpen ? 'open' : ''}`}>▼</span>
      </button>

      {isOpen && (
        <>
          <div className="household-switcher-overlay" onClick={() => setIsOpen(false)} />
          <div className="household-switcher-dropdown">
            {households.map(household => (
              <button
                key={household.id}
                className={`household-option ${household.id === activeHousehold.id ? 'active' : ''}`}
                onClick={() => handleSelect(household)}
              >
                {household.name}
                {household.id === activeHousehold.id && (
                  <span className="check-mark">✓</span>
                )}
              </button>
            ))}
            <div className="household-divider"></div>
            <button
              className="household-option create-household-btn"
              onClick={() => {
                setIsOpen(false);
                setShowCreateJoin(true);
              }}
            >
              + Create or Join Household
            </button>
          </div>
        </>
      )}

      {showCreateJoin && (
        <CreateJoinHousehold onClose={() => setShowCreateJoin(false)} />
      )}
    </div>
  );
}
