import React, { FC, useEffect, useState } from 'react'
import {
  LeadTime,
  MetaData,
  PickupPoint as PickupPointData,
  PostenBringShippingOptions,
} from '../../posten-bring-checkout-block/model/models'
import { useSelect } from '@wordpress/data'
import bringLogo from '../../../../assets/img/Bring_logo.svg'
import postenLogo from '../../../../assets/img/Posten_logo.svg'

export declare interface SummaryProps {
  cart: Cart
  darkMode?: boolean
}

interface ShippingRate {
  rate_id: string
  selected: boolean
  meta_data: Array<MetaData>
}

export interface Cart {
  shippingRates: Array<WooShippingRate>
}

export interface WooShippingRate {
  shipping_rates: Array<ShippingRate>
}

const Summary: FC<SummaryProps> = ({ cart, darkMode }) => {
  const [summary, setSummary] = useState<string>()

  const selectedShippingRate = cart?.shippingRates[0]?.shipping_rates?.find(
    (it: ShippingRate) => it.selected
  ) as ShippingRate | undefined
  const selectedShippingOption = selectedShippingRate?.rate_id
  const metaData: Array<MetaData> = selectedShippingRate?.meta_data || []

  const brand = metaData.find(it => it.key === 'brand')?.value as string
  const serviceName = metaData.find(it => it.key === 'service_name')
    ?.value as string
  const pickupPoints = metaData.find(it => it.key === 'pickup_points')
    ?.value as Array<PickupPointData> | [] as PickupPointData[]
  const leadTime = metaData.find(it => it.key === 'lead_time')
    ?.value as LeadTime

  const extensionData = useSelect(select => {
    // @ts-expect-error 2339
    return select('wc/store/checkout').getExtensionData()?.[
      'posten-bring-checkout'
    ]
  }, [])

  useEffect(() => {
    if (
      extensionData?.selectedBringPickupPointId &&
      (selectedShippingOption === PostenBringShippingOptions.PIKCUP_POINT ||
        selectedShippingOption === PostenBringShippingOptions.PARCEL_LOCKER)
    ) {
      const pickupPoint = pickupPoints.find(
        it => it.id === extensionData?.selectedBringPickupPointId
      )

      setSummary(pickupPoint ? pickupPoint.displayName : serviceName)
    } else if (
      extensionData?.selectedBringDeliveryDate &&
      selectedShippingOption === PostenBringShippingOptions.HOME_DELIVERY
    ) {
      const alternateDeliveryDate = leadTime?.deliveryDateAlternatives?.find(
        it => it.deliveryDate === extensionData.selectedBringDeliveryDate
      )
      setSummary(
        alternateDeliveryDate
          ? `${alternateDeliveryDate.description} ${alternateDeliveryDate.deliveryDateFormatted}`
          : serviceName
      )
    } else if (
      selectedShippingOption &&
      [
        PostenBringShippingOptions.MAILBOX,
        PostenBringShippingOptions.GROUPAGE,
        PostenBringShippingOptions.PALLET,
        PostenBringShippingOptions.PARCEL_TO_BUSINESS,
        // @ts-expect-error 2345
      ].includes(selectedShippingOption)
    ) {
      setSummary(serviceName)
    } else {
      setSummary(undefined)
    }
  }, [
    extensionData,
    pickupPoints,
    selectedShippingOption,
    serviceName,
    leadTime?.deliveryDateAlternatives,
  ])

  const logo = brand === 'Bring' ? bringLogo : postenLogo

  return (
    summary && (
      <div
        id="posten-bring-checkout-summary"
        data-testid="summary"
        className={darkMode ? 'dark' : ''}
      >
        <div className="card mbs">
          <div className="flex flex-dir-row justify-csb align-ic gas">
            <div className="wc-block-components-totals-item__description">
              {summary}
            </div>
            <div>
              <img
                className="logo"
                src={logo}
                alt=""
                data-testid={`logo_${brand}`}
              />
            </div>
          </div>
        </div>
      </div>
    )
  )
}

export default Summary
