/* eslint-disable react/jsx-key */
/* eslint-disable func-names */
/* eslint-disable radix */
/* eslint-disable no-nested-ternary */
/* eslint-disable react/jsx-props-no-spreading */
import { useEffect, useState } from 'react';
import { Grid, Paper, Button, TextField, FormControl } from '@mui/material';
import { makeStyles } from '@mui/styles';
import { TimePicker } from '@mui/x-date-pickers/TimePicker';
import {
  DataGrid,
  GridEventListener,
  GridColDef,
  GridToolbar,
} from '@mui/x-data-grid';
import Typography from '@mui/material/Typography';
import NumberFormat from 'react-number-format';
import { observer } from 'mobx-react';
import { Draft, draft } from 'mobx-keystone';
import { useTranslation } from 'react-i18next';
import { add } from 'date-fns';
import { getRootStore } from '../../models/root-store';
import TarifRow from '../../models/Application/TarifRow';
import Tarif from '../../models/Application/Tarif';

const useStyles2 = makeStyles({
  content: {
    alignItems: 'center',
  },
  paperInput: {
    backgroundColor: '#666666',
    alignItems: 'center',
    paddingTop: 15,
    padding: 10,
    margin: 3,
    minHeight: 70,
  },
  paperInputRows: {
    backgroundColor: 'lightgrey',
    alignItems: 'center',
    paddingTop: 15,
    padding: 10,
    margin: 3,
    minHeight: 70,
  },
  buttonInput: {
    backgroundColor: '#666666',
    alignItems: 'center',
    justifyContentContent: 'center',
    padding: 12,
    margin: 5,
  },
  title: {
    fontSize: 14,
  },
  typo: {
    marginLeft: 25,
    marginTop: 25,
    marginBottom: 25,
  },
  typoAddTicket: {
    marginLeft: 5,
    marginTop: 10,
    marginBottom: 10,
  },
  label: {
    padding: 15,
  },
  button: {
    padding: 3,
  },
  input: {
    color: 'white',
    fontSize: '1.1em',
    padding: '5px',
    width: 'auto',
  },
  inputLabel: {
    color: 'lightgrey',
    fontSize: '20px',
  },
  inputNumbers: {
    color: 'white',
    fontSize: '1.2em',
    padding: '5px',
    width: 'auto',
  },
  delete: {
    display: 'flex',
    justifyContentContent: 'flex-end',
  },
  buttons: {
    alignItems: 'center',
    alignSelf: 'center',
    textAlign: 'center',
    padding: 0,
    margin: 0,
    minHeight: 0,
  },
  dataGrid: {
    border: 0,
    color: 'white',
  },
  root: {
    flexGrow: 1,
  },
  paper: {
    backgroundColor: '#95A5A6',
    textAlign: 'center',
  },
  paperTop: {
    alignItems: 'center',
    padding: 10,
    marginTop: 15,
    marginBottom: 80,
    margin: 15,
  },
  buttonRow: {
    alignItems: 'center',
    alignSelf: 'center',
    textAlign: 'center',
    padding: 0,
    margin: 0,
    minHeight: 0,
  },
});

interface NumberFormatPriceProps {
  inputRef: (instance: NumberFormat | null) => void;
  onChange: (event: { target: { name: string; value: string } }) => void;
  name: string;
}

function NumberFormatPrice(props: NumberFormatPriceProps) {
  const { inputRef, onChange, ...other } = props;

  return (
    <NumberFormat
      {...other}
      getInputRef={inputRef}
      onValueChange={(values) => {
        onChange({
          target: {
            name: props.name,
            value: values.value,
          },
        });
      }}
      thousandSeparator
      fixedDecimalScale
      decimalScale={2}
      prefix="€"
    />
  );
}

let rowsGlobal: any[] = [];


const msToUtcDurationDate = (ms: number) => {
  const d = new Date(ms || 0);
  const out = new Date(0);
  out.setUTCHours(d.getUTCHours(), d.getUTCMinutes(), 0, 0);
  return out;
};

const utcDurationDateToMs = (d: any, fallbackMs: number) => {
  if (!d) return fallbackMs;
  // MUI adapter may return Dayjs; both have .toDate()
  const date: Date = typeof d?.toDate === 'function' ? d.toDate() : d;
  const out = new Date(0);
  out.setUTCHours(date.getHours(), date.getMinutes(), 0, 0);
  return out.getTime();
};

