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

import ButtonWithProgress from '@agiliza/components/atoms/ButtonWithProgress'
import { useFormState } from '@agiliza/utils/hooks/state'
import { CREDIT_LINES_PATHS } from '@agiliza/views/SimulationCreditLines/pages/router'
import { Button, MobileStepper, Typography } from '@material-ui/core'
import { withStyles, WithStyles } from '@material-ui/core/styles'
import {
  AccountBox as AccountBoxIcon,
  Apartment as ApartmentIcon,
  AttachMoney as AttachMoneyIcon,
  CheckBox as CheckBoxIcon,
  ContactMail as ContactMailIcon,
  DriveEta as DriveEtaIcon,
  Forum as ForumIcon,
  Home as HomeIcon,
  InsertDriveFile as InsertDriveFileIcon,
  KeyboardArrowLeft as KeyboardArrowLeftIcon,
  KeyboardArrowRight as KeyboardArrowRightIcon,
  List as ListIcon,
  LocalAtm as LocalAtmIcon,
  ZoomOutMap as ZoomOutMapIcon
} from '@material-ui/icons'

import BDAddress, { initialState as bdAddressInitState } from './BusinessData/Address'
import BDIdentification, {
  initialState as bdIdentificationInitState
} from './BusinessData/Identification'
import ProductsServices, {
  initialState as bdProductServiceInitState
} from './BusinessData/ProductsServices'
import StockSalesCosts, {
  initialState as bdStockSalesCostsInitState
} from './BusinessData/StockSalesCosts'
import { connected, ConnectedProps } from './connect'
import Address, { initialState as cdAddressInitState } from './CustomerData/Address'
import Home, { initialState as cdHomeInitState } from './CustomerData/Home'
import Identification, { initialState as cdIdentInitState } from './CustomerData/Identification'
import PersonalData, { initialState as cdPersonalDataInitState } from './CustomerData/PersonalData'
import References, { initialState as cdReferenceInitState } from './CustomerData/References'
import SourceIncome, { initialState as cdSourceIncomeInitState } from './CustomerData/SourceIncome'
import SpouseAdditionalData from './CustomerData/SpouseAdditionalData'
import SpouseData, { initialState as cdSpouseDataInitState } from './CustomerData/SpouseData'
import Vehicles, { initialState as cdVehicleInitState } from './CustomerData/Vehicles'
import styles from './shared-styles'

export const PROPOSAL_DATA_PATHS = {
  selectOption: '/selecionarOpcao',
  involvedPeople: '/pessoasEnvolvidas',
  businessData: '/dadosNegocio',
}

export interface ProposalDataRouteState {
  subproductId: string
}

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

interface Props extends ExtendedProps {}

