
// original path: resources\assets\ts\DataPage\CloneTaskDialog.tsx
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Checkbox from '@mui/material/Checkbox';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogTitle from '@mui/material/DialogTitle';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormGroup from '@mui/material/FormGroup';
import { RootState } from '../../../DataPage/rootReducer';
import { Trans } from '@lingui/macro';
import {
  check,
  checkAll,
  clonesSelector,
  closeCloneDialog,
  submit,
  setBatchCount,
  reset,
  setReservation
} from '../../../DataPage/cloneTaskSlice';
import { useDispatch, useSelector } from 'react-redux';
import React, { useEffect, useState } from 'react';
import axios from 'B/axios';
import styled from 'styled-components';
import { fetchAll } from '../../../DataPage/dataSlice';

export default function CloneTaskDialog() {
  const d = useDispatch();
  const clones = useSelector((s: RootState) => clonesSelector.selectAll(s));
  const cloneState = useSelector((s: RootState) => s.clones);
  const open = useSelector((s: RootState) => s.clones.open);
  const [isReservation, setIsReservation] = useState(false);
  const [idAddManyOpen, setAddManyOpen] = useState([]);

  const handleClose = () => {
    d(closeCloneDialog());
  };

  const handleChange = (e) => {
    const id = e.target.name;
    const checked = e.target.checked;
    d(check({ id, checked }));
  };

  const handleAllCheck = () => {
    d(checkAll());
  };

  const handleSubmit = () => {
    d(submit()).then(() => {
      d(reset());
      setTimeout(() => {
        d(fetchAll());
      }, 1500);
    });
  };

  const handleClickAddMany = (agb_id) => {
    d(check({ id: agb_id, checked: true }));
  };

  const isChecked = (agb_id) => {
    return cloneState.checked[agb_id] || false;
  };

  useEffect(() => {
    if (open === false) return;
    axios.get('/checks/kurs-reservierung').then((res) => {
      const isReservation: boolean = res.data.isReservation;
      d(setReservation(isReservation));
      setIsReservation(isReservation);
    });
  }, [d, open]);

  return (
    <Dialog onClose={handleClose} open={open}>
      <DialogTitle>
        <Trans>Create a new task</Trans>
      </DialogTitle>
      <DialogContent>
        <FormGroup>
          <FormControlLabel
            control={<Checkbox name={'all'} onClick={handleAllCheck} />}
            label={<Trans>All</Trans>}
          />

          {clones.map((c) => (
            <Box key={c.agb_id}>
              <FormControlLabel
                control={
                  <Checkbox
                    checked={isChecked(c.agb_id)}
                    name={c.agb_id.toString()}
                    onChange={handleChange}
                  />
                }
                label={c.agb_name}
              />

              {isReservation && (
                <Box>
                  <CreateManyView
                    agbID={c.agb_id}
                    isOpen={cloneState.checked[c.agb_id]}
                    handleFormSubmit={handleSubmit}
                  />
                </Box>
              )}
            </Box>
          ))}
        </FormGroup>
      </DialogContent>
      <DialogActions>
        <Button onClick={handleClose}>
          <Trans>Cancel</Trans>
        </Button>
        <Button onClick={handleSubmit}>
          <Trans>Create</Trans>
        </Button>
      </DialogActions>
    </Dialog>
  );
}

const CreateManyViewStyled = styled.div`
  max-height: ${(props: { isOpen: boolean }) => (props.isOpen ? '4rem' : '0')};
  overflow: hidden;
  transition: max-height 250ms ease;
`;
const CreateManyView = ({ agbID, isOpen, handleFormSubmit }) => {
  const cloneStateBatchCount = useSelector(
    (s: RootState) => s.clones.batchCount
  );
  const d = useDispatch();
  const handleCountChange = (e) => {
    d(setBatchCount({ agbID, count: Number(e.target.value) }));
  };
  const handleSubmit = (e) => {
    e.preventDefault();
    handleFormSubmit();
  };

  const value = cloneStateBatchCount[agbID] || '';
  return (
    <CreateManyViewStyled isOpen={isOpen}>
      <form onSubmit={handleSubmit}>
        <label>
          <span style={{ fontWeight: 'bold' }}>
            <Trans>Add Many</Trans>
          </span>
          <input
            type='number'
            step='any'
            style={{ width: '100%' }}
            value={value}
            onChange={handleCountChange}
          />
        </label>
      </form>
    </CreateManyViewStyled>
  );
};
