import {
  AirlineBookingPackageOption,
  AirportBookingPackageOption,
  BookingAirlineGroup,
  BookingAirportGroup,
  BookingOptionGroup,
  BookingOptionUnit,
  PerUnitPackageOption
} from '@qite/tide-client/build/types';
import React, { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { buildClassName } from '../../../shared/utils/class-util';
import { selectDepartureFlight, selectReturnFlight, selectTranslations } from '../booking/selectors';
import OptionBookingAirlineGroup from './option-booking-airline-group';
import OptionUnitGroup from './option-unit-group';

interface OptionUnitsCardProps {
  units: BookingOptionUnit[];
  parentIndex?: number;
  onUnitsChange?: (units: BookingOptionUnit[], index?: number) => void;
}

const OptionUnitsCard: React.FC<OptionUnitsCardProps> = ({ units, parentIndex, onUnitsChange }) => {
  const [toggleStates, setToggleStates] = useState<boolean[]>();
  const translations = useSelector(selectTranslations);
  const departureFlight = useSelector(selectDepartureFlight);
  const returnFlight = useSelector(selectReturnFlight);

  useEffect(() => {
    if (!toggleStates || toggleStates.length !== units.length) {
      setToggleStates(units.map(() => true));
    }
  }, [units, toggleStates, setToggleStates]);

  const getUnitPaxLabel = (unitIndex: number) => {
    return '';
  };

  const onGroupChange = (group: BookingOptionGroup<PerUnitPackageOption>, unitIndex: number) => {
    const updatedUnits = units.map((u) => {
      return u.index !== unitIndex
        ? u
        : {
            ...u,
            groups: u.groups.map((ug) => {
              return ug.name !== group.name ? ug : group;
            })
          };
    });

    if (onUnitsChange) onUnitsChange(updatedUnits, parentIndex);
  };

  const getAirlineGroups = (p: BookingOptionUnit) => {
    return p.airlineGroups.filter((x) => x.flightIds.includes(departureFlight?.entryLineGuid ?? '') || x.flightIds.includes(returnFlight?.entryLineGuid ?? ''));
  };

  const handleOnAirlineGroupChange = (group: BookingAirlineGroup<AirlineBookingPackageOption>, unitIndex: number) => {
    const updatedPax = units.map((u) => {
      return u.index !== unitIndex
        ? u
        : {
            ...u,
            airlineGroups: u.airlineGroups.map((g) => (g.label === group.label ? group : g))
          };
    });

    if (onUnitsChange) onUnitsChange(updatedPax, parentIndex);
  };

  const getAirportGroups = (p: BookingOptionUnit) => {
    return p.airportGroups.filter((x) => x.flightIds.includes(departureFlight?.entryLineGuid ?? '') || x.flightIds.includes(returnFlight?.entryLineGuid ?? ''));
  };

  const handleOnAirportGroupChange = (group: BookingAirportGroup<AirportBookingPackageOption>, unitIndex: number) => {
    const updatedPax = units.map((u) => {
      return u.index !== unitIndex
        ? u
        : {
            ...u,
            airportGroups: u.airportGroups.map((g) => (g.label === group.label ? group : g))
          };
    });

    if (onUnitsChange) onUnitsChange(updatedPax, parentIndex);
  };

  return (
    <>
      {units.map((u, i) => (
        <div className={buildClassName(['booking-card__group', toggleStates && toggleStates[i] && 'booking-card__group--active'])}>
          <div className="booking-card__group-header">
            <h3 className="booking-card__body-heading">
              {translations.OPTIONS_FORM.UNIT_TITLE} {u.index}
            </h3>
            <p>{getUnitPaxLabel(u.index)}</p>
            <div className="booking-card__actions">
              <button
                type="button"
                className="booking-card__toggle"
                onClick={() => {
                  setToggleStates(toggleStates?.map((s, si) => (si == i ? !s : s)));
                }}></button>
            </div>
          </div>
          {toggleStates && toggleStates[i] && (
            <>
              {u.groups.map(
                (ug) =>
                  ug && (
                    <OptionUnitGroup
                      key={ug.name}
                      unitIndex={u.index}
                      group={ug}
                      firstClassName={'booking-card__group-body'}
                      secondClassName={'booking-card__group-heading'}
                      parentId={`${u.index}_${ug.name}`}
                      onGroupChange={onGroupChange}
                    />
                  )
              )}
              {getAirlineGroups(u).map((group, i) => (
                <OptionBookingAirlineGroup
                  key={`${group.label}_${i}`}
                  airGroup={group}
                  onGroupChange={(updatedGroup) => {
                    handleOnAirlineGroupChange(updatedGroup, u.index);
                  }}
                />
              ))}
              {getAirportGroups(u).map((group, i) => (
                <OptionBookingAirlineGroup
                  key={`${group.label}_${i}`}
                  airGroup={group}
                  onGroupChange={(updatedGroup) => {
                    handleOnAirportGroupChange(updatedGroup, u.index);
                  }}
                />
              ))}
            </>
          )}
        </div>
      ))}
    </>
  );
};

export default OptionUnitsCard;
