"use client";

import React, { useEffect, useState } from "react";
import type { NotificationProvider } from "@refinedev/core";
import { useSnackbar } from "@refinedev/mui";
import UndoOutlined from "@mui/icons-material/UndoOutlined";
import Box from "@mui/material/Box";
import CircularProgress from "@mui/material/CircularProgress";
import IconButton from "@mui/material/IconButton";
import Typography from "@mui/material/Typography";

type ProgressNotificationProps = {
  undoableTimeout: number;
  message: string;
};

const ProgressNotification = ({
  undoableTimeout,
  message,
}: ProgressNotificationProps) => {
  const [progress, setProgress] = useState(100);
  const [timeCount, setTimeCount] = useState(undoableTimeout);

  useEffect(() => {
    if (undoableTimeout <= 0 || timeCount <= 0) {
      return;
    }

    const progressStep = 100 / undoableTimeout;
    const timer = window.setInterval(() => {
      setTimeCount((previous) => Math.max(previous - 1, 0));
      setProgress((previous) => Math.max(previous - progressStep, 0));
    }, 1000);

    return () => {
      window.clearInterval(timer);
    };
  }, [timeCount, undoableTimeout]);

  return (
    <>
      <Box sx={{ position: "relative", display: "inline-flex" }}>
        <CircularProgress
          color="inherit"
          variant="determinate"
          value={progress}
        />
        <Box
          sx={{
            top: 0,
            left: 0,
            bottom: 0,
            right: 0,
            position: "absolute",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <Typography component="div">{timeCount}</Typography>
        </Box>
      </Box>
      <Box
        sx={{
          marginLeft: "10px",
          maxWidth: { xs: "150px", md: "100%" },
        }}
      >
        <Typography variant="subtitle2">{message}</Typography>
      </Box>
    </>
  );
};

export const useAppNotificationProvider = (): NotificationProvider => {
  const { closeSnackbar, enqueueSnackbar } = useSnackbar();

  return {
    open: ({
      message,
      type,
      undoableTimeout,
      key,
      cancelMutation,
      description,
    }) => {
      if (type === "progress") {
        const options: NonNullable<Parameters<typeof enqueueSnackbar>[1]> = {
          preventDuplicate: true,
          key,
          autoHideDuration: (undoableTimeout ?? 0) * 1000,
        };

        if (cancelMutation) {
          options.action = (snackbarKey) => (
            <IconButton
              onClick={() => {
                cancelMutation();
                closeSnackbar(snackbarKey);
              }}
              color="inherit"
            >
              <UndoOutlined />
            </IconButton>
          );
        }

        enqueueSnackbar(
          <ProgressNotification
            undoableTimeout={undoableTimeout ?? 0}
            message={message}
          />,
          options,
        );
        return;
      }

      enqueueSnackbar(
        <Box>
          <Typography variant="subtitle2" component="h6">
            {description}
          </Typography>
          <Typography variant="caption" component="p">
            {message}
          </Typography>
        </Box>,
        {
          key,
          variant: type,
        },
      );
    },
    close: (key) => {
      closeSnackbar(key);
    },
  };
};
