'use client'

import { useGDS } from '../hooks/index.ts'
import { cn } from '../utils/index.ts'
import { Field } from './base/Field.tsx'
import { Button } from './Button.tsx'
import { Input, type InputProps } from './Input.tsx'

export interface CurrencyInputProps extends Omit<InputProps, 'render' | 'type' | 'unit'> {
  /** @default 'GRT' */
  currency?: string | undefined
  convertedAmount?: string | undefined
  /** @default 'USD' */
  convertedCurrency?: string | undefined
  onMaxClicked?: (() => void) | undefined
}

export function CurrencyInput({
  currency = 'GRT',
  convertedAmount,
  convertedCurrency = 'USD',
  onMaxClicked,
  className,
  ...props
}: CurrencyInputProps) {
  useGDS()

  return (
    <Input
      type="number"
      unit={currency}
      action={
        onMaxClicked ? (
          <Button disabled={props.disabled || props.readOnly} onClick={onMaxClicked}>
            Max
          </Button>
        ) : null
      }
      className={cn('gds-currency-input', className)}
      {...props}
      renderInput={(renderProps, { inputWithUnitAndAction }) => (
        <Field.Box {...renderProps}>
          {inputWithUnitAndAction}
          {convertedAmount ? (
            <div
              className={`
                flex items-center pb-px text-caption transition
                @state-blank/field:@state-not-disabled/field:text-form-placeholder
                @prop-size-small/field:h-7
                @prop-size-small/field:px-2
                @prop-size-small/field:text-10
                @prop-size-medium/field:h-8
                @prop-size-medium/field:px-3
                @prop-size-medium/field:text-12
                @prop-size-large/field:h-8
                @prop-size-large/field:px-3
                @prop-size-large/field:text-12
              `}
            >
              <div
                className={`
                  absolute inset-x-px -top-px border-t border-form-idle transition
                  @state-not-enabled/field:border-form-disabled
                `}
              />
              {/* `w-0` is used to prevent the dynamic content from affecting the intrinsic width of the component */}
              <div className="w-0 flex-1 truncate">{`= ${convertedAmount} ${convertedCurrency}`}</div>
            </div>
          ) : null}
        </Field.Box>
      )}
    />
  )
}
