import React, { useState } from "react";

import theme from "mazlo-theme";

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

type Props = {
  children: React.ReactNode;
  onConfirm?: () => void;
  onDismiss: () => void;
  visible: boolean;
};

const Dialog = ({ children, onConfirm, onDismiss, visible }: Props) => (
  <Modal visible={visible} contentStyle={styles.content}>
    <Button style={styles.closeButton} onPress={onDismiss}>
      <Icon name="close" color={theme.colors.icon.light} />
    </Button>
    {typeof children === "string" ? <Text>{children}</Text> : children}
    <View style={styles.buttons}>
      <Button style={styles.button} onPress={onDismiss} title="Cancel" />
      <Button
        style={styles.button}
        variant="primary"
        onPress={onConfirm || onDismiss}
        title="OK"
      />
    </View>
  </Modal>
);

export const useConfirm = () => {
  const [message, setMessage] = useState<{
    children: React.ReactNode;
    resolve: (result: boolean) => void;
  }>();
  return {
    confirm: (children: React.ReactNode) =>
      new Promise((resolvePromise) => {
        setMessage({
          children,
          resolve: (value: boolean) => {
            setMessage(null);
            resolvePromise(value);
          },
        });
      }),
    dialog: (
      <Dialog
        visible={!!message}
        onConfirm={() => message.resolve(true)}
        onDismiss={() => message.resolve(false)}
      >
        {message?.children}
      </Dialog>
    ),
  };
};

export default Dialog;
