import React, { useState, useRef, useEffect, useContext } from 'react';
import TravelInput from '../travel-input';
import { useDispatch, useSelector } from 'react-redux';
import { setAdults, setMobileFilterType, setRooms } from '../../store/qsm-slice';
import useMediaQuery from '../../../shared/utils/use-media-query-util';
import { QSMRootState } from '../../store/qsm-store';
import QSMConfigurationContext from '../../qsm-configuration-context';
import Icon from '../../../shared/components/icon';
import { getTranslations } from '../../../shared/utils/localization-util';
import { PortalQsmType } from '@qite/tide-client';

const selectTravelerSummary = (state: QSMRootState, areTravelersInRooms: boolean | undefined) => {
  const { adults, kids, babies, rooms, selectedTravelType } = state.qsm;

  const total = areTravelersInRooms ? rooms.reduce((sum, r) => sum + r.adults + r.kids + r.babies, 0) : adults + kids + babies;

  let summary = `${total} reiziger${total === 1 ? '' : 's'}`;
  if (areTravelersInRooms) {
    summary += `, ${rooms.length} kamer${rooms.length === 1 ? '' : 's'}`;
  }

  if (selectedTravelType) {
    summary = `${selectedTravelType} • ${summary}`;
  }

  return summary;
};

const TravelInputGroup: React.FC = () => {
  const dispatch = useDispatch();
  const isSmallScreen = useMediaQuery('(max-width: 768px)');
  const [isOpen, setIsOpen] = useState(false);
  const wrapperRef = useRef<HTMLDivElement>(null);
  const { askRooms, defaultTravelers, maxTravelers, languageCode } = useContext(QSMConfigurationContext);
  const { adults, rooms, qsmType } = useSelector((s: QSMRootState) => s.qsm);

  const translations = getTranslations(languageCode ?? 'en-GB');

  const areTravelersInRooms = qsmType !== PortalQsmType.Flight && askRooms;

  const initDone = useRef(false);

  const travelerSummary = useSelector((state: QSMRootState) => selectTravelerSummary(state, areTravelersInRooms));

  const handleClick = () => {
    if (isSmallScreen) {
      dispatch(setMobileFilterType('traveler'));
    } else {
      setIsOpen((prev) => !prev);
    }
  };

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (wrapperRef.current && !wrapperRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };

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

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

  useEffect(() => {
    if (initDone.current) {
      return;
    }

    const cap = Math.min(defaultTravelers || 2, maxTravelers ?? Infinity);

    if (areTravelersInRooms) {
      const updated = rooms.map((r) => (r.adults !== cap ? { ...r, adults: cap } : r));
      if (updated.some((r, i) => r.adults !== rooms[i].adults)) {
        dispatch(setRooms(updated));
      }
    } else {
      if (adults !== cap) {
        dispatch(setAdults(cap));
      }
    }

    initDone.current = true;
  }, [defaultTravelers, maxTravelers]);

  return (
    <div ref={wrapperRef} className="qsm__single-input-wrapper qsm__single-input-wrapper--travel">
      <Icon name="ui-user" height={16} />

      <span className="qsm__label">{translations.QSM.TRAVELERS_LABEL}</span>
      <input
        type="text"
        id="traveler"
        className="qsm__input u-ps-2"
        placeholder={translations.QSM.TRAVELERS_LABEL}
        readOnly
        onClick={handleClick}
        value={travelerSummary}
      />

      {!isSmallScreen && isOpen && (
        <div>
          <TravelInput />
        </div>
      )}
    </div>
  );
};

export default TravelInputGroup;
