/* eslint-disable react/jsx-key */
/* eslint-disable react/jsx-props-no-spreading */
import React, { useEffect, useState } from 'react';
import { Grid, Paper, Button, TextField, Autocomplete } from '@mui/material';
import { makeStyles } from '@mui/styles';
import {
  DataGrid,
  GridEventListener,
  GridColDef,
  GridToolbar,
} from '@mui/x-data-grid';
import Typography from '@mui/material/Typography';
import { observer } from 'mobx-react';
import { draft } from 'mobx-keystone';
import { useTranslation } from 'react-i18next';
import { getRootStore } from '../../models/root-store';
import Template from '../../models/Application/Template';

const useStyles = makeStyles({
  dataGrid: {
    border: 0,
    color: 'white',
  },
  content: {
    alignItems: 'center',
  },
  root: {
    flexGrow: 1,
  },
  paper: {
    backgroundColor: '#95A5A6',
    textAlign: 'center',
  },
  paperInput: {
    alignItems: 'center',
    justifyContentItems: 'baseline',
    padding: 10,
    margin: 10,
    minHeight: 70,
  },
  buttons: {
    alignItems: 'center',
    alignSelf: 'center',
    marginRight: 35,
    padding: 0,
    margin: 0,
    minHeight: 70,
  },
  button: {
    backgroundColor: '#3E3E3E',
    height: '90%',
    width: '90%',
    margin: 25,
    padding: 25,
    textAlign: 'center',
  },
  typo: {
    fontSize: 'auto',
  },
  paperTop: {
    alignItems: 'center',
    padding: 10,
    marginTop: 15,
    margin: 15,
  },
  typoAddTicket: {
    marginLeft: 25,
    marginTop: 10,
    marginBottom: 10,
  },
  input: {
    color: 'white',
    fontSize: '1.1em',
    padding: '5px',
    width: 'auto',
  },
  inputLabel: {
    color: 'lightgrey',
    fontSize: '20px',
  },
});

