import React from 'react'

import { extractNumbers } from '@agiliza/utils/extractors'
import { formatCurrency } from '@agiliza/utils/formatters'
import { TextField, TextFieldProps } from '@material-ui/core'

const getTotalPrice = <T extends { price: string; amount: string }>(pva: T) => {
  const { amount, price } = pva
  return price && amount ? (Number(extractNumbers(price)) * Number(amount)).toString() : ''
}

type ExtendedProps = Record<string, unknown>

export interface Values {
  price: string
  amount: string
}

interface Props extends ExtendedProps {
  values: Values
  onChange: (value: Partial<Values>) => void
}

const PriceAmountInput = (props: Props) => {
  const { values, onChange } = props
  const { price, amount } = values

  const handleChangeText =
    (key: keyof Values): TextFieldProps['onChange'] =>
    (evt) => {
      onChange({ [key]: evt.target.value })
    }

  return (
    <>
      <TextField variant="outlined" label="Preço unitário" value={formatCurrency(price)} onChange={handleChangeText('price')} />
      <TextField variant="outlined" label="Quantidade" value={amount} onChange={handleChangeText('amount')} />
      <TextField disabled variant="outlined" label="Valor total" value={formatCurrency(getTotalPrice(values))} />
    </>
  )
}

export default PriceAmountInput
