/* eslint-disable react/jsx-props-no-spreading */
/* eslint-disable react/jsx-key */
/* eslint-disable no-nested-ternary */
import React, { useEffect, useState } from 'react';
import {
  Button,
  Grid,
  Paper,
  FormControl,
  Typography,
  TextField,
} from '@mui/material';
import { makeStyles } from '@mui/styles';
import { observer } from 'mobx-react';
import {
  DataGrid,
  GridEventListener,
  GridColDef,
  GridToolbar,
} from '@mui/x-data-grid';
import { useTranslation } from 'react-i18next';
import { TimePicker } from '@mui/x-date-pickers/TimePicker';
import {
  Area,
  AreaChart,
  CartesianGrid,
  Label,
  Line,
  LineChart,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts';
import { getRootStore } from '../../models/root-store';
import Tarif from '../../models/Application/Tarif';

const useStyles = makeStyles({
  content: {
    alignItems: 'center',
  },
  paperTop: {
    alignItems: 'center',
    padding: 10,
    marginTop: 15,
    margin: 15,
  },
  typoAddTicket: {
    marginLeft: 5,
    marginTop: 10,
    marginBottom: 10,
  },
  paperInput: {
    backgroundColor: '#666666',
    alignItems: 'center',
    paddingTop: 15,
    padding: 10,
    margin: 3,
    minHeight: 70,
  },
  dataGrid: {
    border: 0,
    color: 'white',
  },
  inputLabel: {
    color: 'lightgrey',
    fontSize: '20px',
  },
  inputNumbers: {
    color: 'white',
    fontSize: '1.2em',
    padding: '5px',
    width: 'auto',
  },
});

const Simulator = observer(() => {
  const classes = useStyles();
  const { t } = useTranslation();
  const [rootStore] = useState(() => getRootStore());
  const [data, setData] = React.useState('No ticket scanned');
  const [rows, setRows] = useState<Tarif[]>([]);
  const [selectedRows, setSelectedRows] = useState<any>([]);
  const [tarifListPosition, setTarifListPosition] = useState<number>(0);
  const [tarifId, setTarifId] = useState<string>('');
  const [tarif, setTarif] = useState<Tarif>();
  const [tarifRows, setTarifRows] = useState<any[]>();
  const [simulateMode, setSimulateMode] = useState<boolean>(false);
  const dateValidity = new Date();
  dateValidity.setHours(0);
  dateValidity.setMinutes(30);
  dateValidity.setSeconds(0);
  const [timeInPark, setTimeInPark] = useState(dateValidity);
  const [fullScreen, setFullScreen] = useState<boolean>(false);
  const [simulatorSize, setSimulatorSize] = useState(6);
  const [simulationMode, setSimulationMode] = useState<string>('');

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

  const submit = (e: any) => {
    e.preventDefault();
  };

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

  const handleButtonSimulate = () => {
    const valuesSelection = selectedRows[0];
    const elementPos = rootStore.tarifList.all
      .map(function (te: Tarif) {
        return te.id;
      })
      .indexOf(valuesSelection);
    setTarifListPosition(elementPos);
    setTarifId(rootStore.tarifList.tarifs[elementPos].id);
    setTarif(rootStore.tarifList.tarifs[elementPos]);
    setTarifRows(rootStore.tarifList.tarifs[elementPos].allPerHalfHour);
    setSimulationMode('for 24 hours with 30 minutes intervals.');
    // setSimulateMode(!simulateMode);
  };

  const handleButtonSimulateMinute = () => {
    const valuesSelection = selectedRows[0];
    const elementPos = rootStore.tarifList.all
      .map(function (te: Tarif) {
        return te.id;
      })
      .indexOf(valuesSelection);
    setTarifListPosition(elementPos);
    setTarifId(rootStore.tarifList.tarifs[elementPos].id);
    setTarif(rootStore.tarifList.tarifs[elementPos]);
    setTarifRows(rootStore.tarifList.tarifs[elementPos].allPerMinute);
    setSimulationMode('for 24 hours with 1 minute intervals.');
    // setSimulateMode(!simulateMode);
  };

  const handleButtonSimulateSecond = () => {
    const valuesSelection = selectedRows[0];
    const elementPos = rootStore.tarifList.all
      .map(function (te: Tarif) {
        return te.id;
      })
      .indexOf(valuesSelection);
    setTarifListPosition(elementPos);
    setTarifId(rootStore.tarifList.tarifs[elementPos].id);
    setTarif(rootStore.tarifList.tarifs[elementPos]);
    setTarifRows(rootStore.tarifList.tarifs[elementPos].allPerSecond);
    setSimulationMode('for 2 hours with 1 second intervals.');
  };

  const handleButtonSimulateDays = () => {
    const valuesSelection = selectedRows[0];
    const elementPos = rootStore.tarifList.all
      .map(function (te: Tarif) {
        return te.id;
      })
      .indexOf(valuesSelection);
    setTarifListPosition(elementPos);
    setTarifId(rootStore.tarifList.tarifs[elementPos].id);
    setTarif(rootStore.tarifList.tarifs[elementPos]);
    setTarifRows(rootStore.tarifList.tarifs[elementPos].allPerDay);
    setSimulationMode('for 7 days with 1 hour intervals.');
    // setSimulateMode(!simulateMode);
  };

  const handleButtonFullScreen = () => {
    setFullScreen(!fullScreen);
  };

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

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

  const timeFormatter = new Intl.DateTimeFormat('be-NL', { 
    hour: 'numeric',
    minute: 'numeric',
  });

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

  const columns: GridColDef[] = [
    { field: 'name', headerName: t('common.Name'), width: 200 },
    {
      field: 'startPrice',
      ...euroPrice,
      headerName: 'Start price',
      width: 120,
    },
    { field: 'maxPrice', ...euroPrice, headerName: 'Max price', width: 120 },
    {
      field: 'exitTime',
      ...minSecTime,
      headerName: 'Exit time',
      width: 120,
    },
  ];

  return (
    <Grid container justifyContent="center" spacing={0}>
      <Grid item xs={12} md={12} lg={fullScreen === true ? 12 : 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 ? (
              <>
                <Button
                  sx={{ marginTop: 3 }}
                  variant="contained"
                  color="primary"
                  onClick={handleButtonSimulateDays}
                >
                  7Days / 60Min
                </Button>
                <Button
                  sx={{ marginTop: 3 }}
                  style={{ marginLeft: 20 }}
                  variant="contained"
                  color="primary"
                  onClick={handleButtonSimulate}
                >
                  24Hour / 30Min
                </Button>
                <Button
                  sx={{ marginTop: 3 }}
                  style={{ marginLeft: 20 }}
                  variant="contained"
                  color="primary"
                  onClick={handleButtonSimulateMinute}
                >
                  24Hour / 1Min
                </Button>
                <Button
                  sx={{ marginTop: 3 }}
                  style={{ marginLeft: 20 }}
                  variant="contained"
                  color="primary"
                  onClick={handleButtonSimulateSecond}
                >
                  2Hour / 1Sec
                </Button>
              </>
            ) : null}
          </Paper>
          {simulateMode ? (
            <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">
                      Time in parking
                    </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={4} lg={2}>
                        <form
                          onSubmit={(e) => {
                            submit(e);
                          }}
                        >
                          <FormControl fullWidth variant="outlined">
                            <TimePicker
                              ampm={false}
                              value={timeInPark}
                              onChange={(e: any) => {
                                setTimeInPark(e || dateValidity);
                              }}
                            />
                          </FormControl>
                        </form>
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              </Grid>
            </Paper>
          ) : null}
        </Paper>
      </Grid>
      <Grid item xs={12} md={12} lg={fullScreen === true ? 12 : 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}
          >
            {tarifRows ? (
              <Typography
                className={classes.typoAddTicket}
                style={{
                  color: rootStore.settings.darkMode ? 'white' : 'black',
                }}
                variant="h4"
              >
                Simulating tarif: {tarif?.name} {simulationMode}
              </Typography>
            ) : (
              <Typography
                className={classes.typoAddTicket}
                style={{
                  color: rootStore.settings.darkMode ? 'white' : 'black',
                }}
                variant="h4"
              >
                Simulator
              </Typography>
            )}
          </Grid>
          <Paper className={classes.paperInput}>
            <Grid
              container
              spacing={0}
              direction="row"
              justifyContent="center"
              alignItems="center"
            >
              {tarifRows ? (
                <>
                  <AreaChart
                    width={fullScreen === true ? 1400 : 650}
                    height={300}
                    data={tarifRows}
                    margin={{ top: 10, right: 30, left: 30, bottom: 25 }}
                  >
                    <defs>
                      <linearGradient id="price" x1="0" y1="0" x2="0" y2="1">
                        <stop
                          offset="5%"
                          stopColor="#8884d8"
                          stopOpacity={0.8}
                        />
                        <stop
                          offset="95%"
                          stopColor="#8884d8"
                          stopOpacity={0}
                        />
                      </linearGradient>
                    </defs>
                    <XAxis stroke="#FFFFFF" dataKey="time">
                      <Label
                        value={
                          simulationMode === 'for 7 days with 1 hour intervals.'
                            ? 'Time in DD:HH:MM (Day, hours, minutes)'
                            : simulationMode ===
                              'for 2 hours with 1 second intervals.'
                            ? 'Time in HH:MM:SS (Hours, minutes, seconds)'
                            : 'Time in HH:MM (Hours, minutes)'
                        }
                        offset={-20}
                        position="insideBottom"
                      />
                    </XAxis>
                    <YAxis stroke="#FFFFFF" unit="€" dataKey="price">
                      <Label value="Price" offset={-25} position="insideLeft" />
                    </YAxis>
                    <CartesianGrid strokeDasharray="3 3" />
                    <Tooltip />
                    <Area
                      type="stepBefore"
                      dataKey="price"
                      stroke="#8884d8"
                      fillOpacity={1}
                      fill="url(#price)"
                    />
                  </AreaChart>
                  <Button
                    sx={{ marginTop: 3 }}
                    variant="contained"
                    color="primary"
                    onClick={handleButtonFullScreen}
                    style={{ marginBottom: 50 }}
                  >
                    {fullScreen ? 'CLOSE FULLSCREEN' : 'FULL SCREEN'}
                  </Button>
                </>
              ) : (
                <Typography
                  className={classes.typoAddTicket}
                  style={{
                    color: rootStore.settings.darkMode ? 'white' : 'black',
                    paddingTop: 10,
                  }}
                  variant="body1"
                >
                  Please select a tarif to simulate
                </Typography>
              )}
            </Grid>
          </Paper>
        </Paper>
      </Grid>
    </Grid>
  );
});

export default Simulator;
