import React, { useContext, useEffect, useState } from 'react';

import { BookingPackageFlight } from '@qite/tide-client/build/types';
import { isEmpty } from 'lodash';
import { useSelector } from 'react-redux';
import { buildClassName } from '../../../shared/utils/class-util';
import SettingsContext from '../../settings-context';
import { useAppDispatch } from '../../store';
import { FlightFilterOptions, GroupedFlights } from '../../types';
import { setCurrentStep, setFlights, setPackage } from '../booking/booking-slice';
import { OPTIONS_FORM_STEP, ROOM_OPTIONS_FORM_STEP, TRAVELERS_FORM_STEP } from '../booking/constants';
import {
  selectBookingQueryString,
  selectIsFetchingProductOptions,
  selectPackageDetails,
  selectPackageFlights,
  selectTranslations,
  selectTravelersFirstStep
} from '../booking/selectors';
import { fetchPriceDetails } from '../price-details/price-details-slice';
import FlightFilter from './flight-filter';
import FlightOption from './flight-option';
import FlightOptionModal from './flight-option-modal';
import { buildFilterOptions, buildGroupedFlights, filterGroupedFlights } from './flight-utils';
import { Link, useNavigate } from 'react-router-dom';

interface FlightOptionsFormProps {}

const FlightOptionsForm: React.FC<FlightOptionsFormProps> = () => {
  const settings = useContext(SettingsContext);
  const navigate = settings.skipRouter ? () => {} : useNavigate();

  const translations = useSelector(selectTranslations);
  const dispatch = useAppDispatch();
  const packageDetails = useSelector(selectPackageDetails);
  const bookingQueryString = useSelector(selectBookingQueryString);
  const isLoading = useSelector(selectIsFetchingProductOptions);
  const flights = useSelector(selectPackageFlights);
  const travelersFirstStep = useSelector(selectTravelersFirstStep);

  const [filterOptions, setFilterOptions] = useState<FlightFilterOptions | undefined>();
  const [flightGroups, setFlightGroups] = useState<GroupedFlights[]>([]);

  const handleSubmit: React.FormEventHandler<HTMLFormElement> = (e) => {
    if (settings.skipRouter) {
      if (settings.roomOptions.isHidden) {
        dispatch(setCurrentStep(OPTIONS_FORM_STEP));
      } else {
        dispatch(setCurrentStep(ROOM_OPTIONS_FORM_STEP));
      }
    } else {
      if (settings.roomOptions.isHidden) {
        navigate(`${!settings.skipBasePathInRouting ? settings.basePath : ''}${settings.options.pathSuffix}?${bookingQueryString}`);
      } else {
        navigate(`${!settings.skipBasePathInRouting ? settings.basePath : ''}${settings.roomOptions.pathSuffix}?${bookingQueryString}`);
      }
    }

    e.preventDefault();
  };

  const currentFlightPrice = (flights.outward?.find((x) => x.isSelected)?.price || 0) + (flights.return?.find((x) => x.isSelected)?.price || 0);

  useEffect(() => {
    if (packageDetails && settings.roomOptions.isHidden) {
      const params = new URLSearchParams(location.search);

      const outwardFlight = params.get('outwardflight') ?? undefined;
      const returnFlight = params.get('returnflight') ?? undefined;
      if (outwardFlight && returnFlight) {
        const desiredOutwardFlight = packageDetails.outwardFlights.find((x) => x.entryLineGuid == outwardFlight);
        const desiredReturnFlight = packageDetails.returnFlights.find((x) => x.entryLineGuid == returnFlight);
        if (desiredOutwardFlight && desiredReturnFlight) {
          dispatch(
            setPackage({
              ...packageDetails,
              outwardFlights: packageDetails.outwardFlights.map((flight) => {
                return {
                  ...flight,
                  isSelected: flight.entryLineGuid == desiredOutwardFlight.entryLineGuid ? true : false
                } as BookingPackageFlight;
              }),
              returnFlights: packageDetails.returnFlights.map((flight) => {
                return {
                  ...flight,
                  isSelected: flight.entryLineGuid == desiredReturnFlight.entryLineGuid ? true : false
                } as BookingPackageFlight;
              })
            })
          );
        }
      }
    }
    dispatch(fetchPriceDetails());

    const filters = buildFilterOptions(flights.outward, flights.return, translations);
    setFilterOptions(filters);
  }, []);

  useEffect(() => {
    const groups = buildGroupedFlights(flights.outward, flights.return);
    setFlightGroups(groups);
  }, [flights]);

  const filteredGroups = filterGroupedFlights(flightGroups, filterOptions);
  const resultCount = filteredGroups.length;

  const goPrevious = () => {
    dispatch(setCurrentStep(TRAVELERS_FORM_STEP));
  };

  return (
    <>
      <FlightOptionModal />
      <form className="form" name="booking--flights" id="booking--flights" noValidate onSubmit={handleSubmit}>
        <div className="form__booking--flight">
          {isLoading && settings.loaderComponent}
          {!isLoading && (
            <div className="form__group">
              <div className="booking-card">
                <div className="booking-card__body">
                  {filterOptions && <FlightFilter filterOptions={filterOptions} resultCount={resultCount} applyFilter={setFilterOptions} />}

                  <div className="booking-card__group">
                    <div className="flight outward__flights">
                      {isEmpty(filteredGroups) && <p>{translations.FLIGHTS_FORM.NO_FLIGHTS_FOUND}</p>}

                      {!isEmpty(filteredGroups) &&
                        filteredGroups.map((flight, index) => (
                          <FlightOption
                            key={index}
                            item={flight}
                            isSelected={flight.isSelected}
                            currentPrice={currentFlightPrice}
                            onChange={(item) => {
                              dispatch(setFlights(item));
                              dispatch(fetchPriceDetails());
                            }}
                          />
                        ))}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
        <div className="booking__navigator">
          {travelersFirstStep && settings.skipRouter ? (
            <button type="button" title={translations.STEPS.PREVIOUS} onClick={() => goPrevious()} className="cta cta--secondary">
              {translations.STEPS.PREVIOUS}
            </button>
          ) : travelersFirstStep ? (
            <Link
              to={`${!settings.skipBasePathInRouting ? settings.basePath : ''}${settings.travellers.pathSuffix}?${bookingQueryString}`}
              title={translations.STEPS.PREVIOUS}
              className="cta cta--secondary">
              {translations.STEPS.PREVIOUS}
            </Link>
          ) : null}
          <button type="submit" title={translations.STEPS.NEXT} disabled={isLoading} className={buildClassName(['cta', isLoading && 'cta--disabled'])}>
            {translations.STEPS.NEXT}
          </button>
        </div>
      </form>
    </>
  );
};

export default FlightOptionsForm;
