const {
    TextField,
    Grid,
    FormControl,
    makeStyles,
    Paper,
    Button,
    DialogTitle,
    Tabs,
    Tab,
    Dialog,
    Typography,
    Box,
    Tooltip,
    FormLabel,
    RadioGroup,
    FormControlLabel,
    Radio,
    Select,
    MenuItem,
    InputLabel,
    DialogContent,
    DialogActions,
    Divider,
    Toolbar,
    Table,
    TableHead,
    TableRow,
    TableBody,
    IconButton,
    Icon,
    Snackbar,
    TableCell
  } = MaterialUI;
const { useState, Fragment } = React;
const PropTypes = PropTypes;

const GeneralModel = {
  father_surname: '',
  mother_surname: '',
  name: '',
  birthday_date: '',
  street: '',
  number: 0,
  settlement_name: '',
  postal_code: '',
  city: '',
  state: '',
  country: '',
  residence: '',
  marital_status: 1,
  email: '',
  phone_number:'',
  cellphone: '',
  home_type: 1,
  monthly_rent: 0,
  residency_period: '',
  facebook: '',
  instagram: '',
  whatsapp: '',
  has_job: 1,
  partner_reference: '',
  rfc: '',
  curp_code: '',
}

const OccupationModel = {
  company: '',
  company_address: '',
  company_telephone: '',
  job_position: '',
  job_antiquity: '',
  monthly_income: 0,
  monthly_spend: 0,
  degree: '',
}

const SpuseModel = {
  father_surname: '',
  mother_surname: '',
  name: '',
  birthplace: '',
  nationality: '',
  birthday_date: '',
  cellphone: '',
  works_name: '',
  profession: '',
  job_antiquity: '',
  monthly_income: 0,
  monthly_spend: 0,
  degree: '',
}

const ReferenceModel = {
  familiar_reference_fullname: '',
  familiar_reference_parter: 1,
  familiar_reference_address: '',
  familiar_reference_phone: '',
  no_familiar_reference_fullname: '',
  no_familiar_reference_parter: 1,
  no_familiar_reference_address: '',
  no_familiar_reference_phone: '',
}

const InformalReferenceModel = {
  name: '',
  whatsapp: 0,
}

const BusinessModel = {
  got_business: 0,
  name: '',
  business_activity: '',
  familiar_own_business: 0,
  name_familiar_business: '',
  familiar_business_activity: '',
}

const EconomicDependsModel = {
  relationship: '',
  fullname: '',
  age: '',
  schooling: '',
}

const BeneficiariesModel = {
  name: '',
  parenthood: '',
  percent: 0,
  address: '',
  birthday_date: '',
}

const TraitsModel = {
  qualities: '',
  weaknesses: '',
  hobbies: '',
  aspirations: '',
}

const QuestionsModel = {
  contribute: '',
  accomplishment: '',
  expectation: '',
}

function TabPanel(props) {
  const { children, value, index, ...other } = props;
  
  return (
    <Typography
      component="div"
      role="tabpanel"
      hidden={value !== index}
      id={`vertical-tabpanel-${index}`}
      aria-labelledby={`vertical-tab-${index}`}
      {...other}
    >
      <Box p={3}>{children}</Box>
    </Typography>
  );
}


TabPanel.propTypes = {
  children: PropTypes.node,
  index: PropTypes.any.isRequired,
  value: PropTypes.any.isRequired,
};

function a11yProps(index) {
  return {
    id: `vertical-tab-${index}`,
    'aria-controls': `vertical-tabpanel-${index}`,
  };
}

const useStyles = makeStyles(theme => ({
  root: {
    flexGrow: 1,
    backgroundColor: theme.palette.background.paper,
    display: 'flex',
    height: 220,
  },
  button: {
    marginTop: '30px'
  },
  container: {
    margin: '0 auto',
    width: "80%",
    padding: "15px"
  },
  tabs: {
    borderRight: `1px solid ${theme.palette.divider}`,
    //position: 'fixed'
  },
}));

class App extends React.Component {
    render() {
        return (<Home />);
    }
  }
