import React, { useCallback, useState } from "react";
import { AlertButton } from "react-native";

import { Button } from "../Button";
import { Modal } from "../Modal";
import { Stack } from "../Stack";
import { Text } from "../Text";
import styles from "./styles";

type AlertOptions = {
  cancelable?: boolean;
  onDismiss?: () => void;
};

let alertPush = null;

export const AlertProvider = () => {
  const [alerts, setAlerts] = useState([]);

  const dismiss = useCallback(
    (alertId) => {
      setAlerts((prevState) => {
        const alertIndex = prevState.findIndex((alert) => alert.id === alertId);
        const alert = prevState[alertIndex];
        if (!alert) return prevState;

        return [
          ...prevState.slice(0, alertIndex),
          { ...alert, dismissed: true },
          ...prevState.slice(alertIndex + 1),
        ];
      });

      setTimeout(() => {
        setAlerts((prevState) => {
          const alertIndex = prevState.findIndex(
            (alert) => alert.id === alertId
          );
          if (alertIndex < 0) return prevState;

          return [
            ...prevState.slice(0, alertIndex),
            ...prevState.slice(alertIndex + 1),
          ];
        });
      }, 500);
    },
    [alerts]
  );

  alertPush = (alert) => {
    setAlerts((prevState) => [...prevState, alert]);
  };

  return (
    <>
      {alerts.map((alert) => (
        <Modal
          key={alert.id}
          contentStyle={styles.modalContent}
          style={styles.modal}
          visible={!alert.dismissed}
          onDismiss={() => dismiss(alert.id)}
        >
          <Stack gap={8}>
            <Text bold={!!alert.message}>{alert.title}</Text>
            {alert.message && <Text>{alert.message}</Text>}
            <Stack inline gap={8} pt={2} justify="center">
              {(alert.buttons || []).map((button) => (
                <Button
                  accessibilityLabel={button.text}
                  accessibilityRole="button"
                  key={button.text}
                  title={button.text}
                  variant={button.style}
                  onPress={() => {
                    dismiss(alert.id);
                    if (button.onPress) {
                      button.onPress();
                    }
                  }}
                />
              ))}
            </Stack>
          </Stack>
        </Modal>
      ))}
    </>
  );
};

export const Alert = {
  alert: (
    title: string,
    message?: string,
    buttons: AlertButton[] = [{ text: "OK" }],
    options: AlertOptions = {}
  ) => {
    if (!alertPush) return;

    alertPush({
      id: new Date().getTime(),
      title,
      message,
      buttons,
      options,
    });
  },
};
