import React, { useState } from "react";
import { Alert, Platform, View, Text } from "react-native";
import { PortalProvider } from "@gorhom/portal";

import { Fonts, Style, gutters } from "../styles";

import Overlay from "./Overlay";
import Button from "./Button";

const WebAlertModal = ({ title, description, options }) => {
  const [visible, setVisible] = useState(true);

  const confirmOption = options?.find(({ style }) => style !== "cancel");
  const cancelOption = options?.find(({ style }) => style === "cancel");

  const onConfirm = () => {
    setVisible(false);
    confirmOption?.onPress();
  };

  const onCancel = () => {
    setVisible(false);
    cancelOption?.onPress();
  };

  return (
    <PortalProvider>
      <Overlay isVisible={visible}>
        <View
          style={{
            ...Style.containerModal,
          }}
        >
          <Text
            style={{
              ...Fonts({
                type: "mainTitle",
                style: {
                  textAlign: "center",
                  marginBottom: gutters / 2,
                },
              }),
            }}
          >
            {title}
          </Text>
          <Text
            style={{
              ...Fonts({
                type: "default",
                style: {
                  textAlign: "center",
                  marginBottom: gutters / 2,
                },
              }),
            }}
          >
            {description}
          </Text>

          <Button
            text={confirmOption?.text || "OK"}
            onPress={onConfirm}
            alternateAction={
              cancelOption
                ? {
                    text: cancelOption.text,
                    onPress: () => onCancel(),
                  }
                : null
            }
          />
        </View>
      </Overlay>
    </PortalProvider>
  );
};

const alertPolyfill = (title, description, options, extra) => {
  const rootDiv = document.createElement("div");
  document.body.appendChild(rootDiv);

  const closeModal = () => {
    document.body.removeChild(rootDiv);
  };

  const WebAlertComponent = () => (
    <WebAlertModal
      title={title}
      description={description}
      options={options}
      onDismiss={closeModal}
    />
  );

  // Render the React component into the div
  require("react-dom").render(<WebAlertComponent />, rootDiv);
};

const customAlert = (title, description, options, extra) => {
  // Utilisation de la propriété userInterfaceStyle pour le mettre en mode sombre
  Alert.alert(title, description, options, {
    ...extra,
    userInterfaceStyle: "dark",
  });
};

const alert = Platform.OS === "web" ? alertPolyfill : customAlert;

export default alert;