function Header({text}){
  return(
    <Typography variant="h5">
      {text}
    </Typography>
  )
}
function Home(props) {
    const [general, setGeneral] = React.useState(GeneralModel)
    const [occupation, setOcupation] = React.useState(OccupationModel)
    const [spuse, setSpuse] = React.useState(SpuseModel)
    const [reference, setReference] = React.useState(ReferenceModel)
    const [informalReferenceList, setInformalReferenceList] = React.useState([])
    const [business, setBusiness] = React.useState(BusinessModel)
    const [economicDependList, setEconomicDependList] = React.useState([])
    const [beneficiariesList, setBeneficiariesList] = React.useState([])
    const [traits, setTraits] = React.useState(TraitsModel)
    const [questions, setQuestions] = React.useState(QuestionsModel)
    const [value, setValue] = React.useState(0);
    const [hasError, setHasError] = React.useState(false)
    const [open, setOpen] = React.useState(false);
    const [occupationRequerid, setOccupationRequired] = React.useState(true)
    const [spuseRequired, setSpuseRequired] = React.useState(true)
    const [beneficiariesPercent, setBeficiariesPercent] = React.useState(0)
    const [snackBar, setSnackBar] = React.useState({
      open: false,
      message: "ups"
    })

    function handleClickOpen(){
      setOpen(true);
    }
    function handleClose(){
      setOpen(false);
      setGeneral(GeneralModel)
      setOcupation(OccupationModel)
      setSpuse(SpuseModel)
      setReference(ReferenceModel)
      setInformalReferenceList([])
      setBusiness(BusinessModel)
      setEconomicDependList([])
      setBeneficiariesList([])
      setTraits(TraitsModel)
      setQuestions(QuestionsModel)
      setValue(0);
      setOccupationRequired(true)
      setSpuseRequired(true)
    }

    const classes = useStyles();
    const generalTab = 0,
          occupationTab = 1,
          spuseTab = 2,
          informalReferenceTab = 3,
          businessTab = 4,
          beneficiariesTab = 5,
          traitsTab = 6;


    
    function handleTabChange(event, newValue) {
      
      const currValue = newValue < value ? value - 1 : newValue - 1;
      switch(currValue){
        case generalTab:
          if(
            !isRequired(general.name)
            && !isRequired(general.birthday_date)
            && !isRequired(general.street)
            && !minLenght(general.number, 2)
            && !isRequired(general.settlement_name)
            && !isRequired(general.postal_code)
            && !isRequired(general.state)
            && !isRequired(general.city)
            && !isRequired(general.residence)
            && !isEmail(general.email)
            && !minLenght(general.cellphone, 6)
            && !isRequired(general.residency_period)
          ){
            setHasError(false)
          }else{
            setHasError(true)
            return
          }
          break
        case occupationTab:
          if (occupationRequerid){
            if(
              !isRequired(occupation.company)
              && !isRequired(occupation.job_position)
              && !minLenght(occupation.monthly_income, 3)
              && !minLenght(occupation.monthly_spend, 3)
              && !isRequired(occupation.degree)
            ){
              setHasError(false)
            }else {
              setHasError(true)
              return
            }
          }
          break;
        case spuseTab:
          if (spuseRequired){
            if (!minLenght(spuse.name, 5)){
              setHasError(false)
            } else {
              setHasError(true)
              return
            }
          }
          break;
        case informalReferenceTab:
          if(
            !minLenght(informalReferenceList, 3)
          ){
            setHasError(false)
          }else {
            setSnackBar({open: true, message: "Se requieren al menos 3 posibles interesados"})
            setHasError(true)
            return
          }
          break
        case businessTab:
          break;
        case beneficiariesTab:
          if(
            !minLenght(beneficiariesList, 1)
          ){
            setHasError(false)
          }else {
            setSnackBar({open: true, message: "Es necesario al menos un beneficiario"})
            setHasError(true)
            return
          }
          break;
        case traitsTab:
          break;
        default:
          alert('error')
      }
      
      setValue(newValue);
    }

    function handleClickSave() {
      //var url = 'http://localhost:4000/api/';
      var url = 'https://prospectos.financiera.4plus1creative.com/api/';
      if(
        !minLenght(traits.aspirations, 10)
        && !minLenght(traits.hobbies, 10)
        && !minLenght(traits.qualities, 10)
        && !minLenght(traits.weaknesses, 10)
      ){
        setHasError(false)
      }else{
        setHasError(true)
        return
      }
      general.Occupation = occupation
      general.Spuse = spuse,
      general.InformalReference = informalReferenceList
      general.Business = business
      general.Beneficiary = beneficiariesList
      general.Trait = traits
      fetch(url, {
        method: 'POST',
        body: JSON.stringify(general),
        headers: new Headers({
          'Content-Type': 'application/json'
        })
      }).then(res => res.json())
        .then(response => {
          console.log('Success:', response)
          handleClickOpen()
          return
        })
        .catch(error => console.error(error));
    }
    
      return(
        <div className={classes.container}>
          <div className={classes.root}>
            <Grid xs={3} sm={3} md={2} fixed={true}>
            <Tabs
              orientation="vertical"
              variant="scrollable"
              value={value}
//              onChange={handleTabChange}
              aria-label="Vertical tabs example"
              className={classes.tabs}
            >
              <Tooltip title="Datos generales del solicitante" placement="right">
                <Tab label="Paso 1" {...a11yProps(0)} />
              </Tooltip>
              <Tooltip title="Ocupación del Solicitante" placement="right">
                <Tab label="Paso 2" {...a11yProps(1)} />
              </Tooltip>
              <Tooltip title="Datos del Conyuge" placement="right">
                <Tab label="Paso 3" {...a11yProps(2)} />
              </Tooltip>
              <Tooltip title="Anota 3 personas que consideras que pudiesen aprovechar los beneficios de pertenecer a GENERA" placement="right">
                <Tab label="Paso 4" {...a11yProps(3)} />
              </Tooltip>
              <Tooltip title="Negocio" placement="right">
                <Tab label="Paso 5" {...a11yProps(4)} />
              </Tooltip>
              <Tooltip title="Beneficiarios en caso de fallecimiento" placement="right">
                <Tab label="Paso 6" {...a11yProps(5)} />
              </Tooltip>
              <Tooltip title="Escribe 3 características de los aspectos correspondientes a este apartado" placement="right">
                <Tab label="Paso 7" {...a11yProps(6)} />
              </Tooltip>
            </Tabs>
            </Grid>
            <Grid xs={9} sm={9} md={10}>
            <TabPanel value={value} index={0}>
              <Grid>
                <Header text="Datos generales del solicitante"/>
              </Grid>
              <Grid>
                <General
                  general={general}
                  onGeneralChange={setGeneral}
                  onRequiredOccupationChange={setOccupationRequired}
                  onRequiredSpuseChange={setSpuseRequired}
                  hasError={hasError}
                />
              </Grid>
              <Grid xs={9} sm={9} md={2}>
                <Button
                  variant="contained"
                  color="primary"
                  size="large"
                  value={value}
                  className={classes.button}
                  onClick={ev => handleTabChange(ev, value + 1)}
                  >
                  Siguiente
                </Button>
              </Grid>
            </TabPanel>
            <TabPanel value={value} index={1}>
              <Typography variant="h5">
                Ocupación del Solicitante
              </Typography>
              <Occupation
                occupation={occupation}
                onOccupationChange={setOcupation}
                requiredOccuptionStep={occupationRequerid}
                hasError={hasError}
              />
              <Grid container spacing={1}>
                  <Grid xs={9} sm={4} md={2}>
                      <Button
                          variant="contained"
                          color="primary"
                          size="large"
                          
                          className={classes.button}
                          onClick={ev => handleTabChange(ev, value - 1)}
                          >
                          Atras
                      </Button>
                  </Grid>
                  <Grid xs={9} sm={4} md={2}>
                      <Button
                          variant="contained"
                          color="primary"
                          size="large"
                          
                          value={value}
                          className={classes.button}
                          onClick={ev => handleTabChange(ev, value + 1)}
                          >
                          Siguiente
                      </Button>
                  </Grid>
              </Grid>
            </TabPanel>
            <TabPanel value={value} index={2}>
              <Typography variant="h5">
                Datos del Conyuge
              </Typography>
              <Spuse
                spuse={spuse}
                onSpuseChange={setSpuse}
                requiredSpuseStep={spuseRequired}
                hasError={hasError}
              />
              <Grid container spacing={1}>
                <Grid xs={9} sm={4} md={2}>
                      <Button
                          variant="contained"
                          color="primary"
                          size="large"
                          
                          className={classes.button}
                          onClick={ev => handleTabChange(ev, value - 1)}
                          >
                          Atras
                      </Button>
                  </Grid>
                  <Grid xs={9} sm={4} md={2}>
                      <Button
                          variant="contained"
                          color="primary"
                          size="large"
                          value={value}
                          className={classes.button}
                          onClick={ev => handleTabChange(ev, value + 1)}
                          >
                          Siguiente
                      </Button>
                  </Grid>
              </Grid>
            </TabPanel>
            <TabPanel value={value} index={3}>
              <Typography variant="h5">
                Anota 3 personas que consideras que pudiesen aprovechar los beneficios de pertenecer a GENERA
              </Typography>
              <InformalReferences
                informalReferenceList={informalReferenceList}
                onInformalReferenceListChange={setInformalReferenceList}
                hasError={hasError}
              />
              <Divider />
              <Grid container spacing={1}>
                  <Grid xs={9} sm={4} md={2}>
                      <Button
                          variant="contained"
                          color="primary"
                          size="large"
                          
                          className={classes.button}
                          onClick={ev => handleTabChange(ev, value - 1)}
                          >
                          Atras
                      </Button>
                  </Grid>
                  <Grid xs={9} sm={4} md={2}>
                      <Button
                          variant="contained"
                          color="primary"
                          size="large"
                          value={value}
                          className={classes.button}
                          onClick={ev => handleTabChange(ev, value + 1)}
                          >
                          Siguiente
                      </Button>
                  </Grid>
              </Grid>
            </TabPanel>
            <TabPanel value={value} index={4}>
              <Typography variant="h5">
                Negocio
              </Typography>
              <Business
                business={business}
                onBusinessChange={setBusiness}
                hasError={hasError}
              />
              <Grid container spacing={1}>
                  <Grid xs={9} sm={4} md={2}>
                      <Button
                          variant="contained"
                          color="primary"
                          size="large"
                          
                          className={classes.button}
                          onClick={ev => handleTabChange(ev, value - 1)}
                          >
                          Atras
                      </Button>
                  </Grid>
                  <Grid xs={9} sm={4} md={2}>
                      <Button
                          variant="contained"
                          color="primary"
                          size="large"
                          value={value}
                          className={classes.button}
                          onClick={ev => handleTabChange(ev, value + 1)}
                          >
                          Siguiente
                      </Button>
                  </Grid>
              </Grid>
            </TabPanel>
            <TabPanel value={value} index={5}>
              <Typography variant="h5">
                Beneficiarios en caso de fallecimiento
              </Typography>
              <Beneficiaries
                beneficiariesList={beneficiariesList}
                onBeneficiariesListChange={setBeneficiariesList}
                hasError={hasError}
              />
              <Grid container spacing={1}>
                  <Grid xs={9} sm={4} md={2}>
                      <Button
                          variant="contained"
                          color="primary"
                          size="large"
                          
                          className={classes.button}
                          onClick={ev => handleTabChange(ev, value - 1)}
                          >
                          Atras
                      </Button>
                  </Grid>
                  <Grid xs={9} sm={4} md={2}>
                      <Button
                          variant="contained"
                          color="primary"
                          size="large"
                          value={value}
                          className={classes.button}
                          onClick={ev => handleTabChange(ev, value + 1)}
                          >
                          Siguiente
                      </Button>
                  </Grid>
              </Grid>
            </TabPanel>
            <TabPanel value={value} index={6}>
              <Typography variant="h5">
                Escribe 3 características de los aspectos correspondientes a este apartado
              </Typography>
              <Traits
                traits={traits}
                onTraitsChange={setTraits}
                hasError={hasError}
              />
              <Grid container spacing={1}>
                  <Grid xs={9} sm={4} md={2}>
                      <Button
                          variant="contained"
                          color="primary"
                          size="large"
                          
                          className={classes.button}
                          onClick={ev => handleTabChange(ev, value - 1)}
                          >
                          Atras
                      </Button>
                  </Grid>
                  <Grid xs={9} sm={4} md={2}>
                    <Button
                        variant="contained"
                        color="primary"
                        size="large"
                        fullWidth={true}
                        className={classes.button}
                        onClick={handleClickSave}
                        >
                        Enviar
                    </Button>
                  </Grid>
              </Grid>
            </TabPanel>
            </Grid>
          </div>
        <Dialog onClose={handleClose} aria-labelledby="customized-dialog-title" open={open}>
          <DialogTitle id="customized-dialog-title" onClose={handleClose}>
            Gracias!!
          </DialogTitle>
          <DialogContent dividers>
            <Typography gutterBottom>
              Genera te agradece el tiempo invertido para ser parte de nuestra gran comunidad de socios, un asesor se estara comunicando contigo en los proximos dias.
            </Typography>
          </DialogContent>
          <DialogActions>
            <Button onClick={ev => handleClose()} color="primary">
              Aceptar
            </Button>
          </DialogActions>
        </Dialog>
        <SnackBarSimple
          attributes={snackBar}
          setOpen={setSnackBar}
        />
        </div>
      )
  }

  ReactDOM.render(<App />, document.getElementById('app'));