const ProposalData = (props: Props) => {
  const { classes, history, fetching, proposalId, personId } = props
  const [activeStep, setActiveStep] = useState(0)

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

  const cdIdentification = useFormState('cdIdentificationState', cdIdentInitState)
  const cdPersonalData = useFormState('cdPersonalDataState', cdPersonalDataInitState)
  const cdAddress = useFormState('cdAddressState', cdAddressInitState)
  const cdSourceIncome = useFormState('cdSourceIncome', cdSourceIncomeInitState)
  const cdSpouseData = useFormState('cdSpouseData', cdSpouseDataInitState)
  const cdReference = useFormState('cdReference', cdReferenceInitState)
  const cdHomeState = useFormState('cdHomeState', cdHomeInitState)
  const cdVehicleState = useFormState('cdVehicleState', cdVehicleInitState)

  const bdIdentificationState = useFormState('bdIdentificationState', bdIdentificationInitState)
  const bdAddressState = useFormState('bdAddressState', bdAddressInitState)
  const bdStockSalesCostsState = useFormState('bdStockSalesCostsState', bdStockSalesCostsInitState)
  const bdProductServiceState = useFormState('bdProductServiceState', bdProductServiceInitState)

  const customerDataItems = useMemo(
    () => [
      {
        label: 'Identificação',
        icon: <AccountBoxIcon />,
        component: <Identification state={cdIdentification.state} actions={cdIdentification.actions} />,
      },
      { label: 'Dados Pessoais', icon: <ListIcon />, component: <PersonalData state={cdPersonalData.state} actions={cdPersonalData.actions} /> },
      { label: 'Endereço', icon: <ContactMailIcon />, component: <Address state={cdAddress.state} actions={cdAddress.actions} /> },
      { label: 'Fonte de renda', icon: <LocalAtmIcon />, component: <SourceIncome state={cdSourceIncome.state} actions={cdSourceIncome.actions} /> },
      { label: 'Cônjuge - Ident.', icon: <ForumIcon />, component: <SpouseData state={cdSpouseData.state} actions={cdSpouseData.actions} /> },
      {
        label: 'Cônjuge +',
        icon: <ZoomOutMapIcon />,
        component: <SpouseAdditionalData state={cdSpouseData.state} actions={cdSpouseData.actions} />,
      },
      {
        label: 'Referências',
        icon: <CheckBoxIcon />,
        component: <References state={cdReference.state} actions={cdReference.actions} projectId={proposalId} personId={personId} />,
      },
      { label: 'Moradia', icon: <HomeIcon />, component: <Home state={cdHomeState.state} actions={cdHomeState.actions} /> },
      {
        label: 'Veículos',
        icon: <DriveEtaIcon />,
        component: <Vehicles state={cdVehicleState.state} actions={cdVehicleState.actions} projectId={proposalId} personId={personId} />,
      },
    ],
    [cdIdentification, cdPersonalData, cdAddress, cdSpouseData, cdReference, cdHomeState, cdVehicleState]
  )

  const businessDataItems = useMemo(
    () => [
      {
        label: 'Identificação',
        icon: <AccountBoxIcon />,
        component: <BDIdentification state={bdIdentificationState.state} actions={bdIdentificationState.actions} />,
      },
      { label: 'Endereço', icon: <ApartmentIcon />, component: <BDAddress state={bdAddressState.state} actions={bdAddressState.actions} /> },
      {
        label: 'Produto',
        icon: <InsertDriveFileIcon />,
        component: <ProductsServices projectId={proposalId} state={bdProductServiceState.state} actions={bdProductServiceState.actions} />,
      },
      {
        label: 'Estoque, Vendas e Custos',
        icon: <AttachMoneyIcon />,
        component: <StockSalesCosts state={bdStockSalesCostsState.state} actions={bdStockSalesCostsState.actions} />,
      },
    ],
    [bdIdentificationState, bdAddressState, bdStockSalesCostsState, bdProductServiceState]
  )

  const proposalDataItems = useMemo(() => [...customerDataItems, ...businessDataItems], [customerDataItems, businessDataItems])

  const steps = useMemo(() => proposalDataItems.length, [proposalDataItems])
  // const location = useLocation<ProposalDataRouteState>()

  const handleNext = () => {
    // if (activeStep === steps - 1) history.push({ pathname: PATHS.creditLines })
    const projectPersonIds = { projectId: proposalId, personId }
    switch (activeStep) {
      case 0:
        props.addIndentification({
          identification: { ...cdIdentification.state, account: cdIdentification.state.hasAccount ? cdIdentification.state.account : undefined },
          projectId: proposalId,
          onSuccess: () => setActiveStep((prevActiveStep) => prevActiveStep + 1),
        })
        break
      case 1:
        props.updatePersonalData({
          ...projectPersonIds,
          personalData: cdPersonalData.state,
          onSuccess: () => setActiveStep((prevActiveStep) => prevActiveStep + 1),
        })
        break
      case 2:
        props.updateCDAddress({
          ...projectPersonIds,
          address: cdAddress.state,
          onSuccess: () => setActiveStep((prevActiveStep) => prevActiveStep + 1),
        })
        break
      case 3:
        props.updateSourceIncome({
          ...projectPersonIds,
          sourceIncome: cdSourceIncome.state,
          onSuccess: () => setActiveStep((prevActiveStep) => prevActiveStep + 1),
        })
        break
      case 4:
        props.updateSpouseData({
          ...projectPersonIds,
          spouseData: cdSpouseData.state,
          onSuccess: () => setActiveStep((prevActiveStep) => prevActiveStep + 1),
        })
        break
      case 5:
        props.updateSpouseData({
          ...projectPersonIds,
          spouseData: cdSpouseData.state,
          onSuccess: () => setActiveStep((prevActiveStep) => prevActiveStep + 1),
        })
        break
      case 7:
        props.updateHome({
          ...projectPersonIds,
          home: cdHomeState.state,
          onSuccess: () => setActiveStep((prevActiveStep) => prevActiveStep + 1),
        })
        break
      case 9:
        props.updateIdentification({
          projectId: proposalId,
          identification: bdIdentificationState.state,
          onSuccess: () => setActiveStep((prevActiveStep) => prevActiveStep + 1),
        })
        break
      case 10:
        props.updateBDAddress({
          projectId: proposalId,
          address: bdAddressState.state,
          onSuccess: () => setActiveStep((prevActiveStep) => prevActiveStep + 1),
        })
        break
      case 12:
        props.updateStockSalesCosts({
          projectId: proposalId,
          stockSalesCosts: bdStockSalesCostsState.state,
          onSuccess: () => {
            props.sendProposal({
              proposalId,
              onSuccess: () => {
                history.push({ pathname: CREDIT_LINES_PATHS.finishSimulation, state: { proposalId } })
              },
            })
          },
        })
        break
      default:
        setActiveStep((prevActiveStep) => prevActiveStep + 1)
    }
  }

  const handleBack = () => {
    setActiveStep((prevActiveStep) => prevActiveStep - 1)
  }

  const mapActiveStepToTitle = () => {
    if (activeStep < customerDataItems.length) return 'Dados do cliente'
    if (activeStep < proposalDataItems.length) return 'Dados de negócio'
  }

  return (
    <div className={classes.pageContent}>
      <Typography className={classes.pageTitle} variant="h5">
        {mapActiveStepToTitle()}
      </Typography>
      <Typography className={classes.pageSubtitle}>{proposalDataItems[activeStep].label}</Typography>
      <div className={classes.stepContentContainer}>{proposalDataItems[activeStep].component}</div>
      <div className={classes.stepperContainer}>
        {/* <Stepper activeStep={activeStep} alternativeLabel className={classes.stepper}> */}
        {/* {propostalDataItems.map((iPI, i) => (
            <Step key={i}>
              <StepLabel>{iPI.label}</StepLabel>
            </Step>
          ))} */}
        <MobileStepper
          variant="dots"
          steps={steps}
          position="static"
          activeStep={activeStep}
          style={{ width: '100%' }}
          nextButton={
            <ButtonWithProgress fetching={fetching} variant="text" size="large" onClick={handleNext} className={classes.stepperBtn}>
              {activeStep === steps - 1 ? (
                'Finalizar'
              ) : (
                <>
                  Próximo
                  <KeyboardArrowRightIcon />
                </>
              )}
            </ButtonWithProgress>
          }
          backButton={
            <Button size="large" onClick={handleBack} disabled={activeStep === 0} className={classes.stepperBtn}>
              <KeyboardArrowLeftIcon />
              Anterior
            </Button>
          }
        />
        {/* </Stepper> */}
      </div>
    </div>
  )
}

export default connected(withStyles(styles)(ProposalData))