const TarifGrid = observer(() => {
  const classes = useStyles2();
  const [rows, setRows] = useState<Tarif[]>([]);
  const [selectedRows, setSelectedRows] = useState<any>([]);
  const [editMode, setEditMode] = useState(false);
  const [rootStore] = useState(() => getRootStore());
  const [name, setName] = useState('Tarif');
  const [type, setType] = useState(0);
  const defaultStartDate = new Date();
  const [startDate, setStartDate] = useState<number>(
    defaultStartDate.getTime()
  );
  let defaultEndDate = new Date();
  defaultEndDate.setHours(23);
  defaultEndDate.setMinutes(59);
  defaultEndDate.setSeconds(59);
  defaultEndDate = add(defaultEndDate, {
    years: 10,
  });
  const [endDate, setEndDate] = useState<number>(defaultEndDate.getTime());
  const [startPrice, setStartPrice] = useState<number>(0.0);
  const [maxPrice, setMaxPrice] = useState<number>(0.0);
  const [exitTimeConf, setExitTimeConf] = useState(0);
  const dateValidity = new Date();
  dateValidity.setUTCHours(0, 30, 0, 0);
  const dateValidityRow = new Date();
  dateValidityRow.setUTCHours(1, 0, 0, 0);
  const [exitTime, setExitTime] = useState<number>(dateValidity.getTime());
  const [tarifRows, setTarifRows] = useState<TarifRow[]>([]);
  const [selectedTarifRows, setSelectedTarifRows] = useState<any>([]);
  const [editModeTarifRows, setEditModeTarifRows] = useState(false);

  const [sequence, setSequence] = useState(1);
  const [typeRow, setTypeRow] = useState<string>('Standard');
  const [timeSlot, setTimeSlot] = useState<number>(dateValidityRow.getTime());
  const [repeat, setRepeat] = useState<number>(1);
  const [amount, setAmount] = useState<string>('1.00');

  const [tarifListDraft, setTarifListDraft] = useState<Draft<Tarif>>();
  const [tarifListDraftRowIndex, setTarifListDraftRowIndex] = useState(0);
  const [editId, setEditId] = useState('');

  const [tarifRowDraft, setTarifRowDraft] = useState<any>();
  const [tarifRowDraftRowIndex, setTarifRowDraftRowIndex] = useState(0);
  const [editRowId, setEditRowId] = useState('');
  const [editRowElement, setEditRowElement] = useState(0);
  const [addTarifMode, setAddTarifMode] = useState(false);

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

  const initSequence = () => {
    let highestSequence = 1;
    for (let i = 0; i < rowsGlobal.length; i += 1) {
      if (highestSequence < rowsGlobal[i].sequence) {
        highestSequence = rowsGlobal[i].sequence;
      }
    }
    return highestSequence + 1;
  };

  const checkSequence = (sequenceToCheck: number) => {
    if (
      tarifRows.find(
        (o: { sequence: number }) => o.sequence === sequenceToCheck
      )
    ) {
      return true;
    }
    return false;
  };

  const checkSequenceWithoutElement = () => {
    let result = false;
    for (let i = 0; i < tarifRows.length; i += 1) {
      if (tarifRows[i].id !== editRowId) {
        if (tarifRows[i].sequence === sequence) {
          result = true;
        }
      }
    }
    return result;
  };

  const submit = (e: any) => {
    e.preventDefault();
    rootStore.tarifList.add(
      new Tarif({
        name,
        type,
        startDate,
        endDate,
        startPrice,
        maxPrice,
        exitTimeConf,
        exitTime,
        tarifRows,
      })
    );
    setRows(rootStore.tarifList.all);
    setName('Tarif');
    setType(0);
    setStartDate(defaultStartDate.getTime());
    setEndDate(defaultEndDate.getTime());
    setStartPrice(0.0);
    setMaxPrice(0.0);
    setExitTimeConf(0);
    setExitTime(dateValidity.getTime());
    setTarifRows([]);
    setSelectedRows([]);
    setSelectedTarifRows([]);
  };

  const submitRow = (e: any) => {
    e.preventDefault();
    if (editMode) {
      if (tarifListDraft) {
        tarifListDraft.data.addTarifRow(
          new TarifRow({
            sequence,
            type: typeRow,
            timeSlot,
            repeat,
            amount,
          })
        );
        setSequence(initSequence);
        setTypeRow('Standard');
        setTimeSlot(dateValidityRow.getTime());
        setRepeat(1);
        setAmount('1.00');
        setSelectedTarifRows([]);
        setTarifRows(tarifListDraft.data.all);
        setEditModeTarifRows(false);
      }
    } else {
      if (checkSequence(sequence)) {
        return;
      }
      rowsGlobal = [
        ...tarifRows,
        new TarifRow({
          sequence,
          type: typeRow,
          timeSlot,
          repeat,
          amount,
        }),
      ];
      setTarifRows((localTarifRows) => [
        ...localTarifRows,
        new TarifRow({
          sequence,
          type: typeRow,
          timeSlot,
          repeat,
          amount,
        }),
      ]);
      setSequence(initSequence);
      setTypeRow('Standard');
      setTimeSlot(dateValidityRow.getTime());
      setRepeat(1);
      setAmount('1.00');
      setSelectedTarifRows([]);
      setEditModeTarifRows(false);
    }
  };

  const handleEdit = () => {
    const valuesSelection = selectedRows[0];
    const elementPos = rootStore.tarifList.all
      .map(function (te: Tarif) {
        return te.id;
      })
      .indexOf(valuesSelection);

    const tarifDraft = draft(rootStore.tarifList.tarifs[elementPos]);
    setTarifListDraft(tarifDraft);
    setAddTarifMode(true); // To expand once you select a existing tarif and click change
    setEditMode(true);
    setTarifListDraftRowIndex(elementPos);
    setEditId(tarifDraft.data.allKeystone.id);
    setName(tarifDraft.data.allKeystone.name);
    setType(tarifDraft.data.allKeystone.type);
    setStartDate(tarifDraft.data.allKeystone.startDate);
    setEndDate(tarifDraft.data.allKeystone.endDate);
    setStartPrice(tarifDraft.data.allKeystone.startPrice);
    setMaxPrice(tarifDraft.data.allKeystone.maxPrice);
    setExitTimeConf(tarifDraft.data.allKeystone.exitTimeConf);
    setExitTime(tarifDraft.data.allKeystone.exitTime);
    setTarifRows(tarifDraft.data.all);
  };

  const handleEditRows = () => {
    const valuesSelection = selectedTarifRows[0];

    if (editMode) {
      if (tarifListDraft) {
        const elementPos = tarifListDraft.data.allKeystone.tarifRows
          .map(function (te: TarifRow) {
            return te.id;
          })
          .indexOf(valuesSelection);
        setEditModeTarifRows(true);
        setTarifRowDraftRowIndex(elementPos);
        setEditRowId(tarifListDraft.data.allKeystone.tarifRows[elementPos].id);
        setSequence(
          tarifListDraft.data.allKeystone.tarifRows[elementPos].sequence
        );
        setTypeRow(tarifListDraft.data.allKeystone.tarifRows[elementPos].type);
        setTimeSlot(
          tarifListDraft.data.allKeystone.tarifRows[elementPos].timeSlot
        );
        setRepeat(tarifListDraft.data.allKeystone.tarifRows[elementPos].repeat);
        setAmount(tarifListDraft.data.allKeystone.tarifRows[elementPos].amount);
      }
    } else {
      const elementPosLocal = tarifRows
        .map(function (te: TarifRow) {
          return te.id;
        })
        .indexOf(valuesSelection);
      setEditRowElement(elementPosLocal);
      setEditModeTarifRows(true);
      setEditRowId(tarifRows[elementPosLocal].id);
      setSequence(tarifRows[elementPosLocal].sequence);
      setTimeSlot(tarifRows[elementPosLocal].timeSlot);
      setRepeat(tarifRows[elementPosLocal].repeat);
      setTypeRow(tarifRows[elementPosLocal].type);
    }
  };

  const submitChange = (e: any) => {
    e.preventDefault();
    if (tarifListDraft !== undefined) {
      tarifListDraft.data.change(
        name,
        type,
        startDate,
        endDate,
        startPrice,
        maxPrice,
        exitTimeConf,
        exitTime,
        tarifRows
      );
      tarifListDraft.commit();
      setEditModeTarifRows(false);
      setEditMode(false);
      setEditId('');
      setRows(rootStore.tarifList.all);
      setName('Tarif');
      setType(0);
      setStartDate(defaultStartDate.getTime());
      setEndDate(defaultEndDate.getTime());
      setStartPrice(0.0);
      setMaxPrice(0.0);
      setExitTimeConf(0);
      setExitTime(dateValidity.getTime());
      setTarifRows([]);
    }
  };

  const submitChangeRow = (e: any) => {
    e.preventDefault();
    if (editMode) {
      if (tarifListDraft) {
        tarifListDraft.data.allKeystone.tarifRows[tarifRowDraftRowIndex].change(
          sequence,
          typeRow,
          timeSlot,
          repeat,
          amount
        );
        setEditRowId('');
        setRows(rootStore.tarifList.all);
        setEditModeTarifRows(false);
        setSequence(initSequence);
        setTypeRow('Standard');
        setTimeSlot(dateValidity.getTime());
        setRepeat(1);
        setAmount('1.00');
      }
    } else {
      const currentRow = tarifRows[editRowElement];
      currentRow.change(sequence, typeRow, timeSlot, repeat, amount);
      setEditModeTarifRows(false);
      setEditRowId('');
      setTarifRows(tarifRows);
      setSequence(initSequence);
      setTypeRow('Standard');
      setTimeSlot(dateValidityRow.getTime());
      setRepeat(1);
      setAmount('1.00');
    }
  };

  const cancelChange = () => {
    if (tarifListDraft !== undefined) {
      tarifListDraft.commit();
      setEditId('');
      setRows(rootStore.tarifList.all);
      setName('Tarif');
      setType(0);
      setStartDate(defaultStartDate.getTime());
      setEndDate(defaultEndDate.getTime());
      setStartPrice(0.0);
      setMaxPrice(0.0);
      setExitTimeConf(0);
      setExitTime(dateValidity.getTime());
      setTarifRows([]);
      setEditMode(false);
      setEditModeTarifRows(false);
      setSelectedTarifRows([]);
    }
  };

  const cancelChangeRow = () => {
    if (editMode) {
      setEditModeTarifRows(false);
      setEditRowId('');
      setSequence(initSequence);
      setTypeRow('Standard');
      setTimeSlot(dateValidityRow.getTime());
      setRepeat(1);
      setAmount('1.00');
    } else {
      setEditModeTarifRows(false);
      setEditRowId('');
      setSequence(initSequence);
      setTypeRow('Standard');
      setTimeSlot(dateValidityRow.getTime());
      setRepeat(1);
      setAmount('1.00');
    }
  };
  const resetChange = () => {
    if (tarifListDraft !== undefined) {
      tarifListDraft.reset();
      setEditMode(true);
      setEditId(tarifListDraft.data.allKeystone.id);
      setName(tarifListDraft.data.allKeystone.name);
      setType(tarifListDraft.data.allKeystone.type);
      setStartDate(tarifListDraft.data.allKeystone.startDate);
      setEndDate(tarifListDraft.data.allKeystone.endDate);
      setStartPrice(tarifListDraft.data.allKeystone.startPrice);
      setMaxPrice(tarifListDraft.data.allKeystone.maxPrice);
      setExitTimeConf(tarifListDraft.data.allKeystone.exitTimeConf);
      setExitTime(tarifListDraft.data.allKeystone.exitTime);
      setTarifRows(tarifListDraft.data.allKeystone.tarifRows);
    }
  };

  const resetChangeRow = () => {
    if (editMode) {
      if (tarifListDraft) {
        setEditMode(true);
        setEditRowId(
          tarifListDraft.data.allKeystone.tarifRows[tarifRowDraftRowIndex].id
        );
        setSequence(
          tarifListDraft.data.allKeystone.tarifRows[tarifRowDraftRowIndex]
            .sequence
        );
        setTypeRow(
          tarifListDraft.data.allKeystone.tarifRows[tarifRowDraftRowIndex].type
        );
        setTimeSlot(
          tarifListDraft.data.allKeystone.tarifRows[tarifRowDraftRowIndex]
            .timeSlot
        );
        setRepeat(
          tarifListDraft.data.allKeystone.tarifRows[tarifRowDraftRowIndex]
            .repeat
        );
        setAmount(
          tarifListDraft.data.allKeystone.tarifRows[tarifRowDraftRowIndex]
            .amount
        );
      }
    } else {
      setEditMode(true);
      setSequence(0);
      setTypeRow('Standard');
      setTimeSlot(dateValidityRow.getTime());
      setRepeat(1);
      setAmount('1.00');
    }
  };

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

  const handlePurgeTarifRows = () => {
    if (editMode) {
      if (tarifListDraft) {
        tarifListDraft.data.allKeystone.removeByIds(selectedTarifRows);
        setTarifRows(tarifListDraft.data.all);
        setSelectedTarifRows([]);
      }
    } else {
      setTarifRows(
        tarifRows.filter((item) => selectedTarifRows?.indexOf(item.id) === -1) // 🚀 single line magic
      );
      setSelectedTarifRows([]);
    }
  };
  /*
const handleEvent: GridEventListener<'rowClick'> = (
  params, // GridRowParams
  event, // MuiEvent<React.MouseEvent<HTMLElement>>
  details, // GridCallbackDetails
) => {
  setMessage(`Movie "${params.row.title}" clicked`);
};

  */

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

  const handleSelectionChangeTarifRows: GridEventListener<'rowClick'> = (
    params
  ) => {
    setSelectedTarifRows([params.row.id]);
    if (params.row.length === 0) {
      setEditModeTarifRows(false);
    }
  };

  const { t } = useTranslation();

  const currencyFormatter = new Intl.NumberFormat('be-NL', {
    style: 'currency',
    currency: 'EUR',
  });

  const euroPrice = {
    type: 'number',
    width: 130,
    valueFormatter: ({ value }: any) => currencyFormatter.format(Number(value)),
    cellClassName: 'font-tabular-nums',
  };

  const timeFormatter = new Intl.DateTimeFormat('be-NL', {
    hour: '2-digit',
    minute: '2-digit',
    hour12: false,
    timeZone: 'UTC',
  });

  const minSecTime = {
    type: 'number',
    width: 130,
    valueFormatter: ({ value }: any) => timeFormatter.format(Number(value)),
    cellClassName: 'font-tabular-nums',
  };

  const columns: GridColDef[] = [
    { field: 'name', headerName: t('common.Name'), flex: 1 },
  ];

  const columnsTarifRows: GridColDef[] = [
    { field: 'sequence', headerName: 'Sequence', width: 150 },
    { field: 'amount', ...euroPrice, headerName: 'Price per unit', width: 150 },
    {
      field: 'timeSlot',
      headerName: 'Time in hh:mm',
      ...minSecTime,
      width: 180,
    },
    { field: 'repeat', headerName: 'Repeat', flex: 1 },
  ];

  return (
    <>
      <Grid item xs={12} md={6}>
        <Paper
          elevation={3}
          className={classes.paperTop}
          style={{ background: `${rootStore.settings.backgroundColor}` }}
        >
          <Grid
            item
            xs={12}
            sm={12}
            md={12}
            lg={12}
            className={classes.content}
          >
            <Typography
              className={classes.typoAddTicket}
              style={{ color: rootStore.settings.darkMode ? 'white' : 'black' }}
              variant="h4"
            >
              Tarifs
            </Typography>
          </Grid>
          <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 && !editMode ? (
              <Button
                variant="contained"
                color="primary"
                style={{ backgroundColor: '#f44336', marginTop: 3 }}
                onClick={handlePurge}
              >
                {t('common.Delete-button')}
              </Button>
            ) : null}
            {selectedRows.length === 1 && !editMode ? (
              <Button
                style={{ marginLeft: 20, marginTop: 3 }}
                variant="contained"
                color="primary"
                onClick={handleEdit}
              >
                {t('common.Edit-button')}
              </Button>
            ) : null}
          </Paper>
        </Paper>
      </Grid>
      {/* -----------------------------------------------------------------------   FORM   */}
      <Grid item xs={12} md={6}>
        <Paper
          elevation={3}
          className={classes.paperTop}
          style={{ background: `${rootStore.settings.backgroundColor}` }}
        >
          <Grid container spacing={0}>
            <Grid item xs={10} className={classes.content}>
              <Typography
                className={classes.typoAddTicket}
                style={{
                  color: rootStore.settings.darkMode ? 'white' : 'black',
                  marginTop: 20,
                }}
                variant="h4"
              >
                {editMode
                  ? `Change tarif: ${tarifListDraft?.data.name}`
                  : 'Add a new tarif'}
              </Typography>
            </Grid>
            {editMode ? null : (
              <Button
                className={classes.typoAddTicket}
                variant="contained"
                color="secondary"
                style={{ margin: 20 }}
                onClick={() => setAddTarifMode(!addTarifMode)}
              >
                + add
              </Button>
            )}
            {addTarifMode ? (
              <Grid
                item
                xs={12}
                sm={12}
                md={12}
                lg={12}
                className={classes.content}
              >
                <Grid container spacing={0}>
                  <Grid item xs={12} sm={12} md={12} lg={12}>
                    <Paper className={classes.paperInput}>
                      <form
                        onSubmit={(e) => {
                          submit(e);
                        }}
                      >
                        <TextField
                          label="Name"
                          value={name}
                          placeholder="Name"
                          variant="outlined"
                          fullWidth
                          onChange={(ev) => {
                            setName(ev.target.value || '');
                          }}
                          InputProps={{
                            className: classes.input,
                          }}
                          InputLabelProps={{
                            className: classes.inputLabel,
                          }}
                        />
                      </form>
                    </Paper>
                  </Grid>
                  <Grid item xs={12} sm={12} md={12} lg={12}>
                    <Paper className={classes.paperInput}>
                      <Typography
                        className={classes.content}
                        sx={{ marginTop: -1 }}
                        style={{
                          color: rootStore.settings.darkMode
                            ? 'white'
                            : 'black',
                        }}
                        variant="h6"
                      >
                        Tarif rows
                      </Typography>
                      <Grid
                        item
                        xs={12}
                        style={{
                          height: rootStore.settings.gridHeight,
                          width: '100%',
                        }}
                      >
                        <DataGrid
                          className={classes.dataGrid}
                          rows={tarifRows}
                          columns={columnsTarifRows}
                          onRowClick={handleSelectionChangeTarifRows}
                          components={{
                            Toolbar: GridToolbar,
                          }}
                          sortModel={[
                            {
                              field: 'sequence',
                              sort: 'asc',
                            },
                          ]}
                          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>
                      {selectedTarifRows.length > 0 && !editModeTarifRows ? (
                        <Button
                          variant="contained"
                          color="primary"
                          style={{ backgroundColor: '#f44336', marginTop: 3 }}
                          onClick={handlePurgeTarifRows}
                        >
                          {t('common.Delete-button')}
                        </Button>
                      ) : null}
                      {selectedTarifRows.length === 1 && !editModeTarifRows ? (
                        <Button
                          style={{ marginLeft: 20, marginTop: 3 }}
                          variant="contained"
                          color="primary"
                          onClick={handleEditRows}
                        >
                          {t('common.Edit-button')}
                        </Button>
                      ) : null}
                      {/* -----------------------------------------------------------------------  FORM ROWS   */}
                    </Paper>
                    <Paper className={classes.paperInput}>
                      <Grid item xs={12} md={12}>
                        <Grid container spacing={2}>
                          <Grid
                            item
                            xs={12}
                            sm={12}
                            md={12}
                            lg={12}
                            className={classes.content}
                          >
                            <Typography
                              className={classes.typoAddTicket}
                              variant="h6"
                              sx={{ marginTop: -1 }}
                            >
                              {editModeTarifRows
                                ? tarifListDraft
                                  ? `Change tarif row with sequence: ${tarifListDraft?.data.allKeystone.tarifRows[tarifRowDraftRowIndex].sequence}`
                                  : `Change tarif row with sequence: ${sequence}`
                                : 'Add tarif row'}
                            </Typography>
                          </Grid>
                          <Grid
                            item
                            xs={10}
                            sm={10}
                            md={10}
                            lg={10}
                            className={classes.content}
                          >
                            <Grid container spacing={3}>
                              <Grid item xs={12} sm={12} md={6} lg={3}>
                                <form
                                  onSubmit={(e) => {
                                    submit(e);
                                  }}
                                >
                                  <TextField
                                    label="Sequence"
                                    value={sequence}
                                    placeholder="Sequence"
                                    variant="outlined"
                                    fullWidth
                                    required
                                    helperText={
                                      editModeTarifRows
                                        ? checkSequenceWithoutElement()
                                          ? 'Already used'
                                          : 'OK'
                                        : checkSequence(sequence)
                                        ? 'Already used'
                                        : 'OK'
                                    }
                                    error={
                                      editModeTarifRows
                                        ? checkSequenceWithoutElement()
                                        : checkSequence(sequence)
                                    }
                                    onChange={(ev) => {
                                      setSequence(
                                        parseInt(ev.target.value) ||
                                          initSequence()
                                      );
                                    }}
                                    InputProps={{
                                      className: classes.input,
                                    }}
                                    InputLabelProps={{
                                      className: classes.inputLabel,
                                    }}
                                  />
                                </form>
                              </Grid>
                              <Grid item xs={12} sm={12} md={6} lg={3}>
                                <form
                                  onSubmit={(e) => {
                                    submit(e);
                                  }}
                                >
                                  <TextField
                                    label="Amount"
                                    value={amount}
                                    placeholder="Amount"
                                    variant="outlined"
                                    fullWidth
                                    onChange={(ev) => {
                                      setAmount(ev.target.value || '0.00');
                                    }}
                                    InputProps={{
                                      className: classes.input,
                                    }}
                                    InputLabelProps={{
                                      className: classes.inputLabel,
                                    }}
                                  />
                                </form>
                              </Grid>
                              <Grid item xs={12} sm={12} md={6} lg={4}>
                                <form
                                  onSubmit={(e) => {
                                    submit(e);
                                  }}
                                >
                                  <FormControl fullWidth variant="outlined">
                                    <TimePicker
                                      ampm={false}
                                      minutesStep={1}
                                      value={msToUtcDurationDate(timeSlot)}
                                      onChange={(v: any) => {
                                        setTimeSlot(utcDurationDateToMs(v, dateValidityRow.getTime()));
                                      }}
                                    />
                                  </FormControl>
                                </form>
                              </Grid>
                              <Grid item xs={12} sm={6} md={4} lg={2}>
                                <form
                                  onSubmit={(e) => {
                                    submit(e);
                                  }}
                                >
                                  <TextField
                                    label="Repeat"
                                    value={repeat}
                                    placeholder="Repeat"
                                    variant="outlined"
                                    fullWidth
                                    onChange={(ev) => {
                                      setRepeat(parseInt(ev.target.value));
                                    }}
                                    InputProps={{
                                      className: classes.input,
                                    }}
                                    InputLabelProps={{
                                      className: classes.inputLabel,
                                    }}
                                  />
                                </form>
                              </Grid>
                              <Grid
                                container
                                style={{
                                  marginTop: 20,
                                  marginLeft: 15,
                                  marginBottom: 15,
                                }}
                                className={classes.buttonRow}
                              >
                                {editModeTarifRows ? (
                                  <>
                                    <Grid item className={classes.buttons}>
                                      <Button
                                        variant="contained"
                                        color="secondary"
                                        onClick={submitChangeRow}
                                        style={{ width: 150 }}
                                        disabled={
                                          tarifListDraft?.data.allKeystone
                                            .tarifRows[tarifRowDraftRowIndex]
                                            .sequence === sequence &&
                                          tarifListDraft?.data.allKeystone
                                            .tarifRows[tarifRowDraftRowIndex]
                                            .type === typeRow &&
                                          tarifListDraft?.data.allKeystone
                                            .tarifRows[tarifRowDraftRowIndex]
                                            .timeSlot === timeSlot &&
                                          tarifListDraft?.data.allKeystone
                                            .tarifRows[tarifRowDraftRowIndex]
                                            .repeat === repeat &&
                                          tarifListDraft?.data.allKeystone
                                            .tarifRows[tarifRowDraftRowIndex]
                                            .amount === amount &&
                                          checkSequence(sequence)
                                        }
                                      >
                                        {t('common.Save-button')}
                                      </Button>
                                    </Grid>
                                    <Grid item className={classes.buttons}>
                                      <Button
                                        variant="contained"
                                        color="primary"
                                        onClick={resetChangeRow}
                                        style={{ marginLeft: 40, width: 150 }}
                                        disabled={
                                          tarifListDraft?.data.allKeystone
                                            .tarifRows[tarifRowDraftRowIndex]
                                            .sequence === sequence &&
                                          tarifListDraft?.data.allKeystone
                                            .tarifRows[tarifRowDraftRowIndex]
                                            .type === typeRow &&
                                          tarifListDraft?.data.allKeystone
                                            .tarifRows[tarifRowDraftRowIndex]
                                            .timeSlot === timeSlot &&
                                          tarifListDraft?.data.allKeystone
                                            .tarifRows[tarifRowDraftRowIndex]
                                            .repeat === repeat &&
                                          tarifListDraft?.data.allKeystone
                                            .tarifRows[tarifRowDraftRowIndex]
                                            .amount === amount
                                        }
                                      >
                                        {t('common.Reset-button')}
                                      </Button>
                                    </Grid>
                                    <Grid item className={classes.buttons}>
                                      <Button
                                        variant="contained"
                                        color="primary"
                                        onClick={cancelChangeRow}
                                        style={{
                                          marginLeft: 40,
                                          width: 150,
                                        }}
                                      >
                                        {t('common.Cancel-button')}
                                      </Button>
                                    </Grid>
                                  </>
                                ) : (
                                  <Button
                                    className={classes.typoAddTicket}
                                    variant="contained"
                                    color="secondary"
                                    onClick={submitRow}
                                    sx={{ marginLeft: 1 }}
                                    disabled={checkSequence(sequence)}
                                  >
                                    + add row
                                  </Button>
                                )}
                              </Grid>
                            </Grid>
                          </Grid>
                        </Grid>
                      </Grid>
                      {/* -----------------------------------------------------------------------  END FORM ROWS   */}
                    </Paper>
                    <Grid
                      container
                      style={{ marginTop: 20, marginBottom: 10 }}
                      className={classes.buttonRow}
                    >
                      {editId ? (
                        <>
                          <Grid item className={classes.buttons}>
                            <Button
                              variant="contained"
                              color="secondary"
                              onClick={submitChange}
                              style={{ width: 150 }}
                              disabled={
                                !tarifListDraft?.isDirty &&
                                tarifListDraft?.data.name === name &&
                                tarifListDraft?.data.type === type &&
                                tarifListDraft?.data.startDate === startDate &&
                                tarifListDraft?.data.endDate === endDate &&
                                tarifListDraft?.data.startPrice ===
                                  startPrice &&
                                tarifListDraft?.data.maxPrice === maxPrice &&
                                tarifListDraft?.data.exitTimeConf ===
                                  exitTimeConf &&
                                tarifListDraft?.data.exitTime === exitTime &&
                                tarifListDraft?.data.tarifRows === tarifRows
                              }
                            >
                              {t('common.Save-button')}
                            </Button>
                          </Grid>
                          <Grid item className={classes.buttons}>
                            <Button
                              variant="contained"
                              color="primary"
                              onClick={resetChange}
                              style={{
                                marginLeft: 40,
                                width: 150,
                              }}
                              disabled={
                                !tarifListDraft?.isDirty &&
                                tarifListDraft?.data.name === name &&
                                tarifListDraft?.data.type === type &&
                                tarifListDraft?.data.startDate === startDate &&
                                tarifListDraft?.data.endDate === endDate &&
                                tarifListDraft?.data.startPrice ===
                                  startPrice &&
                                tarifListDraft?.data.maxPrice === maxPrice &&
                                tarifListDraft?.data.exitTimeConf ===
                                  exitTimeConf &&
                                tarifListDraft?.data.exitTime === exitTime &&
                                tarifListDraft?.data.tarifRows === tarifRows
                              }
                            >
                              {t('common.Reset-button')}
                            </Button>
                          </Grid>
                          <Grid item className={classes.buttons}>
                            <Button
                              variant="contained"
                              color="primary"
                              onClick={cancelChange}
                              style={{
                                marginLeft: 40,
                                width: 150,
                              }}
                            >
                              {t('common.Cancel-button')}
                            </Button>
                          </Grid>
                        </>
                      ) : (
                        <Button
                          className={classes.typoAddTicket}
                          variant="contained"
                          color="secondary"
                          style={{ marginTop: 20 }}
                          onClick={submit}
                        >
                          + add tarif
                        </Button>
                      )}
                    </Grid>
                  </Grid>
                </Grid>
              </Grid>
            ) : null}
          </Grid>
        </Paper>
      </Grid>
    </>
  );
});

export default TarifGrid;
