import React, { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { getPriceDifferenceText } from '../../../shared/utils/localization-util';
import { SelectableRoomAccommodation } from '../../types';
import { selectCurrencyCode, selectTranslations } from '../booking/selectors';
import { getDatePeriodText, getDateText } from '../sidebar/sidebar-util';
import { buildClassName } from '../../../shared/utils/class-util';

interface RoomOptionProps {
  room: SelectableRoomAccommodation;
  hasAlternatives?: boolean;
  selectedRoomPrice?: number;
  onAcommodationChange?: (accommodationCode: string, regimeCode: string) => void;
  onRegimeChange?: (code: string) => void;
  onToggleAlternatives?: () => void;
}

const RoomOption: React.FC<RoomOptionProps> = ({ room, hasAlternatives, selectedRoomPrice, onAcommodationChange, onRegimeChange, onToggleAlternatives }) => {
  const translations = useSelector(selectTranslations);
  const currencyCode = useSelector(selectCurrencyCode);

  const [roomPrice, setRoomPrice] = useState<number>(0);
  const [roomRegimeCode, setRoomRegimeCode] = useState<string>(room.regimeCode);

  useEffect(() => {
    setRoomPrice(room.price);
  }, [room.code, room.regimeCode]);

  const getPriceDifference = (selectedPrice: number, currentPrice: number) => {
    const priceDifference = (selectedPrice ?? 0) - currentPrice;
    if (priceDifference !== 0) {
      return `(${getPriceDifferenceText(priceDifference, currencyCode)})`;
    } else {
      return '';
    }
  };

  const selectAccommodation = () => {
    if (onAcommodationChange) {
      onAcommodationChange(room.code, roomRegimeCode);
    }
  };

  const handleRegimeChange: React.FormEventHandler<HTMLSelectElement> = (e) => {
    let regimeCode = e.currentTarget.value;

    const option = room.regimes.find((x) => x.code === regimeCode || (x.code === null && regimeCode === ''))!;
    setRoomRegimeCode(option.code);
    setRoomPrice(option.price);

    if (onRegimeChange) {
      onRegimeChange(regimeCode);
    }

    e.preventDefault();
  };

  return (
    <>
      <div className="form__room">
        {room.viewHtml && <div className="form__room__wrapper" dangerouslySetInnerHTML={{ __html: room.viewHtml }} />}
        {!room.viewHtml && (
          <div className="form__room__wrapper">
            {room.image && (
              <div className="form__room__image">
                <img src={room.image} alt="" className="form__room__img" />
              </div>
            )}
            <div className="form__room__body">
              <div className="">
                <h3 className="form__room__title">{room.title}</h3>
                {room.description && <p className="form__room__text">{room.description}</p>}
                <ul className="list--usps form__room__usps">
                  {room.usps.map((usp, uspIndex) => (
                    <li key={uspIndex} className="list__item">
                      {usp}
                    </li>
                  ))}
                </ul>
              </div>
            </div>
          </div>
        )}
        <div className="form__room__footer">
          <div className="form__room__footer__top">
            <p className="form__room__dates">
              {getDateText(room.from)} - {getDateText(room.to)}
            </p>
            <span className="form__room__days">{getDatePeriodText(translations, room.from, room.to)}</span>
          </div>
          <div className="form__room__footer__bottom">
            {selectedRoomPrice != undefined && (
              <p className="form__room__price form__room__price--increase">
                <span>{getPriceDifference(roomPrice, selectedRoomPrice)}</span>
              </p>
            )}
            {hasAlternatives && onToggleAlternatives && (
              <button type="button" onClick={onToggleAlternatives} className="form__room__alternatives__btn">
                {translations.ROOM_OPTIONS_FORM.SHOW_ALTERNATIVES}
              </button>
            )}
            <div className="select-wrapper">
              <div className="select-wrapper__select">
                <select defaultValue={roomRegimeCode} onChange={handleRegimeChange}>
                  {room.regimes.map((regime) => (
                    <option key={regime.code} value={regime.code ?? ''}>
                      {regime.title} {getPriceDifference(regime.price, roomPrice)}
                    </option>
                  ))}
                </select>
              </div>
            </div>
            <button type="button" onClick={selectAccommodation} className={buildClassName(['cta', selectedRoomPrice ? 'cta--select' : 'cta--selected'])}>
              {selectedRoomPrice ? translations.SHARED.SELECT : translations.SHARED.SELECTED}
            </button>
          </div>
        </div>
      </div>
    </>
  );
};

export default RoomOption;
