import React, { useEffect } from "react";
import {
  SMARTLINK_BASE_URL,
  Environment,
  assembleURLWithOriginHashAndPin,
} from "./helpers";
import useSmartlinkComponent from "./useSmartlinkComponent";

interface SmartlinkComponentProps {
  hash: string;
  pin?: string;
  prePaymentMethod: (
    quoteId: string
  ) => Promise<{ success: boolean; payment_id: string }>;
  env?: Environment;
  onPaymentSuccess?: (successPaymentData: string) => void;
  customStyle?: React.CSSProperties;
}

const SmartlinkComponent: React.FC<SmartlinkComponentProps> = ({
  hash,
  pin,
  prePaymentMethod,
  onPaymentSuccess = (successPaymentData: string) => {},
  env,
  customStyle,
}) => {
  const { iframeRef, sendMessageToIframe, enviroment, rectangle } =
    useSmartlinkComponent(prePaymentMethod, onPaymentSuccess, env);
  const iframeBaseUrl = SMARTLINK_BASE_URL[enviroment];
  const iframeSrc = assembleURLWithOriginHashAndPin(iframeBaseUrl, hash, pin);
  const { width, height } = rectangle ?? {};

  useEffect(() => {
    const timer = setTimeout(() => {
      sendMessageToIframe("ping");
    }, 1000);
    return () => clearTimeout(timer);
  }, [sendMessageToIframe]);

  return (
    <div style={{ position: "relative" }}>
      <iframe
        id="paymentIframe"
        ref={iframeRef}
        src={iframeSrc}
        title="smart component"
        style={
          customStyle
            ? customStyle
            : {
                width: `${(width ?? 328) + 16}px`,
                height: `${(height ?? 650) + 8}px`,
              }
        }
      ></iframe>
    </div>
  );
};

export default SmartlinkComponent;
