import React, { useState } from 'react';
import { useSelector } from 'react-redux';
import { buildClassName } from '../../../shared/utils/class-util';
import { getPriceDifferenceText } from '../../../shared/utils/localization-util';
import { GroupedFlights } from '../../types';
import { selectCurrencyCode, selectTranslations } from '../booking/selectors';
import FlightOptionFlight from './flight-option-flight';

interface FlightOptionProps {
  item: GroupedFlights;
  isSelected: boolean;
  currentPrice: number;
  onChange: (item: GroupedFlights) => void;
}

const FlightOption: React.FC<FlightOptionProps> = ({ item, isSelected, currentPrice, onChange }) => {
  const translations = useSelector(selectTranslations);
  const currencyCode = useSelector(selectCurrencyCode);

  const ownTotalPrice = item.selectedOutward.price + item.selectedReturn.price;
  const priceDifference = item.isSelected ? 0 : ownTotalPrice - currentPrice;

  const [outwardVisible] = useState<boolean>(false);
  const [returnVisible] = useState<boolean>(false);

  const handleButtonClick = () => {
    if (!item.isSelected) onChange(item);
  };

  return (
    <div className="flight__option">
      <div className="flight__content">
        <div className="flight__flights">
          <div className="flight__flight">
            <div className="flight__flight__header">
              <div className="flight__status__container"></div>
              <div className="flight__price">
                {!isSelected && (
                  <span className={buildClassName(['price', priceDifference > 0 && 'price--increase', priceDifference < 0 && 'price--decrease'])}>
                    {getPriceDifferenceText(priceDifference, currencyCode)}
                  </span>
                )}
                <button type="button" className={`cta ${isSelected ? 'cta--selected' : 'cta--select'}`} onClick={handleButtonClick}>
                  {isSelected ? translations.SHARED.SELECTED : translations.SHARED.SELECT}
                </button>
              </div>
            </div>
          </div>
          <FlightOptionFlight details={item.outward} isOptionsVisible={outwardVisible} />
          <FlightOptionFlight details={item.return} isOptionsVisible={returnVisible} />
        </div>
      </div>
    </div>
  );
};

export default FlightOption;
