import React, { useContext } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { QSMRootState } from '../../store/qsm-store';
import { setAdults, setKids, setBabies, setRooms, addRoom, removeRoom, updateRoomTraveler } from '../../store/qsm-slice';
import QSMConfigurationContext from '../../qsm-configuration-context';
import { getTranslations } from '../../../shared/utils/localization-util';
import Icon from '../../../shared/components/icon';
import { PortalQsmType } from '@qite/tide-client';

const TravelInput: React.FC = () => {
  const dispatch = useDispatch();
  const { askRooms, maxTravelers, defaultTravelers, maxChildAge, maxInfantAge, askTravelType, askTravelClass, languageCode } =
    useContext(QSMConfigurationContext);
  const { adults, kids, babies, rooms, qsmType } = useSelector((state: QSMRootState) => state.qsm);
  const areTravelersInRooms = qsmType !== PortalQsmType.Flight && askRooms;

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

  const getTravelerButtonClass = (disabled: boolean) => `button button--increment ${disabled ? 'button--disabled' : ''}`;

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

  const safeMaxTravelers = maxTravelers ?? Infinity;
  const canAddTraveler = totalTravelers < safeMaxTravelers;

  const syncRoomsToRedux = (updatedRooms: typeof rooms) => {
    dispatch(setRooms(updatedRooms));
  };

  const handleTravelerChange = (roomIndex: number, type: 'adults' | 'kids' | 'babies', newValue: number) => {
    const updatedRooms = rooms.map((room, idx) => (idx === roomIndex ? { ...room, [type]: newValue } : room));

    syncRoomsToRedux(updatedRooms);

    dispatch(
      updateRoomTraveler({
        roomIndex,
        type,
        value: newValue
      })
    );
  };

  const handleAddRoom = () => {
    const remaining = (maxTravelers ?? Infinity) - totalTravelers;
    const adultsForRoom = Math.min(defaultTravelers || 2, remaining);

    if (adultsForRoom <= 0) {
      return;
    }

    const newRoom = {
      adults: adultsForRoom,
      kids: 0,
      babies: 0
    };
    const updatedRooms = [...rooms.map((r) => ({ ...r })), newRoom];

    dispatch(addRoom());
    syncRoomsToRedux(updatedRooms);
  };

  const handleRemoveRoom = (index: number) => {
    const updatedRooms = rooms.map((r) => ({ ...r })).filter((_, idx) => idx !== index);

    dispatch(removeRoom(index));
    syncRoomsToRedux(updatedRooms);
  };

  // Compute age labels dynamically
  const ageLabels = {
    adults: maxChildAge ? `${maxChildAge + 1}+ ${translations.PRODUCT.YEAR}` : `12+ ${translations.PRODUCT.YEAR}`,
    kids: maxChildAge && maxInfantAge ? `${maxInfantAge + 1}-${maxChildAge} ${translations.PRODUCT.YEAR}` : `2-11 ${translations.PRODUCT.YEAR}`,
    babies: maxInfantAge !== undefined ? `0-${maxInfantAge} ${translations.PRODUCT.YEAR}` : `0-1 ${translations.PRODUCT.YEAR}`
  };

  return (
    <div className="passenger-picker">
      {areTravelersInRooms ? (
        <div>
          <div className="passenger-picker__rooms-header">
            <h4 className="passenger-picker__rooms-header-title">
              {translations.SHARED.ROOMS}: <span className="passenger-picker__rooms-header-count">{rooms.length}</span>
            </h4>
            {rooms.length < 4 && (
              <div
                className={`cta--secondary${!canAddTraveler ? ' cta--disabled' : ''}`}
                onClick={() => {
                  if (canAddTraveler) {
                    handleAddRoom();
                  }
                }}>
                {translations.QSM.ADD_ROOM}
              </div>
            )}
          </div>

          <div className="passenger-picker__rooms-wrapper">
            {rooms.map((room, idx) => (
              <div key={idx} className="passenger-picker__room">
                <h6 className="passenger-picker__room-title">
                  {translations.SHARED.ROOM} {idx + 1}
                </h6>

                {(['adults', 'kids', 'babies'] as const).map((type) => (
                  <div key={type} className="passenger-picker__item">
                    <div className="passenger-picker__item-text">
                      <span>{type === 'adults' ? 'Volwassenen' : type === 'kids' ? 'Kinderen' : 'Baby’s'}</span>
                      <span className="passenger-picker__item-text-age">{ageLabels[type]}</span>
                    </div>

                    <div className="decrement-increment__ui">
                      {/* - button */}
                      <button
                        type="button"
                        className={`button button--decrement ${room[type] === 0 ? 'button--disabled' : ''}`}
                        onClick={() => room[type] > 0 && handleTravelerChange(idx, type, room[type] - 1)}>
                        <Icon name="ui-min" />
                      </button>

                      <span>{room[type]}</span>

                      {/* + button with max check */}
                      <button
                        className={getTravelerButtonClass(!canAddTraveler)}
                        onClick={() => canAddTraveler && handleTravelerChange(idx, type, room[type] + 1)}>
                        <Icon name="ui-plus" />
                      </button>
                    </div>
                  </div>
                ))}

                {rooms.length > 1 && (
                  <div className="passenger-picker__remove-room">
                    <button type="button" className="cta--remove" onClick={() => handleRemoveRoom(idx)}>
                      {translations.QSM.REMOVE_ROOM}
                    </button>
                  </div>
                )}
                {/* Info Message */}
                {!canAddTraveler && (
                  <div className="passenger-picker__info-message">
                    <svg className="passenger-picker__info-message-icon" width={16} height={16} viewBox="0 0 15.967 15.967">
                      <path
                        id="error_16dp_UNDEFINED_FILL0_wght400_GRAD0_opsz20"
                        d="M103.979-852.024a.735.735,0,0,0,.535-.214.713.713,0,0,0,.218-.53.735.735,0,0,0-.214-.535.712.712,0,0,0-.53-.218.735.735,0,0,0-.535.214.713.713,0,0,0-.218.53.734.734,0,0,0,.214.535A.712.712,0,0,0,103.979-852.024Zm-.744-2.994h1.5v-4.99h-1.5Zm.754,6.986a7.8,7.8,0,0,1-3.1-.624,8.048,8.048,0,0,1-2.547-1.715,8.051,8.051,0,0,1-1.715-2.546A7.8,7.8,0,0,1,96-856.026a7.735,7.735,0,0,1,.624-3.1,8.079,8.079,0,0,1,1.715-2.536,8.051,8.051,0,0,1,2.546-1.715,7.8,7.8,0,0,1,3.108-.624,7.735,7.735,0,0,1,3.1.624,8.081,8.081,0,0,1,2.536,1.715,8.066,8.066,0,0,1,1.715,2.541,7.755,7.755,0,0,1,.624,3.1,7.8,7.8,0,0,1-.624,3.1,8.048,8.048,0,0,1-1.715,2.547,8.066,8.066,0,0,1-2.541,1.715A7.754,7.754,0,0,1,103.99-848.033Zm-.006-1.5a6.255,6.255,0,0,0,4.595-1.892,6.256,6.256,0,0,0,1.892-4.595,6.255,6.255,0,0,0-1.892-4.595,6.255,6.255,0,0,0-4.595-1.892,6.255,6.255,0,0,0-4.595,1.892,6.255,6.255,0,0,0-1.892,4.595,6.256,6.256,0,0,0,1.892,4.595A6.256,6.256,0,0,0,103.984-849.529ZM103.984-856.016Z"
                        transform="translate(-96 864)"
                      />
                    </svg>
                    <span className="passenger-picker__info-message-explanation">{translations.QSM.MAX_TRAVELERS_REACHED}</span>
                  </div>
                )}

                <div className="passenger-picker__line passenger-picker__line--room"></div>
              </div>
            ))}
          </div>
        </div>
      ) : (
        <div>
          <div className="passenger-picker__items">
            {/* Adults */}
            <div className="passenger-picker__item">
              <div className="passenger-picker__item-text">
                <span>{translations.QSM.ADULTS}</span>
                <span className="passenger-picker__item-text-age">{ageLabels.adults}</span>
              </div>
              <div className="decrement-increment__ui">
                <div
                  className={`button button--decrement ${adults === 0 ? 'button--disabled' : ''}`}
                  onClick={() => adults > 0 && dispatch(setAdults(adults - 1))}>
                  <Icon name="ui-min" />
                </div>
                <span>{adults}</span>
                <div className={getTravelerButtonClass(!canAddTraveler)} onClick={() => canAddTraveler && dispatch(setAdults(adults + 1))}>
                  <Icon name="ui-plus" />
                </div>
              </div>
            </div>

            {/* Children */}
            <div className="passenger-picker__item">
              <div className="passenger-picker__item-text">
                <span>{translations.QSM.CHILDREN}</span>
                <span className="passenger-picker__item-text-age">{ageLabels.kids}</span>
              </div>
              <div className="decrement-increment__ui">
                <div className={getTravelerButtonClass(!canAddTraveler)} onClick={() => kids > 0 && dispatch(setKids(kids - 1))}>
                  <Icon name="ui-min" />
                </div>
                <span>{kids}</span>
                <div className={getTravelerButtonClass(!canAddTraveler)} onClick={() => canAddTraveler && dispatch(setKids(kids + 1))}>
                  <Icon name="ui-plus" />
                </div>
              </div>
            </div>

            {/* Babies */}
            <div className="passenger-picker__item">
              <div className="passenger-picker__item-text">
                <span>{translations.QSM.BABIES}</span>
                <span className="passenger-picker__item-text-age">{ageLabels.babies}</span>
              </div>
              <div className="decrement-increment__ui">
                <div
                  className={`button button--decrement ${babies === 0 ? 'button--disabled' : ''}`}
                  onClick={() => babies > 0 && dispatch(setBabies(babies - 1))}>
                  <Icon name="ui-min" />
                </div>
                <span>{babies}</span>
                <div className={getTravelerButtonClass(!canAddTraveler)} onClick={() => canAddTraveler && dispatch(setBabies(babies + 1))}>
                  <Icon name="ui-plus" />
                </div>
              </div>
            </div>
          </div>
          {/* Info Message */}
          {!canAddTraveler && (
            <div className="passenger-picker__info-message">
              <svg className="passenger-picker__info-message-icon" width={16} height={16} viewBox="0 0 15.967 15.967">
                <path
                  id="error_16dp_UNDEFINED_FILL0_wght400_GRAD0_opsz20"
                  d="M103.979-852.024a.735.735,0,0,0,.535-.214.713.713,0,0,0,.218-.53.735.735,0,0,0-.214-.535.712.712,0,0,0-.53-.218.735.735,0,0,0-.535.214.713.713,0,0,0-.218.53.734.734,0,0,0,.214.535A.712.712,0,0,0,103.979-852.024Zm-.744-2.994h1.5v-4.99h-1.5Zm.754,6.986a7.8,7.8,0,0,1-3.1-.624,8.048,8.048,0,0,1-2.547-1.715,8.051,8.051,0,0,1-1.715-2.546A7.8,7.8,0,0,1,96-856.026a7.735,7.735,0,0,1,.624-3.1,8.079,8.079,0,0,1,1.715-2.536,8.051,8.051,0,0,1,2.546-1.715,7.8,7.8,0,0,1,3.108-.624,7.735,7.735,0,0,1,3.1.624,8.081,8.081,0,0,1,2.536,1.715,8.066,8.066,0,0,1,1.715,2.541,7.755,7.755,0,0,1,.624,3.1,7.8,7.8,0,0,1-.624,3.1,8.048,8.048,0,0,1-1.715,2.547,8.066,8.066,0,0,1-2.541,1.715A7.754,7.754,0,0,1,103.99-848.033Zm-.006-1.5a6.255,6.255,0,0,0,4.595-1.892,6.256,6.256,0,0,0,1.892-4.595,6.255,6.255,0,0,0-1.892-4.595,6.255,6.255,0,0,0-4.595-1.892,6.255,6.255,0,0,0-4.595,1.892,6.255,6.255,0,0,0-1.892,4.595,6.256,6.256,0,0,0,1.892,4.595A6.256,6.256,0,0,0,103.984-849.529ZM103.984-856.016Z"
                  transform="translate(-96 864)"
                />
              </svg>
              <span className="passenger-picker__info-message-explanation">{translations.QSM.MAX_TRAVELERS_REACHED}</span>
            </div>
          )}

          <div className="passenger-picker__line"></div>
        </div>
      )}

      {/* {type === 'flight' && askTravelClass && <TravelClassPicker />}
      {type !== 'flight' && askTravelType && <TravelTypePicker />} */}
    </div>
  );
};

export default TravelInput;
