//**DATOS GENERALES DEL SOLICITANTE */
//**Step 1*/
const {

  makeStyles,
 
} = MaterialUI;

const useStyles = makeStyles(theme => ({
  container: {
    display: 'flex',
    flexWrap: 'wrap',
  },
  textField: {
    marginLeft: theme.spacing(1),
    marginRight: theme.spacing(1),
    width: 200,
  },
}));

function isRequired(value){
  return value === "" 
}
function isEmail(value){
  const pattern = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return !pattern.test(value)
}

function onlyDate(value){
  const pattern = /([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/
  return !value || pattern.test(value)
}

function isPercent(value){
  if (value < 0){
    return true
  }
  return value > 100
}


function minLenght(value, min) {
  debugger
  var length = null

  switch (typeof(value)) {
    case 'number':
      length = value.toString().length
      break
    default:
      length = value.length
      break
  }
  return length < min
}

// credits for https://es.stackoverflow.com/a/31040
function validateCurp(curp) {
  var re = /^([A-Z][AEIOUX][A-Z]{2}\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])[HM](?:AS|B[CS]|C[CLMSH]|D[FG]|G[TR]|HG|JC|M[CNS]|N[ETL]|OC|PL|Q[TR]|S[PLR]|T[CSL]|VZ|YN|ZS)[B-DF-HJ-NP-TV-Z]{3}[A-Z\d])(\d)$/,
      validado = curp.match(re);

  if (!validado)  //Coincide con el formato general?
    return false;
  
  //Validar que coincida el dígito verificador
  function digitoVerificador(curp17) {
      //Fuente https://consultas.curp.gob.mx/CurpSP/
      var diccionario  = "0123456789ABCDEFGHIJKLMNÑOPQRSTUVWXYZ",
          lngSuma      = 0.0,
          lngDigito    = 0.0;
      for(var i=0; i<17; i++)
          lngSuma = lngSuma + diccionario.indexOf(curp17.charAt(i)) * (18 - i);
      lngDigito = 10 - lngSuma % 10;
      if (lngDigito == 10) return 0;
      return lngDigito;
  }

  if (validado[2] != digitoVerificador(validado[1])) 
    return false;
      
  return true; //Validado
}

//credits for https://es.stackoverflow.com/a/31714
function validateRfc(rfc, aceptarGenerico = true) {
  const re       = /^([A-ZÑ&]{3,4}) ?(?:- ?)?(\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])) ?(?:- ?)?([A-Z\d]{2})([A\d])$/;
  var   validado = rfc.match(re);

  if (!validado)  //Coincide con el formato general del regex?
      return false;

  //Separar el dígito verificador del resto del RFC
  const digitoVerificador = validado.pop(),
        rfcSinDigito      = validado.slice(1).join(''),
        len               = rfcSinDigito.length,

  //Obtener el digito esperado
        diccionario       = "0123456789ABCDEFGHIJKLMN&OPQRSTUVWXYZ Ñ",
        indice            = len + 1;
  var   suma,
        digitoEsperado;

  if (len == 12) suma = 0
  else suma = 481; //Ajuste para persona moral

  for(var i=0; i<len; i++)
      suma += diccionario.indexOf(rfcSinDigito.charAt(i)) * (indice - i);
  digitoEsperado = 11 - suma % 11;
  if (digitoEsperado == 11) digitoEsperado = 0;
  else if (digitoEsperado == 10) digitoEsperado = "A";

  //El dígito verificador coincide con el esperado?
  // o es un RFC Genérico (ventas a público general)?
  if ((digitoVerificador != digitoEsperado)
   && (!aceptarGenerico || rfcSinDigito + digitoVerificador != "XAXX010101000"))
      return false;
  else if (!aceptarGenerico && rfcSinDigito + digitoVerificador == "XEXX010101000")
      return false;
  return rfcSinDigito + digitoVerificador;
}

const hasJobEnum = {
  yes: 1,
  no: 2
}

const maritalStatusEnum = {
  married: 1,
  single: 2,
  consensual_union: 3
}

