import React, { useContext, useEffect, useState } from 'react';
import Spinner from '../spinner/spinner';
import { useDispatch, useSelector } from 'react-redux';
import { SearchResultsRootState } from '../../store/search-results-store';
import { getTranslations } from '../../../shared/utils/localization-util';
import SearchResultsConfigurationContext from '../../search-results-configuration-context';
import {
  PackagingAccommodationRequest,
  PackagingAccommodationResponse,
  PackagingDestination,
  searchPackagingExcursions,
  TideClientConfig
} from '@qite/tide-client';
import { EXCURSION_SERVICE_TYPE } from '../../utils/query-utils';
import { SearchSeed } from '../../types';
import he from 'he';
import { setFlyInType, setSelectedExcursionSearchResult } from '../../store/search-results-slice';

interface ExcursionResultsProps {
  isFlyIn?: boolean;
  activeSearchSeed?: SearchSeed | null;
}

const ExcursionResults: React.FC<ExcursionResultsProps> = ({ isFlyIn, activeSearchSeed }) => {
  const context = useContext(SearchResultsConfigurationContext);
  const dispatch = useDispatch();
  const [isLoading, setIsLoading] = useState(false);
  const [excursions, setExcursions] = useState<PackagingAccommodationResponse[] | null>(null);

  const { flyInIsOpen, flyInType, excursionSearchParams, transactionId } = useSelector((state: SearchResultsRootState) => state.searchResults);

  useEffect(() => {
    if (!context || !activeSearchSeed || !excursionSearchParams) return;

    (async () => {
      try {
        setIsLoading(true);
        console.log('Excursion search params changed, fetching excursions...', excursionSearchParams);

        const config: TideClientConfig = {
          host: context.tideConnection.host,
          apiKey: context.tideConnection.apiKey
        };

        const destination = excursionSearchParams.locationId
          ? { id: Number(excursionSearchParams.locationId), type: 'location' }
          : excursionSearchParams.oordId
          ? { id: Number(excursionSearchParams.oordId), type: 'oord' }
          : excursionSearchParams.regionId
          ? { id: Number(excursionSearchParams.regionId), type: 'region' }
          : excursionSearchParams.countryId
          ? { id: Number(excursionSearchParams.countryId), type: 'country' }
          : { id: 0, type: null };

        const allPax = activeSearchSeed.rooms.flatMap((room) => room.pax);

        const searchRequest: PackagingAccommodationRequest = {
          transactionId: transactionId ?? '',
          officeId: context.tideConnection.officeId ?? 1,
          agentId: context.agentId ?? null,
          portalId: context.portalId ?? null,
          catalogueId: context.searchConfiguration.defaultCatalogueId ?? 0,
          searchConfigurationId: context.searchConfiguration.id,
          language: context.languageCode ?? 'en-GB',
          serviceType: EXCURSION_SERVICE_TYPE,
          fromDate: excursionSearchParams.fromDate,
          toDate: excursionSearchParams.toDate,
          destination: {
            id: destination.id,
            isCountry: destination.type === 'country',
            isRegion: destination.type === 'region',
            isOord: destination.type === 'oord',
            isLocation: destination.type === 'location',
            isAirport: false,
            code: ''
          } as PackagingDestination,
          productCode: '',
          // rooms: activeSearchSeed.rooms.map((room) => ({
          //   travellers: room.pax.map((pax) => ({
          //     id: pax.id,
          //     age: pax.age,
          //     dateOfBirth: pax.dateOfBirth
          //   }))
          // })),
          rooms: [
            {
              travellers: allPax.map((pax) => ({
                id: pax.id,
                age: pax.age,
                dateOfBirth: pax.dateOfBirth
              }))
            }
          ],
          tagIds: []
        };

        const packageExcursionSearchResults = await searchPackagingExcursions(config, searchRequest);
        console.log('Excursion search results', packageExcursionSearchResults);
        setExcursions(packageExcursionSearchResults);
      } catch (err) {
        console.error('Excursion search failed', err);
      } finally {
        setIsLoading(false);
      }
    })();
  }, [context, activeSearchSeed, excursionSearchParams, transactionId]);

  if (!context || !activeSearchSeed) {
    return null;
  }

  if (!flyInIsOpen || flyInType !== 'excursion-results') {
    return null;
  }

  const translations = getTranslations(context.languageCode ?? 'en-GB');

  const handleChange = (excursion: PackagingAccommodationResponse): void => {
    console.log('Selected excursion', excursion);
    dispatch(setFlyInType('excursion-details'));
    dispatch(setSelectedExcursionSearchResult(excursion));
  };

  return isLoading ? (
    <Spinner label={translations.SRP.LOADING_EXCURSIONS} />
  ) : (
    <div className="flyin__content flyin__content--columns">
      {/* <Filters
                initialFilters={initialFilters}
                filters={filters}
                isOpen={false}
                handleSetIsOpen={() => { }}
                // handleApplyFilters={() => setSearchTrigger((prev) => prev + 1)}
                isLoading={isLoading}
                setFilters={(filters) => dispatch(setFilters(filters))}
                resetFilters={(filters) => dispatch(resetFilters(filters))}
              /> */}
      <div className="search__results__wrapper">
        <div className="search__result-row">
          <span className="search__result-row-text">
            {!isLoading && (
              <>
                {excursions?.length && excursions.length}
                &nbsp;{translations.SRP.TOTAL_RESULTS_LABEL}
              </>
            )}
          </span>
          {/* {sortByTypes && sortByTypes.length > 0 && (
                    <div className="search__result-row-filter">
                      <ItemPicker
                        items={sortByTypes}
                        selection={selectedSortType?.label || undefined}
                        selectedSortByType={selectedSortType}
                        label={translations.SRP.SORTBY}
                        placeholder={translations.SRP.SORTBY}
                        classModifier="travel-class-picker__items"
                        valueFormatter={(value, direction) => getSortingName(translations, findSortByType(sortByTypes, value, direction ?? 'asc'))}
                        onPick={(newSortKey, direction) => handleSortChange(newSortKey, direction)}
                      />
                    </div>
                  )} */}
        </div>
        <div className="search__results__cards search__results__cards--compact">
          {excursions &&
            excursions.length > 0 &&
            excursions.map((excursion) => (
              <div
                key={excursion.code}
                className="search__result-card__wrapper search__result-card__wrapper--custom"
                onMouseEnter={(e) => (e.currentTarget.style.transform = 'scale(1.02)')}
                onMouseLeave={(e) => (e.currentTarget.style.transform = 'scale(1)')}>
                {excursion.contents ? <div dangerouslySetInnerHTML={{ __html: he.decode(excursion.contents) }}></div> : 'no contents'}
                <div className="search__result-card__footer">
                  <button type="button" className="cta cta--select" onClick={() => handleChange(excursion)}>
                    {translations?.SHARED.SELECT}
                  </button>
                </div>
              </div>
            ))}
        </div>
      </div>
    </div>
  );
};

export default ExcursionResults;
