// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

import type { JSXElement } from "@coreai-ds/react-components";
import * as React from 'react';
import { useId } from "@coreai-ds/react-components";
import { useToastController } from "@coreai-ds/react-components";
import { Toast } from "@coreai-ds/react-components";
import { ToastTitle } from "@coreai-ds/react-components";
import { ToastTrigger } from "@coreai-ds/react-components";
import { Link } from "@coreai-ds/react-components";
import { Field } from "@coreai-ds/react-components";
import { SpinButton } from "@coreai-ds/react-components";
import { Toaster } from "@coreai-ds/react-components";
import { Button } from "@coreai-ds/react-components";

export const CustomTimeout = (): JSXElement => {
    const [timeout, setDismissTimeout] = React.useState(1000);
    const toasterId = useId('toaster');
    const { dispatchToast } = useToastController(toasterId);
    const notify = () => dispatchToast(<Toast>
        <ToastTitle action={<ToastTrigger>
              <Link>Dismiss</Link>
            </ToastTrigger>}>
          {timeout >= 0 ? `Custom timeout ${timeout}ms` : `Dismiss manually`}
        </ToastTitle>
      </Toast>, { timeout, intent: 'info' });
    return (<>
      <Field label="Timeout" hint="Timeout is in milliseconds">
        <SpinButton value={timeout} onChange={(e, data) => {
            if (data.value) {
                setDismissTimeout(data.value);
            }
            else if (data.displayValue !== undefined) {
                const newValue = parseFloat(data.displayValue);
                if (!Number.isNaN(newValue)) {
                    setDismissTimeout(newValue);
                }
            }
        }}/>
      </Field>
      <br />
      <Toaster toasterId={toasterId}/>
      <Button onClick={notify}>Make toast</Button>
    </>);
};

export default CustomTimeout;
