import React, { FC, useEffect, useState } from 'react'
import { OrderItem, Parcel, ServiceDetails } from '../model/models'
import { splitWeightIntoParcels } from './parcels'
import {
  __experimentalNumberControl as NumberControl,
  Button,
} from '@wordpress/components'
import { plus, trash } from '@wordpress/icons'
import { useI18n } from '@wordpress/react-i18n'
import { sprintf } from '@wordpress/i18n'

export declare interface PackageDetailsProps {
  selectedShippingOption?: string
  availableServices: Array<ServiceDetails>
  toCountry: string
  items: Array<OrderItem>
  totalWeightInGrams: number
  parcels: Array<Parcel>
  setParcels: (parcels: Array<Parcel>) => void
}

const PackageDetails: FC<PackageDetailsProps> = ({
  selectedShippingOption,
  availableServices,
  toCountry,
  items,
  totalWeightInGrams,
  parcels,
  setParcels,
}) => {
  const { __ } = useI18n()
  const [maxWeight, setMaxWeight] = useState<number>()
  const [packageLimits, setPackageLimits] = useState<string>()

  useEffect(() => {
    const shippingOption = availableServices?.find(
      value => value.service_id === selectedShippingOption
    )
    const maxWeightInGram =
      shippingOption && shippingOption.max_weight_in_kgs
        ? shippingOption.max_weight_in_kgs * 1000 - 100
        : undefined
    setMaxWeight(maxWeightInGram)

    if (shippingOption?.max_dimensions) {
      setPackageLimits(
        sprintf(
          // translators: 1: maximum weight in kilograms, 2: length in cm, 3: width in cm, 4: height in cm
          __(
            'Max parcel weight %1$s kg. Within %2$s x %3$s X %4$s cm.',
            'posten-bring-checkout'
          ),
          shippingOption.max_weight_in_kgs.toString(),
          shippingOption.max_dimensions.length.toString(),
          shippingOption.max_dimensions.width.toString(),
          shippingOption.max_dimensions.height.toString()
        )
      )
    } else if (shippingOption?.max_edges) {
      setPackageLimits(
        // translators: 1: maximum weight in kilograms, 2: longest edge in cm, 3: sum of edges in cm
        sprintf(
          __(
            'Max parcel weight %1$s kg. Max length %2$s cm. Length + width + height = max %3$s cm.',
            'posten-bring-checkout'
          ),
          shippingOption.max_weight_in_kgs.toString(),
          shippingOption.max_edges.max_longest_edge.toString(),
          shippingOption.max_edges.max_sum_of_edges.toString()
        )
      )
    } else if (shippingOption?.max_circumference) {
      setPackageLimits(
        sprintf(
          // translators: 1: maximum weight in kilograms, 2: longest edge in cm, 3: max circumference in cm
          __(
            'Max parcel weight %1$s kg. Max length %2$s cm. Max circumference + longest edge = max %3$s cm.',
            'posten-bring-checkout'
          ),
          shippingOption.max_weight_in_kgs.toString(),
          shippingOption.max_circumference.max_longest_side.toString(),
          shippingOption.max_circumference.max_circumference_plus_longest_side.toString()
        )
      )
    }
  }, [selectedShippingOption, availableServices, __])

  useEffect(() => {
    setParcels(splitWeightIntoParcels(totalWeightInGrams, maxWeight))
  }, [totalWeightInGrams, setParcels, maxWeight])

  const addParcel = () => {
    const updatedParcels = [...parcels]
    updatedParcels.push({ weightInGrams: 100 })
    setParcels(updatedParcels)
  }

  const updateParcelWeight = (index: number, weight: number) => {
    const updatedParcels = [...parcels]
    updatedParcels[index].weightInGrams = weight
    setParcels(updatedParcels)
  }

  const removeParcel = (index: number) => {
    if (index <= 0 || index >= parcels.length) return
    const updatedParcels = [...parcels]
    updatedParcels.splice(index, 1)
    setParcels(updatedParcels)
  }

  const canAddParcel =
    selectedShippingOption === '0340'
      ? toCountry !== 'Norway'
      : selectedShippingOption !== '3584'

  return (
    parcels.length > 0 && (
      <div className="mtl">
        <table id="bring-table" className="mts">
          <thead>
            <tr>
              <th scope="col">
                <div className="header-content-wrapper">
                  {__('Parcel', 'posten-bring-checkout')}
                </div>
              </th>
              <th scope="col">
                <div className="header-content-wrapper narrow">
                  {__('Weight', 'posten-bring-checkout')}
                </div>
              </th>
              {canAddParcel && (
                <th>
                  <Button icon={plus} onClick={addParcel}>
                    {__('Add parcel', 'posten-bring-checkout')}
                  </Button>
                </th>
              )}
            </tr>
          </thead>
          <tbody>
            {parcels.map((parcel, idx) => (
              <tr key={idx}>
                <td>
                  <div className="cell-content-wrapper wide">
                    {sprintf(
                      // translators: 1: parcel number, 2: total number of parcels
                      __('Parcel %1$s of %2$s', 'posten-bring-checkout'),
                      `${idx + 1}`,
                      `${parcels.length}`
                    )}
                  </div>
                </td>
                <td>
                  <div className="cell-content-wrapper narrow">
                    <NumberControl
                      type="number"
                      step={0.1}
                      min={0.1}
                      suffix="kg"
                      required={true}
                      value={(parcel.weightInGrams / 1000).toFixed(1)}
                      onChange={value =>
                        updateParcelWeight(idx, Number(value) * 1000)
                      }
					  __next40pxDefaultSize={true}
                    />
                  </div>
                </td>
                {canAddParcel && (
                  <td>
                    {idx > 0 && (
                      <Button
                        data-testid={`remove_${idx}`}
                        icon={trash}
                        onClick={() => removeParcel(idx)}
                      />
                    )}
                  </td>
                )}
              </tr>
            ))}
          </tbody>
          <tfoot>
            <tr>
              <td colSpan={canAddParcel ? 3 : 2}>{packageLimits}</td>
            </tr>
          </tfoot>
        </table>
      </div>
    )
  )
}

export default PackageDetails
