import React from 'react';
import { compact, groupBy, isEmpty } from 'lodash';
import { getDateText } from '../../booking-wizard/features/sidebar/sidebar-util';

export const renderEditablePackagingEntrySummaryOptions = (editablePackagingEntry: any, priceDetails: any, translations: any) => {
  const priceDetailsByProduct = groupBy(priceDetails?.details ?? [], (detail: any) => `${detail.productCode}|${detail.accommodationCode}`);

  return (editablePackagingEntry?.lines ?? []).map((line: any) => {
    const groupedPriceDetails = priceDetailsByProduct[`${line.productCode}|${line.accommodationCode}`] ?? [];
    const visiblePriceDetails = groupedPriceDetails.filter((detail: any) => detail.showPrice || detail.isSeparate);

    return (
      <li key={line.guid}>
        <h6>{line.productName}</h6>
        <ul>
          <li className="list__item">{compact([line.accommodationName, line.regimeName]).join(', ')}</li>

          {line.flightInformation?.flightLines?.map((flightLine: any, index: number) => (
            <li className="list__item" key={`${line.guid}-${index}`}>
              {flightLine.departureAirportCode} {flightLine.departureTime?.slice(0, 5)} &gt; {flightLine.arrivalAirportCode}{' '}
              {flightLine.arrivalTime?.slice(0, 5)} ({flightLine.operatingFlightNumber || `${flightLine.airlineCode}${flightLine.flightNumber}`})
            </li>
          ))}

          {!isEmpty(visiblePriceDetails) &&
            visiblePriceDetails.map((detail: any, index: number) => (
              <li className="list__item" key={`${line.guid}-price-${index}`}>
                {detail.priceDescription}: {detail.total?.toLocaleString(undefined, { style: 'currency', currency: 'EUR' })}
              </li>
            ))}
        </ul>
        <p>
          (
          {line.from === line.to ? (
            getDateText(line.from)
          ) : (
            <>
              {getDateText(line.from)} &gt; {getDateText(line.to)}
            </>
          )}
          )
        </p>
      </li>
    );
  });
};

export const getImageSrcFromHtml = (html?: string | null): string | undefined => {
  if (!html || typeof window === 'undefined') {
    return undefined;
  }

  const doc = new DOMParser().parseFromString(html, 'text/html');
  const img = doc.querySelector('img');

  return img?.getAttribute('src') ?? undefined;
};
