import React, { useContext, useState } from 'react';
import Icon from '../../../shared/components/icon';
import { BookingPackageFlight } from '@qite/tide-client';
import { parseISO, format } from 'date-fns';
import { useDispatch } from 'react-redux';
import { selectFlight } from '../../store/search-results-slice';
import { getTranslations } from '../../../shared/utils/localization-util';
import SearchResultsConfigurationContext from '../../search-results-configuration-context';

interface FlightResultsProps {
  flights?: BookingPackageFlight[];
  isDeparture?: boolean;
}

const ticksToMinutes = (ticks: number) => Math.floor(ticks / 600000000);

const formatDuration = (ticks: number) => {
  const minutes = ticksToMinutes(ticks);
  const h = Math.floor(minutes / 60);
  const m = minutes % 60;
  return `${h}h ${m}m`;
};

const FlightResults: React.FC<FlightResultsProps> = ({ flights, isDeparture }) => {
  const context = useContext(SearchResultsConfigurationContext);
  const translations = getTranslations(context?.languageCode ?? 'en-GB');

  const dispatch = useDispatch();

  const [activeDetailId, setActiveDetailId] = useState<string | null>(null);

  const handleDetailClick = (flightOptionId: string) => {
    setActiveDetailId((prev) => (prev === flightOptionId ? null : flightOptionId));
  };

  const firstResult = flights?.[0];
  const firstResultDate = firstResult?.startDateTime ? parseISO(firstResult.startDateTime) : null;

  return (
    <>
      {/* Header */}
      <div className="search__results__label">
        <div className="search__results__label__date">
          {firstResultDate && (
            <>
              <p className="search__results__label__date-date">{format(firstResultDate, 'd')}</p>
              <p>{format(firstResultDate, 'MMM')}</p>
            </>
          )}
        </div>
        <div className="search__results__label__text">
          <h3>
            {translations.SRP.SELECT} <strong>{isDeparture ? translations.SRP.DEPARTURE : translations.SRP.RETURN}</strong>
          </h3>
        </div>
      </div>

      {flights && flights.length > 0 && (
        <div className="search__results__cards search__results__cards--extended">
          {flights.map((flight, index) => {
            const lines = flight.flightMetaData.flightLines;
            const firstLine = lines[0];
            const lastLine = lines[lines.length - 1];
            const stops = lines.length - 1;

            return (
              <div className="flight" key={`flight-${flight.flightId}-${index}`}>
                <div className="flight__option">
                  <div className="flight__content">
                    <div className="flight__flights">
                      {/* HEADER */}
                      <div className="flight__flight">
                        <div className="flight__flight__header">
                          <div className="flight__status__container" />
                          <div className="flight__price">
                            <span className="price">€ {flight.price.toFixed(2)}</span>

                            <button
                              type="button"
                              className={`cta ${flight.isSelected ? 'cta--selected' : 'cta--select'}`}
                              onClick={() => dispatch(selectFlight({ flightOptionId: flight.flightOptionId, isDeparture: !!isDeparture }))}>
                              {flight.isSelected ? 'Selected' : 'Select'}
                            </button>
                          </div>
                        </div>
                      </div>

                      {/* SUMMARY */}
                      <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/${firstLine.airlineCode}.png?height=256`}
                                alt={flight.airlineDescription}
                                className="flight__logo"
                              />
                              <span>{flight.airlineDescription}</span>
                            </div>

                            <div className="flight__info">
                              <div className="flight__info__times">
                                <strong>
                                  {firstLine.departureTime} {firstLine.departureAirport}
                                </strong>
                                <p>{format(parseISO(firstLine.departureDate), 'EEE dd MMM yyyy')}</p>
                              </div>

                              <div className="flight__info__duration">
                                <p>{formatDuration(flight.flightMetaData.durationInTicks)}</p>

                                <div className="flight__info__duration__stops">{stops > 0 && <div className="flight__info__duration__stop" />}</div>

                                <span>{stops === 0 ? translations.SRP.DIRECT : `${stops} ${translations.SRP.STOP}${stops > 1 ? 's' : ''}`}</span>
                              </div>

                              <div className="flight__info__times flight__info__times--arrival">
                                <strong>
                                  {lastLine.arrivalTime} {lastLine.arrivalAirport}
                                </strong>
                                <p>{format(parseISO(lastLine.arrivalDate), 'EEE dd MMM yyyy')}</p>
                              </div>
                            </div>
                          </div>

                          <div className="flight__detail__btn__wrapper">
                            <div
                              className={`flight__detail__btn ${activeDetailId === flight.flightOptionId ? 'flight__detail__btn--active' : ''}`}
                              onClick={() => handleDetailClick(flight.flightOptionId)}>
                              <Icon name="ui-chevron" className="flight__detail__btn__arrow" width={16} height={16} />
                            </div>
                          </div>
                        </div>

                        {/* DETAILS */}
                        <div className={`flight__detail ${activeDetailId === flight.flightOptionId ? 'flight__detail--active' : ''}`}>
                          {lines.map((line, index) => {
                            const nextLine = lines[index + 1];

                            return (
                              <React.Fragment key={index}>
                                {/* Flight line */}
                                <div className="flight__info">
                                  <div className="flight__info__times__wrapper">
                                    <div className="flight__info__times">
                                      <p>{line.departureTime}</p>
                                      <strong>{line.departureAirport}</strong>
                                      <p>{format(parseISO(line.departureDate), 'EEE dd MMM yyyy')}</p>
                                    </div>

                                    <Icon name="ui-plane-depart" width={30} height={20} />
                                  </div>

                                  <div className="flight__info__duration">
                                    <p>{formatDuration(line.durationInTicks)}</p>
                                    <span>
                                      {line.airline} {line.number}
                                    </span>
                                  </div>

                                  <div className="flight__info__times__wrapper flight__info__times__wrapper--arrival">
                                    <Icon name="ui-plane-arrive" width={30} height={20} />
                                    <div className="flight__info__times flight__info__times--arrival">
                                      <p>{line.arrivalTime}</p>
                                      <strong>{line.arrivalAirport}</strong>
                                      <p>{format(parseISO(line.arrivalDate), 'EEE dd MMM yyyy')}</p>
                                    </div>
                                  </div>
                                </div>

                                {nextLine && (
                                  <div className="flight__info">
                                    <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>{translations.SRP.STOP_TIME}</span>
                                        <strong>{formatDuration(parseISO(nextLine.departureDate).getTime() - parseISO(line.arrivalDate).getTime())}</strong>
                                      </div>
                                    </div>
                                  </div>
                                )}
                              </React.Fragment>
                            );
                          })}
                        </div>
                      </div>
                    </div>

                    <div className="flight__rate" />
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* <div className="search__results__options">
        <p>There are more transports at your disposal</p>
        <a href="#">More options</a>
      </div> */}
    </>
  );
};

export default FlightResults;
