import React, { useEffect, useState } from 'react'
import { RouteComponentProps, useHistory } from 'react-router'

import { destinations } from '@agiliza/__mocks__/creditLines'
import { SimulationCategory } from '@agiliza/api/domain'
import { extractCurrency, extractNumbers } from '@agiliza/utils/extractors'
import { formatCurrency } from '@agiliza/utils/formatters'
import { SelectField } from '@curio/components'
import {
  Button,
  CircularProgress,
  IconButton,
  InputAdornment,
  TextareaAutosize,
  TextField,
  Typography
} from '@material-ui/core'
import { withStyles, WithStyles } from '@material-ui/core/styles'
import { Refresh as RefreshIcon } from '@material-ui/icons'
import { Autocomplete } from '@material-ui/lab'

import { CREDIT_LINES_PATHS, SimulationRouteState } from '../router'
import { connected, ConnectedProps } from './connect'
import SliderField from './SliderField'
import styles from './styles'

type ExtendedProps = WithStyles<typeof styles> & RouteComponentProps & ConnectedProps

interface Props extends ExtendedProps {
  fetching: boolean
}

const CreditLinesList = (props: Props) => {
  const { classes, fetching, simulationCategories } = props

  useEffect(() => {
    props.fetchSimulationCategories()
  }, [])

  const history = useHistory<SimulationRouteState>()

  const [selectedSimulCategory, setSelectedSimulCategory] = useState<SimulationCategory | null>(null)
  const [amount, setAmount] = useState('0')
  const [paymentMonths, setPaymentMonths] = useState(0)
  const [graceMonths, setGraceMonths] = useState(0)
  const [destination, setDestination] = useState('')

  // const parentPath = match.path.substring(0, match.path.lastIndexOf('/'))
  const handleSimulate = () => {
    if (selectedSimulCategory)
      props.getSubproducts({
        categoryId: selectedSimulCategory.id,
        creditValue: Number(amount),
        gracePeriodId: graceMonths.toString(),
        installmentsNumber: paymentMonths,
        onSuccess: (subPdcs) => {
          if (subPdcs && subPdcs.length > 0) {
            props.setData({ simulationCategoryId: selectedSimulCategory.id, amount, paymentMonths, graceMonths })
            history.push({ pathname: CREDIT_LINES_PATHS.simulation, state: { hasSubproducts: true } })
          } else props.setErrorMessage('Nenhum subproduto encontrado. Tente novamente com outros valores...')
        },
      })
  }

  return (
    <div className={classes.pageContent}>
      <div className={classes.contentContainer}>
        <div className={classes.content}>
          <Typography variant="h5" className={classes.title}>
            Escolha a melhor opção para sua empresa e clique em simular!
          </Typography>
          <Autocomplete<SimulationCategory>
            id="credit-lines"
            className={classes.creditLinesAutocomplete}
            options={simulationCategories}
            getOptionLabel={(option) => option.description}
            getOptionSelected={(opt, val) => opt.id === selectedSimulCategory?.id}
            noOptionsText="Nenhum motivo encontrado..."
            value={selectedSimulCategory}
            onChange={(_, opt) => {
              setSelectedSimulCategory(opt || null)

              // setAmount(opt?.amount.min.toString() || '0')
              setPaymentMonths(opt?.maxInstallment || 0)
              setGraceMonths(opt?.maxGraceMonths || 0)
            }}
            renderInput={(params) => {
              const isValid = React.isValidElement(params.InputProps.endAdornment)
              const fetchingEndAdornment = (
                <InputAdornment position="end" style={{ flex: '1', display: 'flex', justifyContent: 'flex-end' }}>
                  <IconButton>
                    <CircularProgress size={20} />
                  </IconButton>
                </InputAdornment>
              )
              const validEndAdornment = React.cloneElement(params.InputProps.endAdornment as React.ReactElement, {
                style: { marginRight: '1rem' },
              })
              const refreshEndAdorment = (
                <InputAdornment position="end" style={{ flex: '1', display: 'flex', justifyContent: 'flex-end' }}>
                  <IconButton onClick={() => props.fetchSimulationCategories()}>
                    <RefreshIcon />
                  </IconButton>
                </InputAdornment>
              )
              return (
                <TextField
                  {...params}
                  id="select-patient-id"
                  label="Qual o motivo do financiamento?"
                  variant="outlined"
                  InputProps={{
                    ref: params.InputProps.ref,
                    endAdornment: fetching
                      ? fetchingEndAdornment
                      : !simulationCategories.length
                      ? refreshEndAdorment
                      : isValid
                      ? validEndAdornment
                      : params.InputProps.endAdornment,
                  }}
                />
              )
            }}
          />
          <TextField
            className={classes.description}
            label="Descrição"
            value={selectedSimulCategory?.fullDescription || ''}
            rows={5}
            multiline
            contentEditable={false}
            InputLabelProps={{
              shrink: true,
            }}
            InputProps={{ readOnly: true, inputProps: { component: TextareaAutosize } }}
            variant="outlined"
            unselectable="on"
          />
          <SelectField
            id="destination-select"
            variant="outlined"
            label="Qual a destinação do capital?"
            value={destination}
            onChange={(vl) => setDestination(vl)}
            items={destinations.map((st) => ({ label: st.description, value: st.id }))}
            shrink={false}
            className={classes.destinationsSelect}
          />
          <SliderField
            className={classes.sliderField}
            title="De quanto você precisa?"
            // sliderProps={{
            //   min: 0,
            //   max: 5000,
            //   marks: selectedSimulCategory
            //     ? [
            //         { value: 0, label: formatCurrency('0') },
            //         { value: 99999, label: formatCurrency('99999') },
            //         // { value: selectedSimulCategory.amount.min, label: formatCurrency(selectedSimulCategory.amount.min.toString()) },
            //         // { value: selectedSimulCategory.amount.max, label: formatCurrency(selectedSimulCategory.amount.max.toString()) },
            //       ]
            //     : [
            //         { value: 0, label: formatCurrency('0') },
            //         { value: 5000, label: '' },
            //       ],
            //   value: Number(amount),
            //   step: 0.01,
            //   onChange: (_, value) => setAmount((value as number).toString()),
            // }}
            valueField={formatCurrency(amount.toString(), true)}
            disabled={!selectedSimulCategory}
            onChangeField={(evt) => setAmount(extractCurrency(evt.target.value))}
            onBlurField={(evt) => {
              // const amountValue = extractCurrency(evt.target.value)
              // if (selectedSimulCategory)
              //   setAmount(Number(amountValue) <= selectedSimulCategory.amount.max ? amountValue : selectedSimulCategory.amount.max.toString())
            }}
          />
          <SliderField
            className={classes.sliderField}
            title="Quantos meses para pagar?"
            sliderProps={{
              min: 0,
              max: selectedSimulCategory?.maxInstallment || 12,
              marks: selectedSimulCategory
                ? [
                    { value: 0, label: `${0} meses` },
                    { value: selectedSimulCategory?.maxInstallment, label: `${selectedSimulCategory?.maxInstallment} meses` },
                  ]
                : [
                    { value: 0, label: '0 meses' },
                    { value: 12, label: '' },
                  ],
              value: Number(paymentMonths),
              onChange: (_, value) => setPaymentMonths(value as number),
            }}
            valueField={paymentMonths.toString()}
            suffix={`m${paymentMonths > 1 ? 'e' : 'ê'}s${paymentMonths > 1 ? 'es' : ''}`}
            disabled={!selectedSimulCategory}
            onChangeField={(evt) => setPaymentMonths(Number(extractNumbers(evt.target.value)))}
            onBlurField={(evt) => {
              const paymentMonthsValue = Number(extractNumbers(evt.target.value))
              if (selectedSimulCategory)
                setPaymentMonths(
                  paymentMonthsValue <= selectedSimulCategory.maxInstallment ? paymentMonthsValue : selectedSimulCategory.maxInstallment
                )
            }}
          />
          <SliderField
            className={classes.sliderField}
            title="Quantos meses de carência?"
            sliderProps={{
              min: 0,
              max: selectedSimulCategory?.maxGraceMonths || 12,
              marks: selectedSimulCategory
                ? [
                    { value: 0, label: `${0} meses` },
                    { value: selectedSimulCategory?.maxGraceMonths, label: `${selectedSimulCategory?.maxGraceMonths} meses` },
                  ]
                : [
                    { value: 0, label: '0 meses' },
                    { value: 12, label: '' },
                  ],
              value: Number(graceMonths),
              onChange: (_, value) => setGraceMonths(value as number),
            }}
            valueField={graceMonths.toString()}
            suffix={`m${paymentMonths > 1 ? 'e' : 'ê'}s${paymentMonths > 1 ? 'es' : ''}`}
            disabled={!selectedSimulCategory}
            onChangeField={(evt) => setGraceMonths(Number(extractNumbers(evt.target.value)))}
            onBlurField={(evt) => {
              const graceMonthsValue = Number(extractNumbers(evt.target.value))
              if (selectedSimulCategory)
                setGraceMonths(graceMonthsValue <= selectedSimulCategory.maxGraceMonths ? graceMonthsValue : selectedSimulCategory.maxGraceMonths)
            }}
          />
          <div className={classes.btnContainer}>
            <Button disabled={!selectedSimulCategory} variant="contained" color="secondary" onClick={handleSimulate}>
              Simular
            </Button>
          </div>
        </div>
      </div>
    </div>
  )
}

export default connected(withStyles(styles)(CreditLinesList))
