import React, { useEffect, useMemo, useState } from 'react';
import { Trans, msg } from '@lingui/macro';
import { useLingui } from '@lingui/react';
import type { MessageDescriptor } from '@lingui/core';

import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
import TextField from '@mui/material/TextField';
import styled from 'styled-components';
import ConfirmationDialog from './ConfirmationDialog';

const LocalDialog = styled(Dialog)`
  .MuiPaper-root {
    min-width: 22rem;
  }
`;

function containsForbiddenChars(input: string): boolean {
  const forbidden = /[§$%&\\/=€'´"*~;:]/;
  return forbidden.test(input);
}

type PromptDialogProps = {
  open: boolean;
  title: MessageDescriptor;
  text?: MessageDescriptor;
  label: MessageDescriptor;
  initialValue?: string;
  handleCancel: () => void;
  handleOk: (value: string) => void;
};

type CloseReason = 'escapeKeyDown' | 'backdropClick' | 'cancelButton';

export default function PromptDialog({
  title,
  text,
  open,
  initialValue = '',
  label,
  handleCancel,
  handleOk,
}: PromptDialogProps) {
  const { i18n } = useLingui();
  const [value, setValue] = useState(initialValue);
  const [confirmCloseOpen, setConfirmCloseOpen] = useState(false);

  useEffect(() => {
    if (open) setValue(initialValue);
  }, [open, initialValue]);

  const trimmed = useMemo(() => value.trim(), [value]);
  const hasSpecial = useMemo(() => containsForbiddenChars(value), [value]);
  const okDisabled = trimmed.length === 0 || hasSpecial;

  const handlePromptClose = (_event?: unknown, reason?: CloseReason) => {
    const isCloseAttempt = 
      reason === 'escapeKeyDown' || 
      reason === 'backdropClick'||
      reason === 'cancelButton';

    if (isCloseAttempt && trimmed.length > 0) {
      setConfirmCloseOpen(true);
      return;
    }

    handleCancel();
  };

  return (
    <>
      <LocalDialog open={open} onClose={handlePromptClose}>
        <DialogTitle>{i18n._(title)}</DialogTitle>

        <DialogContent>
          {!!text && <DialogContentText>{i18n._(text)}</DialogContentText>}

          {hasSpecial && (
            <DialogContentText sx={{ mt: 0.5 }}>
              <Trans>
                Folgende Sonderzeichen sind nicht erlaubt: <br></br>
              </Trans>
                § $ % & \\ / = € ' ´ \" * ~ ; : 
            </DialogContentText>
          )}

          <TextField
            autoFocus
            fullWidth
            sx={{ mt: 1 }}
            value={value}
            onChange={(e) => setValue(e.target.value)}
            onKeyDown={(e) => {
              if (e.key === 'Enter' && !okDisabled) {
                e.preventDefault();
                handleOk(trimmed);
              }
            }}
            error={hasSpecial}
            label={i18n._(label)}
            helperText={hasSpecial ? i18n._(msg`Keine Sonderzeichen erlaubt`) : ' '}
          />
        </DialogContent>

        <DialogActions>
          <Button onClick={() => handlePromptClose(undefined, 'cancelButton')}>
            <Trans>Cancel</Trans>
          </Button>
          <Button onClick={() => handleOk(trimmed)} disabled={okDisabled} autoFocus>
            <Trans>OK</Trans>
          </Button>
        </DialogActions>
      </LocalDialog>
      <ConfirmationDialog
        open={confirmCloseOpen}
        title={i18n._(msg`Wirklich schließen?`)}
        text={i18n._(msg`Nicht gespeicherte Änderungen gehen verloren.`)}
        handleClose={() => setConfirmCloseOpen(false)}
        handleNotConfirmed={() => setConfirmCloseOpen(false)}
        handleConfirmed={() => {
          setConfirmCloseOpen(false);
          handleCancel();
        }}
      />
    </>
  );
}
