import React, { useContext, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
  resetFlightFilters,
  setFlightFilters,
  setFlightSortType,
  setFlyInIsOpen,
  setFlyInType,
  setSelectedOutwardKey,
  setSelectedReturnKey
} from '../../../search-results/store/search-results-slice';
import { SearchResultsRootState } from '../../../search-results/store/search-results-store';
import Spinner from '../../../search-results/components/spinner/spinner';
import SearchResultsConfigurationContext from '../../../search-results/search-results-configuration-context';
import { findSortByType, getSortingName, getTranslations } from '../../utils/localization-util';
import { getFlightKey } from '../../../search-results/utils/flight-utils';
import {
  selectSelectedOutward,
  selectSelectedReturn,
  selectUniqueOutwardFlights,
  selectUniqueReturnFlights
} from '../../../search-results/store/search-results-selectors';
import IndependentFlightOption from '../../../search-results/components/flight/flight-selection/independent-flight-option';
import Filters from '../../../search-results/components/filters/filters';
import { SortByType } from '../../../search-results/types';
import ItemPicker from '../../../search-results/components/item-picker';
import Icon from '../icon';

type FlightsFlyInProps = {
  isOpen: boolean;
  setIsOpen: (open: boolean) => void;
  toggleFilters?: () => void;
  filtersOpen: boolean;
};

const PackageingFlightsFlyIn: React.FC<FlightsFlyInProps> = ({ isOpen, setIsOpen, toggleFilters, filtersOpen }) => {
  const context = useContext(SearchResultsConfigurationContext);
  const language = context?.languageCode ?? 'en-GB';
  const translations = getTranslations(language);

  const dispatch = useDispatch();
  const { flightsLoading, initialFlightFilters, flightFilters, flyInType, selectedFlightSortType } = useSelector(
    (state: SearchResultsRootState) => state.searchResults
  );
  const uniqueOutwardFlights = useSelector(selectUniqueOutwardFlights);
  const uniqueReturnFlights = useSelector(selectUniqueReturnFlights);
  const selectedOutward = useSelector(selectSelectedOutward);
  const selectedReturn = useSelector(selectSelectedReturn);

  const [outwardStepComplete, setOutwardStepComplete] = useState<boolean>(false);

  const handleConfirm = (): void => {
    if (!outwardStepComplete) {
      setOutwardStepComplete(true);
      dispatch(setFlyInType('flight-return-results'));
      return;
    } else {
      dispatch(setFlyInType(null));
      setOutwardStepComplete(false);
      dispatch(setFlyInIsOpen(false));
    }
  };

  const sortByTypes = [
    { direction: 'asc', label: 'default' } as SortByType,
    { direction: 'asc', label: 'price' } as SortByType,
    { direction: 'desc', label: 'price' } as SortByType,
    { direction: 'asc', label: 'departureTime' } as SortByType,
    { direction: 'desc', label: 'departureTime' } as SortByType,
    { direction: 'asc', label: 'durationInTicks' } as SortByType,
    { direction: 'desc', label: 'durationInTicks' } as SortByType
  ];

  const handleSortChange = (newSortKey: string, direction?: string) => {
    if (sortByTypes === undefined) return;
    const newSortByType = findSortByType(sortByTypes, newSortKey, direction ?? 'asc');
    if (newSortByType) {
      dispatch(setFlightSortType(newSortByType));
    }
  };

  return (
    <>
      <div className="flyin__content flyin__content--columns">
        {flightsLoading ? (
          <Spinner label={translations.SRP.LOADING_FLIGHTS} />
        ) : (
          <>
            <Filters
              initialFilters={initialFlightFilters}
              filters={flightFilters}
              isOpen={filtersOpen}
              handleSetIsOpen={() => toggleFilters && toggleFilters()}
              // handleApplyFilters={() => setSearchTrigger((prev) => prev + 1)}
              isLoading={flightsLoading}
              setFilters={(filters) => dispatch(setFlightFilters(filters))}
              resetFilters={(filters) => dispatch(resetFlightFilters(filters))}
            />
            <div className="search__results__wrapper">
              <div className="search__result-row">
                <span className="search__result-row-text">
                  {uniqueOutwardFlights?.length && uniqueOutwardFlights.length}
                  &nbsp;{translations.FLIGHTS_FORM.FLIGHTS_FOUND_2}&nbsp;{translations.FLIGHTS_FORM.FLIGHTS_FOUND_3}
                </span>
                <div className="cta cta--filter" onClick={() => toggleFilters && toggleFilters()}>
                  <Icon name="ui-filter" className="mobile-filters-button__icon" height={16} />
                  {translations.SRP.FILTERS}
                </div>
                {sortByTypes && sortByTypes.length > 0 && (
                  <div className="search__result-row-filter">
                    <ItemPicker
                      items={sortByTypes}
                      selection={selectedFlightSortType?.label || undefined}
                      selectedSortByType={selectedFlightSortType || undefined}
                      label={translations.SRP.SORTBY}
                      placeholder={translations.SRP.SORTBY}
                      classModifier=""
                      valueFormatter={(value, direction) => getSortingName(translations, findSortByType(sortByTypes, value, direction ?? 'asc'))}
                      // onPick={handleSortChange}
                      onPick={(newSortKey, direction) => handleSortChange(newSortKey, direction)}
                    />
                  </div>
                )}
              </div>
              <div className="search__results__cards search__results__cards--extended">
                {flyInType == 'flight-outward-results' &&
                  uniqueOutwardFlights.map((result) => (
                    <IndependentFlightOption
                      key={`flight-${result.outwardGuid}`}
                      item={result.outward}
                      onSelect={() => dispatch(setSelectedOutwardKey(getFlightKey(result.outward.segments)))}
                      guid={result.outwardGuid}
                      isOutward={true}
                      price={result.price}
                      currentSelectedPrice={selectedOutward?.price}
                      selectedGuid={selectedOutward?.outwardGuid}
                      showSelectedState={true}
                    />
                  ))}
                {flyInType == 'flight-return-results' &&
                  uniqueReturnFlights.map((result) => (
                    <IndependentFlightOption
                      key={`flight-${result.outwardGuid}`}
                      item={result.return}
                      onSelect={() => dispatch(setSelectedReturnKey(getFlightKey(result.return.segments)))}
                      guid={result.outwardGuid}
                      isOutward={false}
                      price={result.price}
                      currentSelectedPrice={selectedReturn?.price}
                      selectedGuid={selectedReturn?.outwardGuid}
                      showSelectedState={true}
                    />
                  ))}
              </div>
            </div>
          </>
        )}
      </div>
      <div className="flyin__footer">
        <div className="flyin__footer__price"></div>
        <div className="flyin__button-wrapper">
          <button className="cta cta--select" onClick={() => handleConfirm()}>
            {translations.QSM.CONFIRM}
          </button>
        </div>
      </div>
    </>
  );
};

export default PackageingFlightsFlyIn;
