"use client";

import { useEffect } from "react";

declare global {
  interface Window {
    Worldpay: unknown;
  }
}

interface WorldpayFormProps {
  clientKey: string;
  orderData: {
    transactionReference: string;
    merchant: { entity: string };
    narrative: { line1: string };
    value: { currency: string; amount: number };
    resultURLs?: {
      successURL: string;
      failureURL: string;
      cancelURL: string;
      errorURL: string;
    };
  };
}

export default function WorldpayForm({
  clientKey,
  orderData
}: WorldpayFormProps) {
  useEffect(() => {
    const initializeWorldpay = async () => {
      if (typeof window.Worldpay !== "undefined") {
        const form = document.createElement("form");
        form.method = "post";
        form.action = "https://try.access.worldpay.com/payment_pages";

        // Append order data as hidden fields
        Object.entries(orderData).forEach(([key, value]) => {
          const input = document.createElement("input");
          input.type = "hidden";
          input.name = key;
          input.value =
            typeof value === "object" ? JSON.stringify(value) : String(value);
          form.appendChild(input);
        });

        document.body.appendChild(form);

        const config = {
          url: "https://try.access.worldpay.com/payment_pages",
          paymentSection: document.getElementById("worldpay-container"),
          form: form,
          clientKey: clientKey,
          display: "inline",
          type: "card",
          onSuccess: response => {
            console.log("Payment successful:", response);
          },
          onError: error => {
            console.error("Payment error:", error);
          }
        };

        //@ts-expect-error - Worldpay is not defined in the global scope
        window.Worldpay.HPP.init(config);
      }
    };

    initializeWorldpay();
  }, [clientKey, orderData]);

  return <div id="worldpay-container" />;
}
