text: import React from 'react';
  import axios from 'axios';
  import PropTypes from 'prop-types';
  import { useCookies } from 'react-cookie';
  import moment from 'moment';
  
  import WeekScheduler from '../WeekScheduler';
  
  import Autocomplete from '@material-ui/lab/Autocomplete';
  import { makeStyles } from '@material-ui/styles';
  import {
    Grid,
    TextField,
    CircularProgress,
    Typography,
  } from '@material-ui/core';
  
  const useStyles = makeStyles(() => ({
    root: {
      display: 'flex',
      flexDirection: 'column',
      margin: 10
    }
  }));
  
  const ViewScheduleForm = props => {
    const classes = useStyles();
  
    const [schedule, setSchedule] = React.useState([]);
    const [isLoadingSchedule, setIsLoadingSchedule] = React.useState(false);
  
    const [cookies] = useCookies(['user']);
  
    const [locations, setLocations] = React.useState([]);
    const [selectedLocation, setSelectedLocation] = React.useState({});
    const [isLoadingLocations, setIsLoadingLocations] = React.useState(false);
  
    const [beginDate, setBeginDate] = React.useState('');
    const [requestFlag, setRequestFlag] = React.useState(false);
  
    const [employees, setEmployees] = React.useState([]);
    const [selectedEmployees, setSelectedEmployees] = React.useState('');
    const [isLoadingEmployees, setIsLoadingEmployees] = React.useState(false);
  
    React.useEffect(() => {
      axios.get(process.env.REACT_APP_BACKEND_URL + process.env.REACT_APP_BACKEND_LOCATION + `?&api_token=${cookies?.user?.token}`).then(res => {
        setLocations(res.data);
        setIsLoadingLocations(false);
      }).catch(err => {
        console.log(err);
      })
    }, [cookies])
  
    const handleChangeLocation = (event, value) => {
      console.log(selectedLocation);
      console.log(selectedEmployees);
      setSelectedLocation(value);
      setEmployees('');
      setSchedule([]);
      if (value) {
        setIsLoadingEmployees(true);
        axios.get(process.env.REACT_APP_BACKEND_URL + process.env.REACT_APP_BACKEND_EMPLOYEELOCATION + `${value?.id}?&api_token=${cookies?.user?.token}`).then(res => {
          console.log(res.data)
          setEmployees(res.data);
          setIsLoadingEmployees(false);
        }).catch((error) => {
          console.log(error);
        })
      }
    }
  
    const handleChangeEmployee = (event, value) => {
      console.log(value)
      setRequestFlag(false);
      setSelectedEmployees(value);
      setSchedule([]);
      if (value) {
        setIsLoadingSchedule(true);
        axios.get(process.env.REACT_APP_BACKEND_URL + process.env.REACT_APP_BACKEND_VIEWSCHEDULE + `?&api_token=${cookies?.user?.token}&locacion_id=${selectedLocation?.id}&empleado_id=${value?.id}`).then(res => {
          console.log(res);
          if (res?.data?.horarios_laborales?.length) {
            setBeginDate(new Date(res?.data?.horarios_laborales[0][0]));
            const defaultSchedule = res?.data?.horarios_laborales?.map(range =>
              range.map(dateString => new Date(dateString))
            );
            setSchedule(defaultSchedule);
          } else {
            setSchedule([]);
            setRequestFlag(true);
          }
          setIsLoadingSchedule(false);
        }).catch((error) => {
          console.log(error);
          console.log(error?.response);
          if (error?.response?.status === 406) {
            setSchedule([]);
            setIsLoadingSchedule(false);
          }
        })
      }
    }
  
    return (
      <form
        autoComplete="off"
        className={classes.root}
      >
        <Grid
          container
          spacing={3}
        >
          <Grid
            item
            lg={12}
            md={12}
            sm={12}
            xs={12}
          >
            <Autocomplete
              fullWidth
              getOptionLabel={(option) => option.direccion}
              id="employee-combo-box"
              onChange={handleChangeLocation}
              options={locations}
              renderInput={(params) =>
                <TextField
                  {...params}
                  fullWidth
                  InputProps={{
                    ...params.InputProps,
                    endAdornment: (
                      <React.Fragment>
                        {isLoadingLocations ?
                          <CircularProgress
                            color="inherit"
                            size={20}
                          /> : null}
                        {params.InputProps.endAdornment}
                      </React.Fragment>
                    ),
                  }}
                  label="Locacion"
                  variant="outlined"
                />
              }
            />
          </Grid>
          <Grid
            item
            lg={12}
            md={12}
            sm={12}
            style={{ textAlign: 'center' }}
            xs={12}
          >
            {isLoadingEmployees ?
              <CircularProgress
                color="primary"
                size={40}
              />
              :
              employees.length ?
                <Autocomplete
                  getOptionLabel={(option) => option.nombre}
                  id="employees"
                  onChange={handleChangeEmployee}
                  options={employees}
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      fullWidth
                      InputProps={{
                        ...params.InputProps,
                        endAdornment: (
                          <React.Fragment>
                            {isLoadingEmployees ?
                              <CircularProgress
                                color="inherit"
                                size={20}
                              /> : null}
                            {params.InputProps.endAdornment}
                          </React.Fragment>
                        ),
                      }}
                      label="Empleado"
                      placeholder="Empleado"
                      variant="outlined"
                    />
                  )}
                />
                :
                null
            }
          </Grid>
          <Grid
            item
            lg={12}
            md={12}
            sm={12}
            style={{ display: 'flex', justifyContent: 'center' }}
            xs={12}
          >
            {isLoadingSchedule ?
              <CircularProgress
                color="primary"
                size={40}
              />
              :
              schedule.length ?
                <WeekScheduler
                  beginDate={beginDate}
                  disabled
                  schedule={schedule}
                  setSchedule={setSchedule}
                />
                :
                requestFlag ?
                  <Typography>
                    No tiene horarios cargados
                  </Typography>
                  :
                  null
            }
          </Grid>
          <Grid
            item
            lg={6}
            md={6}
            sm={12}
            xs={12}
          >
            {isLoadingSchedule ?
              null
              :
              schedule.length ?
                <TextField
                  defaultValue={moment(beginDate).format('YYYY-MM-DD')}
                  disabled
                  fullWidth
                  id={'fechainicio'}
                  label={'Fecha Inicio'}
                  type="date"
                  variant="outlined"
                />
                :
                null
            }
          </Grid>
        </Grid>
      </form>
    );
  };
  
  ViewScheduleForm.propTypes = {
    setOpenDialog: PropTypes.func
  };
  
  export default ViewScheduleForm;