import { ErrorOutline, CheckmarkFilled } from "@carbon/icons-react";
import { noop } from "@greatness/util";

import { cn } from "@/util/cn";

import { createContext, useContext, useState } from "react";

interface IAlert {
  message?: string;
  severity?: "success" | "error";
  title?: string;
}

interface IAlertState {
  addAlert: (alert: IAlert) => void;
  alerts: IAlert[];
}

const AlertContext = createContext<IAlertState>({
  addAlert: noop,
  alerts: [],
});

export const useAlert = (): IAlertState => useContext(AlertContext);

export default function AlertProvider({
  children,
}: React.PropsWithChildren) {
  const [alerts, setAlerts] = useState<IAlert[]>([]);

  const dismissAlert = (alertToDismiss: IAlert) =>
    setAlerts((currentAlerts) =>
      currentAlerts.filter((currentAlert) => currentAlert !== alertToDismiss),
    );

  const addAlert = (alert: IAlert) => {
    setAlerts((prev) => {
      setTimeout(() => dismissAlert(alert), 10000); // 10 sec alert for now
      return [...prev, alert];
    });
  };

  return (
    <AlertContext.Provider value={{ addAlert, alerts }}>
      {children}
      <div className="fixed top-0 right-4 top-4 z-50">
        {alerts.map((alert, idx) => (
          <div
            role="presentation"
            key={[alert.title, idx].join("-")}
            onClick={() => dismissAlert(alert)}
            className={cn("flex items-center justify-between bg-black text-white border-white p-2 cursor-pointer", {
              "bg-green-500": alert.severity === "success",
              "bg-red-500": alert.severity === "error",
            })}
          >
            <div className="flex items-center justify-center w-6 h-6">
              {alert.severity === "error" ? (
                <ErrorOutline />
              ) : (
                <CheckmarkFilled />
              )}
            </div>
            <div className="flex flex-col">
              {alert.title && (
                <span className="text-xs font-medium">{alert.title}</span>
              )}
              <span className="text-xs">{alert.message}</span>
            </div>
            {/* <div className="flex items-center justify-center w-6 h-6">
              <Exit />
            </div> */}
          </div>
        ))}
      </div>
    </AlertContext.Provider>
  );
}