function TemplateGrid() {
  const { t } = useTranslation();
  const classes = useStyles();
  const [rootStore] = useState(() => getRootStore());
  const [rows, setRows] = useState<Template[]>(rootStore.templateList.all);

  const [selectedRows, setSelectedRows] = useState<any>([]);

  const [newName, setNewName] = useState('Name');
  const [editName, setEditName] = useState('');

  const [newIdTemplate, setNewIdTemplate] = useState('0000');
  const [editIdTemplate, setEditIdTemplate] = useState('0000');

  const [newIdTarif, setNewIdTarif] = useState('0000');
  const [editIdTarif, setEditIdTarif] = useState('0000');

  const [templateListDraft, setTemplateListDraft] = useState<any>();
  const [editId, setEditId] = useState('');
  const [editMode, setEditMode] = useState(false);
  const [templateListDraftRowIndex, setTemplateListDraftRowIndex] = useState(0);

  useEffect(() => {
    if (rows !== rootStore.templateList.all) {
      setRows(rootStore.templateList.all);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [rootStore.templateList]);

  const submit = (e: any) => {
    e.preventDefault();
    if (newName === '') {
      return;
    }
    if (!rootStore.templateList) {
      return;
    }
    rootStore.templateList.add(
      new Template({
        name: newName,
        idTemplate: newIdTemplate,
        idTarif: newIdTarif,
      })
    );
    setRows(rootStore.templateList.all);
    setNewName(t('common.Name'));
    setNewIdTemplate('0000');
  };

  const submitChange = (e: any) => {
    e.preventDefault();
    if (editName === '') {
      return;
    }
    templateListDraft.data.all[templateListDraftRowIndex].change(
      editName,
      editIdTemplate,
      editIdTarif
    );
    templateListDraft.commit();
    setRows(rootStore.templateList.all);
    setEditName(t('common.Name'));
    setEditIdTemplate('0000');
    setEditId('');
    setEditMode(false);
    setEditIdTarif('0000');
  };

  const cancelChange = () => {
    templateListDraft.commit();
    setRows(rootStore.templateList.all);
    setEditName(t('common.Name'));
    setEditIdTemplate('0000');
    setEditId('');
    setEditMode(false);
    setNewIdTarif('0000');
  };

  const resetChange = () => {
    templateListDraft.reset();
    const elementPos = templateListDraft.data.all
      .map(function (u: Template) {
        return u.id;
      })
      .indexOf(editId);
    setEditMode(true);
    setEditIdTemplate(templateListDraft.data.all[elementPos].idTemplate);
    setTemplateListDraftRowIndex(elementPos);
    setEditName(templateListDraft.data.all[elementPos].name);
    setNewIdTarif(templateListDraft.data.all[elementPos].idTarif);
  };

  const handlePurge = () => {
    rootStore.templateList.removeByIds(selectedRows);
    setRows(rootStore.templateList.all);
    setSelectedRows([]);
  };

  const handleEdit = () => {
    const valuesSelection = selectedRows[0];
    const templateDraft = draft(rootStore.templateList);

    setTemplateListDraft(templateDraft);

    const elementPos = templateDraft.data.all
      .map(function (te: Template) {
        return te.id;
      })
      .indexOf(valuesSelection);
    setEditMode(true);
    setTemplateListDraftRowIndex(elementPos);
    setEditId(templateDraft.data.all[elementPos].id);
    setEditName(templateDraft.data.all[elementPos].name);
    setEditIdTemplate(templateDraft.data.all[elementPos].idTemplate);
    setEditIdTarif(templateDraft.data.all[elementPos].idTarif);
  };

  const handleSelectionChange: GridEventListener<'rowClick'> = (params) => {
    setSelectedRows([params.row.id]);
    if (params.row.length === 0) {
      setEditMode(false);
    }
  };

  const handleChangeTarif = (event: any, value: any) => {
    if (value !== null) {
      setEditIdTarif(value.id);
    } else {
      setEditIdTarif('');
    }
  };

  const handleNewTarif = (event: any, value: any) => {
    if (value !== null) {
      setNewIdTarif(value.id);
    } else {
      setNewIdTarif('');
    }
  };

  function getFullName(param: any) {
    return rootStore.tarifList.getTarifNameById(param.value?.toString());
  }
  const columns: GridColDef[] = [
    { field: 'name', headerName: t('common.Name'), flex: 1 },
    {
      field: 'idTemplate',
      headerName: t('templateGrid.Template Id'),
      width: 250,
    },
    {
      field: 'idTarif',
      headerName: 'Tarief',
      width: 250,
      valueGetter: (cellParams3) => getFullName(cellParams3),
    },
  ];

  return (
    <Paper
      elevation={3}
      className={classes.paperTop}
      style={{ background: `${rootStore.settings.backgroundColor}` }}
    >
      <Typography
        className={classes.content}
        style={{ color: rootStore.settings.darkMode ? 'white' : 'black' }}
        variant="h4"
      >
        {t('templateGrid.Title')}
      </Typography>
      <Paper className={classes.paperInput}>
        <Grid container spacing={0}>
          <Grid
            item
            xs={12}
            style={{ height: rootStore.settings.gridHeight, width: '100%' }}
          >
            <DataGrid
              className={classes.dataGrid}
              rows={rows}
              columns={columns}
              onRowClick={handleSelectionChange}
              components={{
                Toolbar: GridToolbar,
              }}
              localeText={{
                columnMenuSortAsc: t('grid.columnMenuSortAsc'),
                columnMenuSortDesc: t('grid.columnMenuSortDesc'),
                columnMenuFilter: t('grid.columnMenuFilter'),
                columnMenuHideColumn: t('grid.columnMenuHideColumn'),
                columnMenuShowColumns: t('grid.columnMenuShowColumns'),
                columnMenuUnsort: t('grid.columnMenuUnsort'),
                noRowsLabel: t('grid.noRowsLabel'),
                footerRowSelected: (count) =>
                  count !== 1
                    ? `${count.toLocaleString()} ${t('grid.rowsSelected')}`
                    : `${count.toLocaleString()} ${t('grid.rowSelected')}`,
              }}
            />
          </Grid>
        </Grid>
        {selectedRows.length > 0 ? (
          <Button
            sx={{ margin: 3, marginLeft: 0 }}
            variant="contained"
            color="primary"
            style={{ backgroundColor: '#f44336' }}
            onClick={handlePurge}
          >
            {t('common.Delete-button')}
          </Button>
        ) : null}
        {selectedRows.length === 1 ? (
          <Button
            sx={{ margin: 3 }}
            style={{ marginLeft: 20 }}
            variant="contained"
            color="primary"
            onClick={handleEdit}
          >
            {t('common.Edit-button')}
          </Button>
        ) : null}
      </Paper>

      <Paper className={classes.paperInput}>
        {editMode ? (
          <Grid container spacing={0}>
            <Grid
              item
              xs={12}
              sm={12}
              md={12}
              lg={12}
              className={classes.content}
            >
              <Typography className={classes.typoAddTicket} variant="h6">
                {t('templateGrid.Modify Template')}
              </Typography>
            </Grid>
            <Grid
              item
              xs={12}
              sm={12}
              md={12}
              lg={12}
              className={classes.content}
            >
              <Grid container spacing={0}>
                <Grid item xs={12} sm={8} lg={4} className={classes.paperInput}>
                  <form
                    onSubmit={(e) => {
                      submit(e);
                    }}
                  >
                    <TextField
                      label={t('common.Name')}
                      value={editName}
                      error={editName === ''}
                      placeholder={t('common.Name')}
                      variant="outlined"
                      fullWidth
                      onChange={(ev) => {
                        setEditName(ev.target.value || '');
                      }}
                      InputProps={{
                        className: classes.input,
                      }}
                      InputLabelProps={{
                        className: classes.inputLabel,
                      }}
                    />
                  </form>
                </Grid>
                <Grid item xs={12} sm={8} lg={4} className={classes.paperInput}>
                  <form
                    onSubmit={(e) => {
                      submit(e);
                    }}
                  >
                    <TextField
                      label={t('templateGrid.Template Id')}
                      value={editIdTemplate}
                      placeholder="000-0000-000"
                      error={editIdTemplate.length !== 4}
                      helperText={
                        editIdTemplate.length !== 4
                          ? t('userGrid.Code to short')
                          : null
                      }
                      variant="outlined"
                      fullWidth
                      onChange={(ev) => {
                        setEditIdTemplate(ev.target.value || '');
                      }}
                      InputProps={{
                        className: classes.input,
                      }}
                      InputLabelProps={{
                        className: classes.inputLabel,
                      }}
                    />
                  </form>
                </Grid>
                <Grid item xs={12} sm={8} lg={4} className={classes.paperInput}>
                  <form
                    onSubmit={(e) => {
                      submit(e);
                    }}
                  >
                    <Autocomplete
                      id="Tarief"
                      value={rootStore.tarifList.getTarifById(editIdTarif)}
                      options={rootStore.tarifList.all}
                      getOptionLabel={(option) => option.name}
                      onChange={handleChangeTarif}
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          label="Tarif"
                          variant="outlined"
                          InputLabelProps={{
                            className: classes.inputLabel,
                          }}
                        />
                      )}
                    />
                  </form>
                </Grid>
                <Grid item xs="auto" sm="auto" className={classes.buttons}>
                  <Button
                    sx={{ margin: 3, marginLeft: 0 }}
                    variant="contained"
                    color="secondary"
                    onClick={submitChange}
                    style={{ width: 150 }}
                  >
                    {t('common.Save-button')}
                  </Button>
                </Grid>
                <Grid item xs="auto" sm="auto" className={classes.buttons}>
                  <Button
                    sx={{ margin: 3 }}
                    variant="contained"
                    color="primary"
                    onClick={resetChange}
                    style={{ marginLeft: 40, width: 150 }}
                  >
                    {t('common.Reset-button')}
                  </Button>
                </Grid>
                <Grid item xs="auto" sm="auto" className={classes.buttons}>
                  <Button
                    sx={{ margin: 3 }}
                    variant="contained"
                    color="primary"
                    onClick={cancelChange}
                    style={{ width: 150 }}
                  >
                    {t('common.Cancel-button')}
                  </Button>
                </Grid>
              </Grid>
            </Grid>
          </Grid>
        ) : (
          <Grid container spacing={0}>
            <Grid
              item
              xs={12}
              sm={12}
              md={12}
              lg={12}
              className={classes.content}
            >
              <Typography className={classes.typoAddTicket} variant="h6">
                {t('templateGrid.Add Template')}:
              </Typography>
            </Grid>
            <Grid container spacing={0}>
              <Grid
                item
                xs={3}
                sm={3}
                md={3}
                lg={3}
                className={classes.paperInput}
              >
                <form
                  onSubmit={(e) => {
                    submit(e);
                  }}
                >
                  <TextField
                    label={t('common.Name')}
                    value={newName}
                    placeholder={t('common.Name')}
                    variant="outlined"
                    error={newName === ''}
                    required
                    fullWidth
                    onChange={(ev) => {
                      setNewName(ev.target.value || '');
                    }}
                    InputProps={{
                      className: classes.input,
                    }}
                    InputLabelProps={{
                      className: classes.inputLabel,
                    }}
                  />
                </form>
              </Grid>
              <Grid
                item
                xs={3}
                sm={3}
                md={3}
                lg={3}
                className={classes.paperInput}
              >
                <form
                  onSubmit={(e) => {
                    submit(e);
                  }}
                >
                  <TextField
                    label={t('templateGrid.Template Id')}
                    value={newIdTemplate}
                    placeholder="000-0000-000"
                    variant="outlined"
                    fullWidth
                    error={newIdTemplate.length < 4}
                    helperText={
                      newIdTemplate.length < 4
                        ? t('userGrid.Code to short')
                        : null
                    }
                    onChange={(ev) => {
                      setNewIdTemplate(ev.target.value || '');
                    }}
                    InputProps={{
                      className: classes.input,
                    }}
                    InputLabelProps={{
                      className: classes.inputLabel,
                    }}
                  />
                </form>
              </Grid>
              <Grid
                item
                xs={3}
                sm={3}
                md={3}
                lg={3}
                className={classes.paperInput}
              >
                <form
                  onSubmit={(e) => {
                    submit(e);
                  }}
                >
                  <Autocomplete
                    id="Tarief"
                    options={rootStore.tarifList.all}
                    getOptionLabel={(option) => option.name}
                    onChange={handleNewTarif}
                    renderInput={(params) => (
                      <TextField
                        {...params}
                        label="Tarif"
                        variant="outlined"
                        InputLabelProps={{
                          className: classes.inputLabel,
                        }}
                      />
                    )}
                  />
                </form>
              </Grid>
              <Grid
                item
                xs={2}
                sm={2}
                md={2}
                lg={2}
                className={classes.buttons}
              >
                <Button
                  sx={{ margin: 3 }}
                  style={{ marginLeft: 10 }}
                  variant="contained"
                  color="secondary"
                  onClick={submit}
                >
                  {t('common.Add-button')}
                </Button>
              </Grid>
            </Grid>
          </Grid>
        )}
      </Paper>
    </Paper>
  );
}

export default observer(TemplateGrid);
