/* eslint-disable no-promise-executor-return */
/* eslint-disable react/jsx-key */
/* eslint-disable react/jsx-props-no-spreading */
/* eslint-disable no-console */
/* eslint-disable radix */
import { useCallback, useState } from 'react';
import { Grid, Paper, TextField, Autocomplete } from '@mui/material';
import { makeStyles } from '@mui/styles';

import Typography from '@mui/material/Typography';

import { observer } from 'mobx-react';
import { useTranslation } from 'react-i18next';
import {
  DataGrid,
  GridColDef,
  GridToolbar,
  GridRowModel,
} from '@mui/x-data-grid';
import { getRootStore } from '../../models/root-store';

const useStyles = makeStyles({
  content: {
    alignItems: 'center',
  },
  dataGrid: {
    border: 0,
    color: 'white',
  },
  root: {
    flexGrow: 1,
  },
  paper: {
    backgroundColor: '#95A5A6',
    textAlign: 'center',
  },
  paperInput: {
    backgroundColor: '#666666',
    alignItems: 'center',
    justifyContentItems: 'baseline',
    padding: 10,
    margin: 10,
    minHeight: 70,
  },
  paperInputNested: {
    backgroundColor: '#7d7d7d',
    alignItems: 'center',
    justifyContentItems: 'baseline',
    padding: 15,
    margin: 10,
    minHeight: 70,
  },
  paperUpdate: {
    backgroundColor: '#EAEAEA',
    alignItems: 'center',
    justifyContentItems: 'baseline',
    padding: 10,
    margin: 10,
    minHeight: 50,
  },
  buttons: {
    backgroundColor: '#666666',
    alignItems: 'center',
    alignSelf: 'center',
    padding: 10,
    margin: 10,
    minHeight: 70,
  },
  gridItemButton: {
    margin: 0,
    padding: 0,
    textAlign: 'center',
  },
  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: 5,
    marginTop: 0,
    marginBottom: 0,
  },
  typoText: {
    textAlign: 'center',
    marginTop: 15,
    marginBottom: 0,
    marginRight: 60,
  },
  input: {
    color: 'white',
    fontSize: '1.1em',
    padding: '5px',
    width: 'auto',
  },
  inputLabel: {
    color: 'black',
    fontSize: '20px',
  },
  inputNumbers: {
    color: 'white',
    fontSize: '1.2em',
    padding: '5px',
    width: 'auto',
  },
  buttonInput: {
    backgroundColor: '#666666',
    alignItems: 'center',
    justifyContentContent: 'center',
    padding: 20,
    marginTop: 20,
    marginLeft: 10,
  },
});

const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

function Languages() {
  const classes = useStyles();
  const [rootStore] = useState(() => getRootStore());
  const { t } = useTranslation();

  const columns: GridColDef[] = [
    { field: 'id', headerName: 'Field name', width: 200 },
    {
      field: 'translation',
      headerName: 'Translation',
      width: 250,
    },
    {
      field: 'customTranslation',
      headerName: 'Custom Translation',
      editable: true,
      width: 300,
      flex: 1,
    },
    {
      field: 'changed',
      type: 'boolean',
      headerName: 'Use custom',
      editable: true,
      width: 150,
    },
    { field: 'occursWhere', headerName: 'Occurs where', width: 250 },
  ];

  const processRowUpdate = useCallback(
    async (newRow: GridRowModel) => {
      // Make the HTTP request to save in the backend or save with mobx
      // customFieldId holds the ID of the selected language
      if (rootStore.languageList.customFieldId === '') {
        // Change the custom translation
        rootStore.languageList.changeSingleCustomTranslation(
          rootStore.languageList.all[0].id,
          newRow.id,
          newRow.customTranslation || ''
        );
        // And change if its been used or not
        rootStore.languageList.changeSingleCustomTranslationUsed(
          rootStore.languageList.all[0].id,
          newRow.id,
          newRow.changed || false
        );
      } else {
        rootStore.languageList.changeSingleCustomTranslation(
          rootStore.languageList.customFieldId,
          newRow.id,
          newRow.customTranslation || ''
        );
        // And change if its been used or not
        rootStore.languageList.changeSingleCustomTranslationUsed(
          rootStore.languageList.customFieldId,
          newRow.id,
          newRow.changed || false
        );
      }
      return newRow;
    },
    [rootStore.languageList]
  );

  const handleProcessRowUpdateError = useCallback((error: Error) => {
    console.log({ children: error.message, severity: 'error' });
  }, []);

  return (
    <Grid container justifyContent="center" spacing={0}>
      <Grid item xs={12} sm={12} md={12} lg={12} xl={12}>
        <Paper
          elevation={3}
          className={classes.paperTop}
          style={{ background: `${rootStore.settings.backgroundColor}` }}
        >
          <Grid item xs={12}>
            <Typography
              style={{
                color: rootStore.settings.darkMode ? 'white' : 'black',
              }}
              className={classes.content}
              variant="h4"
            >
              Languages, translations
            </Typography>
          </Grid>
          <Grid container justifyContent="center" spacing={0}>
            <Grid item xs={12} sm={12} md={12} lg={12} xl={12}>
              <Paper className={classes.paperInput}>
                <br />
                <Autocomplete
                  id="Mode"
                  value={
                    rootStore.languageList.getLanguageById(
                      rootStore.languageList.customFieldId
                    )
                      ? rootStore.languageList.getLanguageById(
                          rootStore.languageList.customFieldId
                        )
                      : rootStore.languageList.all[0]
                  }
                  options={rootStore.languageList.all}
                  getOptionLabel={(option) => option.label}
                  onChange={async (event: any, newValue: any) => {
                    rootStore.languageList.setCustomFieldId(newValue.id);
                  }}
                  disableClearable
                  selectOnFocus
                  clearOnBlur
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      label="Selected language"
                      variant="outlined"
                    />
                  )}
                />
                <br />
                <Grid
                  item
                  xs={12}
                  style={{
                    height: rootStore.settings.gridHeight,
                    width: '100%',
                  }}
                >
                  <DataGrid
                    className={classes.dataGrid}
                    rows={
                      rootStore.languageList.customFieldId === ''
                        ? rootStore.languageList.allFields(
                            rootStore.languageList.all[0].id
                          )
                        : rootStore.languageList.allFields(
                            rootStore.languageList.customFieldId
                          )
                    }
                    components={{
                      Toolbar: GridToolbar,
                    }}
                    columns={columns}
                    sortModel={[
                      {
                        field: 'id',
                        sort: 'asc',
                      },
                    ]}
                    processRowUpdate={processRowUpdate}
                    onProcessRowUpdateError={handleProcessRowUpdateError}
                    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>
              </Paper>
            </Grid>
          </Grid>
        </Paper>
      </Grid>
    </Grid>
  );
}

export default observer(Languages);
