import React, { useEffect, useState } from 'react'

import { SubProduct } from '@agiliza/api/domain'
import { formatCurrency } from '@agiliza/utils/formatters'
import { SelectField } from '@curio/components'
import { Button, Grid } from '@material-ui/core'
import { withStyles, WithStyles } from '@material-ui/core/styles'

import { connected, ConnectedProps } from './connect'
import GridLine from './GridLine'
import InstallmentsDialog from './InstallmentsDialog'
import styles from './styles'

type ExtendedProps = WithStyles<typeof styles> & ConnectedProps

interface Props extends ExtendedProps {
  subproduct?: SubProduct
  onChangeSubproduct: (subprd?: SubProduct) => void
}

const CreditLinesInfo = (props: Props) => {
  const { classes, subproducts, subproduct, onChangeSubproduct } = props

  // const [selectedSP, setSelectedSP] = useState<SubProduct | undefined>()
  const [open, setOpen] = useState(false)

  useEffect(() => {
    if (subproducts.length === 1) onChangeSubproduct(subproducts[0])
  }, [subproducts])

  return (
    <div className={classes.contentContainer}>
      <div className={classes.content}>
        <SelectField
          id="subproducts"
          className={classes.selectField}
          label="Opções de Subproduto"
          items={subproducts.map((sp) => ({ label: sp.description || '', value: sp.id }))}
          value={subproduct?.id || ''}
          onChange={(value) => {
            const subprd = subproducts.find((sp) => sp.id === value)
            onChangeSubproduct(subprd)
          }}
          shrink={false}
        />
        <Grid container className={classes.gridContainer}>
          <GridLine label="Número de parcelas" value={subproduct?.maxAmountInstallment || ''} />
          {/* <GridLine label="Valor das parcelas" value={formatCurrency(subproduct?.amount.toFixed(2))} /> */}
          <GridLine label="Taxa de juros" value={subproduct?.fee ? `${subproduct?.fee} %` : ''} />
          <GridLine label="Custo efetivo total (CET)" value={subproduct?.IOF !== undefined ? `${subproduct?.IOF} %` : ''} />
          <GridLine label="Taxa abertura crédito (TAC)" value={formatCurrency(subproduct?.TAC?.toFixed(2))} />
        </Grid>
        <Button variant="text" onClick={() => setOpen(true)} disabled={!subproduct}>
          Exibir opções de parcelamento
        </Button>
        <InstallmentsDialog open={open} onClose={() => setOpen(false)} installmentOptions={subproduct?.installementOptions} />
      </div>
    </div>
  )
}

export default connected(withStyles(styles)(CreditLinesInfo))
