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

import type { JSXElement } from "@coreai-ds/react-components";
import { useId } from "@coreai-ds/react-components";
import * as React from 'react';
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 { ToastBody } from "@coreai-ds/react-components";
import { Text } from "@coreai-ds/react-components";
import { ProgressBar } from "@coreai-ds/react-components";
import { ToastFooter } from "@coreai-ds/react-components";
import { Toaster } from "@coreai-ds/react-components";
import { Button } from "@coreai-ds/react-components";

const intervalIncrement = 5;

const intervalDelay = 100;

const DownloadProgressBar: React.FC<{
    onDownloadEnd: () => void;
}> = ({ onDownloadEnd }) => {
    const [value, setValue] = React.useState(100);
    // This effect simulates progress value based on state/remote data
    React.useEffect(() => {
        if (value > 0) {
            const timeout = setTimeout(() => {
                setValue(v => Math.max(v - intervalIncrement, 0));
            }, intervalDelay);
            return () => clearTimeout(timeout);
        }
        if (value === 0) {
            onDownloadEnd();
        }
    }, [value, onDownloadEnd]);
    return <ProgressBar value={value} max={100}/>;
};

export const ProgressToast = (): JSXElement => {
    const toasterId = useId('toaster');
    const toastId = useId('toast');
    const [unmounted, setUnmounted] = React.useState(true);
    const { dispatchToast, dismissToast } = useToastController(toasterId);
    const dismiss = React.useCallback(() => dismissToast(toastId), [dismissToast, toastId]);
    const notify = () => dispatchToast(<Toast>
        <ToastTitle action={<ToastTrigger>
              <Link>Dismiss</Link>
            </ToastTrigger>}>
          Downloading file
        </ToastTitle>
        <ToastBody>
          <Text>This may take a while</Text>
          <DownloadProgressBar onDownloadEnd={dismiss}/>
        </ToastBody>
        <ToastFooter>
          <Link>Action</Link>
          <Link>Action</Link>
        </ToastFooter>
      </Toast>, {
        intent: 'success',
        timeout: -1,
        toastId,
        onStatusChange: (e, { status }) => setUnmounted(status === 'unmounted'),
    });
    return (<>
      <Toaster toasterId={toasterId}/>
      <Button disabledFocusable={!unmounted} onClick={notify}>
        Make toast
      </Button>
    </>);
};

export default ProgressToast;
