import React, { useContext, useState } from 'react';
import { durationTicksInHoursString, formatPrice, getTranslations, longFormatDate, timeFromDateTime } from '../../../../shared/utils/localization-util';
import Icon from '../../../../shared/components/icon';
import { ExtendedFlightSearchResponseItem } from '../../../types';
import SearchResultsConfigurationContext from '../../../search-results-configuration-context';
import { getArrivalSegment, getDepartureSegment, getFlightSegments, getNumberOfStopsLabel } from '../../../utils/flight-utils';
import { useDispatch, useSelector } from 'react-redux';
import { setFlyInIsOpen, setSelectedFlight } from '../../../store/search-results-slice';
import { SearchResultsRootState } from '../../../store/search-results-store';
import { useFlightSearch } from '../flight-search-context';

interface PairedFlightOptionProps {
  item: ExtendedFlightSearchResponseItem;
}

const PairedFlightOption: React.FC<PairedFlightOptionProps> = ({ item }) => {
  const dispatch = useDispatch();
  const { selectedFlight } = useSelector((state: SearchResultsRootState) => state.searchResults);
  const context = useContext(SearchResultsConfigurationContext);
  const { onFlightSearch } = useFlightSearch();
  const language = context?.languageCode ?? 'en-GB';
  const translations = getTranslations(language);

  const [isOutwardOpen, setIsOutwardOpen] = useState(false);
  const [isReturnOpen, setIsReturnOpen] = useState(false);

  const handleSelect = (flight: ExtendedFlightSearchResponseItem) => {
    dispatch(setSelectedFlight(flight));
    onFlightSearch(flight); // Trigger search to update accommodation options based on selected flight
    dispatch(setFlyInIsOpen(true));
  };

  return (
    <div className="search__result-card" key={`flight-${item.guid}`}>
      <div className="flight">
        <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">
                    <span className="price">{formatPrice(item.price, 'EUR', context?.languageCode ?? 'en-GB')}</span>
                    <button
                      type="button"
                      className={`cta ${selectedFlight?.guid === item.guid ? 'cta--selected' : 'cta--select'}`}
                      onClick={() => handleSelect(item)}>
                      {selectedFlight?.guid === item.guid ? 'Selected' : 'Select'}
                    </button>
                  </div>
                </div>
              </div>
              {item.outward && (
                <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.outward)?.marketingAirlineCode}.png?height=256`}
                          alt=""
                          className="flight__logo"
                        />
                        <span>{getDepartureSegment(item.outward)?.marketingAirlineName}</span>
                      </div>
                      <div className="flight__info">
                        <div className="flight__info__times">
                          <strong>
                            {timeFromDateTime(getDepartureSegment(item.outward)?.departureDateTime)} {getDepartureSegment(item.outward)?.departureAirportCode}
                          </strong>
                          <p>{longFormatDate(getDepartureSegment(item.outward)?.departureDateTime, language)}</p>
                        </div>
                        <div className="flight__info__duration">
                          <p>{durationTicksInHoursString(item.outward.durationInTicks)}</p>
                          <div className="flight__info__duration__stops">
                            <div className="flight__info__duration__stop" />
                          </div>
                          <span>{getNumberOfStopsLabel(item.outward, translations.SRP.DIRECT, translations.SRP.STOPS, translations.SRP.STOP)}</span>
                        </div>
                        <div className="flight__info__times flight__info__times--arrival">
                          <strong>
                            {timeFromDateTime(getArrivalSegment(item.outward)?.arrivalDateTime)} {getArrivalSegment(item.outward)?.arrivalAirportCode}
                          </strong>
                          <p>{longFormatDate(getArrivalSegment(item.outward)?.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 ${isOutwardOpen ? 'flight__detail__btn--active' : ''}`}
                        onClick={() => setIsOutwardOpen((prev) => !prev)}>
                        <Icon name="ui-chevron" className="flight__detail__btn__arrow" width={16} height={16} />
                      </div>
                    </div>
                  </div>

                  <div className={`flight__detail ${isOutwardOpen ? 'flight__detail--active' : ''}`}>
                    {getFlightSegments(item.outward).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>
              )}
              {item.return && (
                <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.return)?.marketingAirlineCode}.png?height=256`}
                          alt=""
                          className="flight__logo"
                        />
                        <span>{getDepartureSegment(item.return)?.marketingAirlineName}</span>
                      </div>
                      <div className="flight__info">
                        <div className="flight__info__times">
                          <strong>
                            {timeFromDateTime(getDepartureSegment(item.return)?.departureDateTime)} {getDepartureSegment(item.return)?.departureAirportCode}
                          </strong>
                          <p>{longFormatDate(getDepartureSegment(item.return)?.departureDateTime, language)}</p>
                        </div>
                        <div className="flight__info__duration">
                          <p>{durationTicksInHoursString(item.return.durationInTicks)}</p>
                          <div className="flight__info__duration__stops">
                            <div className="flight__info__duration__stop" />
                          </div>
                          <span>{getNumberOfStopsLabel(item.return, translations.SRP.DIRECT, translations.SRP.STOPS, translations.SRP.STOP)}</span>
                        </div>
                        <div className="flight__info__times flight__info__times--arrival">
                          <strong>
                            {timeFromDateTime(getArrivalSegment(item.return)?.arrivalDateTime)} {getArrivalSegment(item.return)?.arrivalAirportCode}
                          </strong>
                          <p>{longFormatDate(getArrivalSegment(item.return)?.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 ${isReturnOpen ? 'flight__detail__btn--active' : ''}`}
                        onClick={() => setIsReturnOpen((prev) => !prev)}>
                        <Icon name="ui-chevron" className="flight__detail__btn__arrow" width={16} height={16} />
                      </div>
                    </div>
                  </div>

                  <div className={`flight__detail ${isReturnOpen ? 'flight__detail--active' : ''}`}>
                    {getFlightSegments(item.return).map((segment, index) => (
                      <React.Fragment key={`return-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 PairedFlightOption;
