import {
  EmbeddedCheckoutProvider,
  EmbeddedCheckout,
} from "@stripe/react-stripe-js";
import { useState, createContext } from "react";
import { View, StyleSheet } from "react-native";

import { loadStripe } from "@stripe/stripe-js";

import {
  STRIPE_PUBLISHABLE_KEY_LIVE,
  STRIPE_PUBLISHABLE_KEY_TEST,
} from "../data/keys";
import { mainBorderRadius } from "../styles/Style";
import Overlay from "../components/Overlay";
import Button from "../components/Button";
import useLayoutType from "../hooks/useLayoutType";

const isStripeTesting = false;
const stripePromise = loadStripe(
  isStripeTesting ? STRIPE_PUBLISHABLE_KEY_TEST : STRIPE_PUBLISHABLE_KEY_LIVE
);

export const StripeEmbeddedContext = createContext();

export default ({ children }) => {
  const { isMobile } = useLayoutType();

  const [clientSecret, setClientSecret] = useState(null);

  return (
    <StripeEmbeddedContext.Provider value={{ setClientSecret }}>
      {children}
      <Overlay
        isVisible={clientSecret !== null}
        setIsVisible={() => setClientSecret(null)}
      >
        <View
          style={{
            position: "absolute",
            ...StyleSheet.absoluteFillObject,
            justifyContent: "center",
            alignItems: "center",
          }}
        >
          <View
            style={{
              alignSelf: "center",
              width: isMobile ? "90%" : "80%",
              height: "70vh",
              borderRadius: mainBorderRadius,
              overflow: "scroll",
            }}
          >
            <EmbeddedCheckoutProvider
              stripe={stripePromise}
              options={{ clientSecret }}
            >
              <EmbeddedCheckout />
            </EmbeddedCheckoutProvider>
          </View>

          <Button
            type="secondary"
            isAbsoluteBottom
            text="Fermer"
            onPress={() => setClientSecret(null)}
          />
        </View>
      </Overlay>
    </StripeEmbeddedContext.Provider>
  );
};
