import React from 'react'

import { BDProductService, ProposalDataContext } from '@agiliza/api/domain'
import { DocumentTemplate } from '@agiliza/components/templates'
import { formatCurrency } from '@agiliza/utils/formatters'
import { ActionType } from '@agiliza/utils/hooks/state'
import { maskMonthYear } from '@agiliza/utils/masks'
import { getBase64FromFile } from '@agiliza/utils/method'
import { SelectField, SelectFieldProps } from '@curio/components'
import { TextField, TextFieldProps, Typography } from '@material-ui/core'
import { withStyles, WithStyles } from '@material-ui/core/styles'

import { BDStockSalesCostsState } from '../state'
import styles from './styles'

type ExtendedProps = WithStyles<typeof styles>

interface Props extends ExtendedProps {
  state: BDStockSalesCostsState
  actions: ActionType<BDStockSalesCostsState>
  context: ProposalDataContext
  productsServices: BDProductService[]
}

const Form = (props: Props) => {
  const { classes, state, actions, context, productsServices } = props

  const { monthYearReference, salesCommission, document, monthRating } = state

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

  const handleChangeImage: React.DetailedHTMLProps<React.InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>['onChange'] = async (evt) => {
    const file = evt.target.files && evt.target.files[0]
    if (file) {
      const b64: string = await getBase64FromFile(file)
      actions.update({ document: { url: b64 } })
    }
  }

  const handleChangeDocumentType = (value: string) => {
    const documentType = context.documentTypes.find((dT) => dT.id === value)
    if (documentType) actions.update({ document: { type: documentType } })
  }

  const handleChangeSelect =
    (key: keyof BDStockSalesCostsState): SelectFieldProps['onChange'] =>
    (vl) => {
      actions.update({ [key]: vl })
    }

  const getTotals = (key: keyof Pick<BDProductService, 'monthlySales' | 'stock' | 'variableCosts'>) => {
    let total = 0
    productsServices?.forEach((pS) => (total += Number(pS[key].amount) * Number(pS[key].price)))
    return total
  }

  const getTotalCommission = (comm: string) => {
    return (getTotals('monthlySales') * Number(comm)) / 100
  }

  return (
    <form className={classes.form}>
      <DocumentTemplate context={context} document={document} onChangeImage={handleChangeImage} onChangeDocumentType={handleChangeDocumentType} />
      {/* <Typography className={classes.label}>
        Preencha as informações abaixo, e na tela seguinte informe os produtos/serviços e os respectivos dados referente a estoque, vendas mensais e
        custos variáveis.
      </Typography> */}
      <TextField
        variant="outlined"
        label="Mês/Ano referência"
        value={maskMonthYear(monthYearReference)}
        onChange={handleChangeText('monthYearReference')}
        inputProps={{ maxLength: 7 }}
        type="tel"
      />
      <TextField variant="outlined" label="Comissão vendas (%)" value={salesCommission} onChange={handleChangeText('salesCommission')} />
      <SelectField
        id="month-rating-select-field"
        label="Classificação do mês"
        value={monthRating}
        onChange={handleChangeSelect('monthRating')}
        items={context.monthRatings.map((mR) => ({ label: mR.description, value: mR.id }))}
        variant="outlined"
        shrink={false}
      />
      <Typography className={classes.label}>
        Após o preenchimento das informações citadas acima, os totais abaixo serão preenchidos automaticamente.
      </Typography>
      <TextField variant="outlined" disabled label="Total geral estoque" value={formatCurrency(getTotals('stock').toFixed(2)) || ''} />
      <TextField variant="outlined" disabled label="Total geral vendas" value={formatCurrency(getTotals('monthlySales').toFixed(2)) || ''} />
      <TextField
        variant="outlined"
        disabled
        label="Total geral vendas"
        value={formatCurrency(getTotalCommission(salesCommission).toFixed(2)) || ''}
      />
      <TextField variant="outlined" disabled label="Total geral custos var." value={formatCurrency(getTotals('variableCosts').toFixed(2)) || ''} />
    </form>
  )
}

export default withStyles(styles)(Form)
