'use client'

import type { Product, Variant } from '@/payload-types'

import { Price } from '@/components/Price'
import {
  getDocumentPrice,
  getHighestProductPrice,
  getLowestProductPrice,
} from '@/utilities/pricing'
import { useCurrency } from '@payloadcms/plugin-ecommerce/client/react'
import React from 'react'

type Props = {
  as?: 'span' | 'p'
  className?: string
  currencyCode?: string
  currencyCodeClassName?: string
  mode?: 'lowest' | 'range'
  product: Partial<Product>
  quantity?: number
  variant?: Partial<Variant> | null
}

export const ProductPrice: React.FC<Props> = ({
  as,
  className,
  currencyCode: currencyCodeFromProps,
  currencyCodeClassName,
  mode = 'lowest',
  product,
  quantity = 1,
  variant,
}) => {
  const { currency } = useCurrency()
  const currencyCode = currencyCodeFromProps || currency.code

  if (variant) {
    const variantPrice = getDocumentPrice(variant, currencyCode)
    const productPrice = getDocumentPrice(product, currencyCode)
    const price = variantPrice ?? productPrice

    return typeof price === 'number' ? (
      <Price
        amount={price * quantity}
        as={as}
        className={className}
        currencyCode={currencyCode}
        currencyCodeClassName={currencyCodeClassName}
      />
    ) : null
  }

  if (mode === 'range') {
    const lowestAmount = getLowestProductPrice(product, currencyCode)
    const highestAmount = getHighestProductPrice(product, currencyCode)

    if (lowestAmount === null || highestAmount === null) {
      return null
    }

    return (
      <Price
        as={as}
        className={className}
        currencyCode={currencyCode}
        currencyCodeClassName={currencyCodeClassName}
        highestAmount={highestAmount * quantity}
        lowestAmount={lowestAmount * quantity}
      />
    )
  }

  const price = getLowestProductPrice(product, currencyCode)

  return typeof price === 'number' ? (
    <Price
      amount={price * quantity}
      as={as}
      className={className}
      currencyCode={currencyCode}
      currencyCodeClassName={currencyCodeClassName}
    />
  ) : null
}