function General({general, onGeneralChange, hasError, onRequiredOccupationChange, onRequiredSpuseChange}) { 
  const classes = useStyles();

  function hasJobHandler(value){
    if (value === hasJobEnum.yes){
      onRequiredOccupationChange(true)
    }else{
      onRequiredOccupationChange(false)
    }
    onGeneralChange({...general, has_job: value})
  }

  function maritalStatusHandler(value) {
    if (value === maritalStatusEnum.married) {
      onRequiredSpuseChange(true)
    }else {
      onRequiredSpuseChange(false)
    }
    debugger
    onGeneralChange({...general, marital_status: value})
  }

  function rfcHandler(value = "") {
    onGeneralChange({...general, rfc: value.trim().toUpperCase()})
  }

  function curpHandler(value = "") {
    onGeneralChange({...general, curp_code: value.trim().toUpperCase()})
  }

  return(
  <Grid container spacing={4}>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl fullWidth>
        <TextField
            label="Apellido Paterno:"
            margin="normal"
            value={general.father_surname}
            onChange={ev => onGeneralChange({...general, father_surname: ev.target.value})}
          />
      </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl fullWidth>
        <TextField
          label="Apellido Materno:"
          margin="normal"
          value={general.mother_surname}
          onChange={ev => onGeneralChange({...general, mother_surname: ev.target.value})}
          />
      </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl fullWidth>
        <TextField
          label="Nombre (s):"
          margin="normal"
          error={hasError && isRequired(general.name)}
          helperText={hasError && isRequired(general.name) && "Campo requerido"}
          value={general.name}
          onChange={ev => onGeneralChange({...general, name: ev.target.value})}
          required
          />
      </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl fullWidth>
        <TextField
          label="Fecha de nacimiento:"
          margin="normal"
          type="date"
          error={hasError && isRequired(general.birthday_date)}
          helperText={hasError && isRequired(general.birthday_date) && "Campo requerido"}
          value={general.birthday_date}
          onChange={ev => onGeneralChange({...general, birthday_date: ev.target.value})}
          className={classes.textField}
          InputLabelProps={{
            shrink: true,
          }}
          required
          />
      </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl fullWidth>
        <TextField
          label="Calle:"
          margin="normal"
          error={hasError && isRequired(general.street)}
          helperText={hasError && isRequired(general.street) && "Campo requerido"}
          value={general.street}
          onChange={ev => onGeneralChange({...general, street: ev.target.value})}
          required
          />
      </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl fullWidth>
        <TextField
          label="Numero:"
          margin="normal"
          type="number"
          error={hasError && minLenght(general.number, 2)}
          helperText={hasError && minLenght(general.number, 2) && "Campo requerido"}
          value={general.number}
          onChange={ev => onGeneralChange({...general, number: Number(ev.target.value)})}
          required
          />
      </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl fullWidth>
        <TextField
          label="Colonia:"
          margin="normal"
          error={hasError && isRequired(general.settlement_name)}
          helperText={hasError && isRequired(general.settlement_name) && "Campo requerido"}
          value={general.settlement_name}
          onChange={ev => onGeneralChange({...general, settlement_name: ev.target.value})}
          required
          />
      </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl fullWidth>
        <TextField
          label="C.P:"
          margin="normal"
          error={hasError && isRequired(general.postal_code)}
          helperText={hasError && isRequired(general.postal_code) && "Campo requerido"}
          value={general.postal_code}
          onChange={ev => onGeneralChange({...general, postal_code: ev.target.value})}
          required
          />
      </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl fullWidth>
        <TextField
          label="Ciudad:"
          margin="normal"
          error={hasError && isRequired(general.city)}
          helperText={hasError && isRequired(general.city) && "Campo requerido"}
          value={general.city}
          onChange={ev => onGeneralChange({...general, city: ev.target.value})}
          required
          />
      </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl fullWidth>
        <TextField
          label="Estado:"
          margin="normal"
          error={hasError && isRequired(general.state)}
          helperText={hasError && isRequired(general.state) && "Campo requerido"}
          value={general.state}
          onChange={ev => onGeneralChange({...general, state: ev.target.value})}
          required
          />
      </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl fullWidth>
        <TextField
          label="País:"
          margin="normal"
          error={hasError && isRequired(general.country)}
          helperText={hasError && isRequired(general.country) && "Campo requerido"}
          value={general.country}
          onChange={ev => onGeneralChange({...general, country: ev.target.value})}
          required
          />
      </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl fullWidth>
        <TextField
          label="Residencia:"
          margin="normal"
          error={hasError && isRequired(general.residence)}
          helperText={hasError && isRequired(general.residence) && "Campo requerido"}
          value={general.residence}
          onChange={ev => onGeneralChange({...general, residence: ev.target.value})}
          required
          />
      </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl component="fieldset">
          <FormLabel component="legend">Actualmente Labora</FormLabel>
          <RadioGroup 
          aria-label="gender" 
          name="has_job" 
          value={general.has_job}
          onChange={ev => hasJobHandler(Number(ev.target.value))}
          >
            <FormControlLabel value={1} control={<Radio />} label="Si" />
            <FormControlLabel value={2} control={<Radio />} label="No" />
          </RadioGroup>
        </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl component="fieldset">
          <FormLabel component="legend">Estado Civil</FormLabel>
          <RadioGroup 
          aria-label="gender" 
          name="marital_status" 
          value={general.marital_status}
          onChange={ev => maritalStatusHandler(Number(ev.target.value))}
          >
            <FormControlLabel value={1} control={<Radio />} label="Casado(a)" />
            <FormControlLabel value={2} control={<Radio />} label="Soltero(a)" />
            <FormControlLabel value={3} control={<Radio />} label="Unión libre" />
          </RadioGroup>
        </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl fullWidth>
        <TextField
          label="Email:"
          margin="normal"
          error={hasError && isEmail(general.email)}
          helperText={hasError && isEmail(general.email) && "Email invalido"}
          value={general.email}
          onChange={ev => onGeneralChange({...general, email: ev.target.value})}
          required
          />
      </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl fullWidth>
        <TextField
          label="Teléfono:"
          margin="normal"
          type="number"
          value={general.phone_number}
          onChange={ev => onGeneralChange({...general, phone_number: ev.target.value})}
          />
      </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl fullWidth>
        <TextField
          label="Celular:"
          margin="normal"
          type="number"
          error={hasError && minLenght(general.cellphone, 6)}
          helperText={hasError && minLenght(general.cellphone, 6) && "Campo requerido"}
          value={general.cellphone}
          onChange={ev => onGeneralChange({...general, cellphone: ev.target.value})}
          required
          />
      </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl component="fieldset">
          <FormLabel component="legend">Mi casa es</FormLabel>
          <RadioGroup
          aria-label="gender" 
          name="home_type" 
          value={general.home_type}
          onChange={ev => onGeneralChange({...general, home_type: Number(ev.target.value)})}
          >
            <FormControlLabel value={1} control={<Radio />} label="Propia(a)" />
            <FormControlLabel value={2} control={<Radio />} label="Renta(a)" />
          </RadioGroup>
        </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl fullWidth>
        <TextField
          label="En caso de ser de renta el pago mensual es:"
          margin="normal"
          type="number"
          value={general.monthly_rent}
          onChange={ev => onGeneralChange({...general, monthly_rent: ev.target.value})}
          />
      </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl fullWidth>
        <TextField
          label="Tiempo viviendo ahí:"
          margin="normal"
          error={hasError && isRequired(general.residency_period)}
          helperText={hasError && isRequired(general.residency_period) && "Campo requerido"}
          value={general.residency_period}
          onChange={ev => onGeneralChange({...general, residency_period: ev.target.value})}
          required
          />
      </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl fullWidth>
        <TextField
          label="Rfc:"
          margin="normal"
          error={hasError && !validateRfc(general.rfc)}
          helperText={hasError && !validateRfc(general.rfc) && "Rfc invalido"}
          value={general.rfc}
          onChange={ev => rfcHandler(ev.target.value)}
          required
          />
      </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl fullWidth>
        <TextField
          label="Curp:"
          margin="normal"
          error={hasError && !validateCurp(general.curp_code)}
          helperText={hasError && !validateCurp(general.curp_code) && "Curp invalida"}
          value={general.curp_code}
          onChange={ev => curpHandler(ev.target.value)}
          required
          />
      </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl fullWidth>
        <TextField
          label="Facebook:"
          margin="normal"
          value={general.facebook}
          onChange={ev => onGeneralChange({...general, facebook: ev.target.value})}
          />
      </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl fullWidth>
        <TextField
          label="Instagram:"
          margin="normal"
          value={general.instagram}
          onChange={ev => onGeneralChange({...general, instagram: ev.target.value})}
          />
      </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl fullWidth>
        <TextField
          label="Whatsapp:"
          margin="normal"
          value={general.whatsapp}
          onChange={ev => onGeneralChange({...general, whatsapp: ev.target.value})}
          />
      </FormControl>
    </Grid>
    <Grid item xs={12} sm={6} md={6}>
      <FormControl fullWidth>
        <TextField
          label="En caso de que algún socio te haya invitado, favor de poner su nombre o número de socio:"
          margin="normal"
          value={general.partner_reference}
          onChange={ev => onGeneralChange({...general, partner_reference: ev.target.value})}
          />
      </FormControl>
    </Grid>
    
  </Grid>
  )
}
