import React, { useContext, useState } from 'react';
import { durationTicksInHoursString, formatPrice, getTranslations, longFormatDate, timeFromDateTime } from '../../../../shared/utils/localization-util';
import Icon from '../../../../shared/components/icon';
import SearchResultsConfigurationContext from '../../../search-results-configuration-context';
import { getArrivalSegment, getDepartureSegment, getFlightSegments, getNumberOfStopsLabel } from '../../../utils/flight-utils';
import { FlightSearchResponseFlight } from '@qite/tide-client';

interface IndependentFlightOptionProps {
  item: FlightSearchResponseFlight;
  onSelect?: () => void;
  guid: string | null;
  selectedGuid?: string | null;
  isOutward: boolean;
  showSelectedState?: boolean;
  currentSelectedPrice?: number;
  price?: number;
}

const IndependentFlightOption: React.FC<IndependentFlightOptionProps> = ({
  item,
  onSelect,
  guid,
  selectedGuid,
  isOutward,
  showSelectedState,
  currentSelectedPrice,
  price
}) => {
  const context = useContext(SearchResultsConfigurationContext);
  const language = context?.languageCode ?? 'en-GB';
  const translations = getTranslations(language);

  const [detailsOpen, setDetailsOpen] = useState(false);

  const priceDifference = price && currentSelectedPrice ? price - currentSelectedPrice : null;

  return (
    <div className="search__result-card" key={`flight-${item.code}`}>
      <div className={`flight ${showSelectedState && selectedGuid === guid ? 'flight--selected' : ''}`}>
        <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">
                    {price != null &&
                      price > 0 &&
                      (isOutward ? (
                        <span className="price">
                          {translations.QSM.ROUNDTRIP + ' ' + translations.SRP.PRICE}&nbsp;{formatPrice(price, 'EUR', context?.languageCode ?? 'en-GB')}
                        </span>
                      ) : (
                        priceDifference != null &&
                        Math.abs(priceDifference) > 0 && (
                          <span className="price">
                            {priceDifference > 0 ? '+' : '-'}&nbsp;{formatPrice(Math.abs(priceDifference), 'EUR', context?.languageCode ?? 'en-GB')}
                          </span>
                        )
                      ))}
                    <button type="button" className={`cta ${selectedGuid === guid ? 'cta--selected' : 'cta--select'}`} onClick={() => onSelect?.()}>
                      {selectedGuid === guid ? 'Selected' : 'Select'}
                    </button>
                  </div>
                </div>
              </div>
              <div className="flight__flight">
                <div className="flight__flight__container">
                  <div className="flight__flight__wrapper">
                    <div className="flight__logo__wrapper">
                      <img
                        src={`https://media.tidesoftware.be/media/shared/Airlines/${getDepartureSegment(item)?.marketingAirlineCode}.png?height=256`}
                        alt=""
                        className="flight__logo"
                      />
                      <span>{getDepartureSegment(item)?.marketingAirlineName}</span>
                    </div>
                    <div className="flight__info">
                      <div className="flight__info__times">
                        <strong>
                          {timeFromDateTime(getDepartureSegment(item)?.departureDateTime)} {getDepartureSegment(item)?.departureAirportCode}
                        </strong>
                        <p>{longFormatDate(getDepartureSegment(item)?.departureDateTime, language)}</p>
                      </div>
                      <div className="flight__info__duration">
                        <p>{durationTicksInHoursString(item.durationInTicks)}</p>
                        <div className="flight__info__duration__stops">
                          <div className="flight__info__duration__stop" />
                        </div>
                        <span>{getNumberOfStopsLabel(item, translations.SRP.DIRECT, translations.SRP.STOPS, translations.SRP.STOP)}</span>
                      </div>
                      <div className="flight__info__times flight__info__times--arrival">
                        <strong>
                          {timeFromDateTime(getArrivalSegment(item)?.arrivalDateTime)} {getArrivalSegment(item)?.arrivalAirportCode}
                        </strong>
                        <p>{longFormatDate(getArrivalSegment(item)?.arrivalDateTime, language)}</p>
                        {/* <span className="flight__info__times__days">+1 day</span> */}
                      </div>
                    </div>
                  </div>

                  <div className="flight__detail__btn__wrapper">
                    <div className={`flight__detail__btn ${detailsOpen ? 'flight__detail__btn--active' : ''}`} onClick={() => setDetailsOpen((prev) => !prev)}>
                      <Icon name="ui-chevron" className="flight__detail__btn__arrow" width={16} height={16} />
                    </div>
                  </div>
                </div>

                <div className={`flight__detail ${detailsOpen ? 'flight__detail--active' : ''}`}>
                  {getFlightSegments(item)?.map((segment, index) => (
                    <React.Fragment key={`outward-segment-${index}-${segment.flightNumber}`}>
                      <div className="flight__info">
                        <div className="flight__info__times__wrapper">
                          <div className="flight__info__times">
                            <p>{timeFromDateTime(segment.departureDateTime)}</p>
                            <strong>{segment.departureAirportCode}</strong>
                            <p>{longFormatDate(segment.departureDateTime, language)}</p>
                          </div>
                          <div>
                            <Icon name="ui-plane-depart" width={30} height={20} />
                          </div>
                        </div>
                        <div className="flight__info__duration">
                          <p>{durationTicksInHoursString(segment.durationInTicks)}</p>
                          <div className="flight__info__duration__stops" />
                          <span>{segment.marketingAirlineName}</span>
                          <strong>{segment.operatingFlightNumber}</strong>
                        </div>
                        <div className="flight__info__times__wrapper flight__info__times__wrapper--arrival">
                          <div>
                            <Icon name="ui-plane-arrive" width={30} height={20} />
                          </div>
                          <div className="flight__info__times flight__info__times--arrival">
                            <p>{timeFromDateTime(segment.arrivalDateTime)}</p>
                            <strong>{segment.arrivalAirportCode}</strong>
                            <p>{longFormatDate(segment.arrivalDateTime, language)}</p>
                          </div>
                        </div>
                      </div>

                      {segment.transferTimeInTicks && (
                        <div className="flight__info">
                          <div className="flight__info__times" />
                          <div className="flight__info__duration flight__info__duration--waittime">
                            <div className="flight__info__duration__stops flight__info__duration__stops--stoptime">
                              <Icon name="ui-clock" width={24} height={24} />
                            </div>
                            <div className="flight__info__duration__stoptime">
                              <span>Stop time</span>
                              <strong>{durationTicksInHoursString(segment.transferTimeInTicks)}</strong>
                            </div>
                          </div>
                          <div className="flight__info__times flight__info__times--arrival" />
                        </div>
                      )}
                    </React.Fragment>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default IndependentFlightOption;
