import React, { useState, useEffect } from "react";
import { Link, useParams, useNavigate } from "react-router-dom";
import { __ } from "@wordpress/i18n";
import Form, { useForm } from "rc-field-form";
import FormBuilder from "@libs/form-builder";
import { buildUrl } from "@/libs/url";
import DefaultPageLayout from "@/components/DefaultPageLayout";
import { ToastContainer, useToast } from "@libs/toast";

const SubscriptionForm = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [form] = useForm();
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [products, setProducts] = useState([]);
  const [variations, setVariations] = useState([]);
  const [customerOptions, setCustomerOptions] = useState([]);
  const [selectedProductData, setSelectedProductData] = useState(null);
  const [billingPeriod, setBillingPeriod] = useState("month");
  const { toasts, showToast, removeToast } = useToast();
  const isEdit = !!id;
  const { env } = window.arraySubs;

  useEffect(() => {
    fetchSubscriptionProducts();
    if (isEdit) {
      fetchData();
    }
  }, [id]);

  /**
   * Fetch only subscription products
   */
  const fetchSubscriptionProducts = async () => {
    try {
      const response = await fetch(
        buildUrl(`${env?.apiBaseUrl}arraysubs/v1/subscriptions/products`),
        {
          headers: {
            "X-WP-Nonce": env?.nonce,
          },
        },
      );

      if (!response.ok) {
        throw new Error(__("Failed to fetch products", "arraysubs"));
      }

      const data = await response.json();
      const productsList = data.content || data.data || [];

      setProducts(
        productsList.map((p) => ({
          label: `${p.name} (${p.type})`,
          value: p.id,
          data: p,
        })),
      );
    } catch (error) {
      showToast(error.message, "error");
      console.error("Failed to fetch products:", error);
    }
  };

  /**
   * Fetch existing subscription data for edit mode
   */
  const fetchData = async () => {
    setLoading(true);
    try {
      const url = buildUrl(
        `${env?.apiBaseUrl}arraysubs/v1/subscriptions/${id}/detail`,
      );
      const response = await fetch(url, {
        headers: { "X-WP-Nonce": env?.nonce },
      });

      if (!response.ok) {
        throw new Error(__("Failed to fetch data", "arraysubs"));
      }

      const result = await response.json();
      const data = result.data;

      // Parse addresses
      const billingAddress = data.billing_address
        ? typeof data.billing_address === "string"
          ? JSON.parse(data.billing_address)
          : data.billing_address
        : {};

      const shippingAddress = data.shipping_address
        ? typeof data.shipping_address === "string"
          ? JSON.parse(data.shipping_address)
          : data.shipping_address
        : {};

      form.setFieldsValue({
        status: data.status,
        customer_id: data.customer_id,
        product_id: data.product_id,
        variation_id: data.variation_id || "",
        quantity: data.quantity || 1,
        recurring_amount: data.recurring_amount || "",
        billing_interval:
          data.billing_period === "lifetime" ? 1 : data.billing_interval || 1,
        billing_period: data.billing_period || "month",
        subscription_length: data.subscription_length || 0,
        trial_length: data.trial_length || 0,
        trial_period: data.trial_period || "day",
        signup_fee: data.signup_fee || 0,
        enable_different_renewal_price:
          data.enable_different_renewal_price || false,
        different_renewal_price: data.different_renewal_price || "",
        different_renewal_price_after: data.different_renewal_price_after || 1,
        invoice_email: data.invoice_email || "",
        // Billing address
        billing_first_name: billingAddress.first_name || "",
        billing_last_name: billingAddress.last_name || "",
        billing_company: billingAddress.company || "",
        billing_address_1: billingAddress.address_1 || "",
        billing_address_2: billingAddress.address_2 || "",
        billing_city: billingAddress.city || "",
        billing_state: billingAddress.state || "",
        billing_postcode: billingAddress.postcode || "",
        billing_country: billingAddress.country || "",
        billing_phone: billingAddress.phone || "",
        // Shipping address
        shipping_first_name: shippingAddress.first_name || "",
        shipping_last_name: shippingAddress.last_name || "",
        shipping_company: shippingAddress.company || "",
        shipping_address_1: shippingAddress.address_1 || "",
        shipping_address_2: shippingAddress.address_2 || "",
        shipping_city: shippingAddress.city || "",
        shipping_state: shippingAddress.state || "",
        shipping_postcode: shippingAddress.postcode || "",
        shipping_country: shippingAddress.country || "",
      });

      // Sync billing period state for lifetime handling
      setBillingPeriod(data.billing_period || "month");

      // If product is set, trigger prefill
      if (data.product_id) {
        handleProductChange(data.product_id, true);
      }

      // Resolve customer label for display
      if (data.customer_id) {
        try {
          const customerResponse = await fetch(
            buildUrl(`${env?.apiBaseUrl}wp/v2/users`, {
              include: data.customer_id,
              context: "edit",
            }),
            {
              headers: { "X-WP-Nonce": env?.nonce },
            },
          );
          if (customerResponse.ok) {
            const users = await customerResponse.json();
            setCustomerOptions(
              users.map((u) => ({
                label: u.email ? `${u.name} - ${u.email}` : u.name,
                value: u.id,
              })),
            );
          }
        } catch {
          // Customer label will show as ID if resolution fails
        }
      }
    } catch (error) {
      showToast(error.message, "error");
    } finally {
      setLoading(false);
    }
  };

  /**
   * Handle product selection and prefill values
   */
  const handleProductChange = (productId, skipReset = false) => {
    const selectedProduct = products.find((p) => p.value === productId);

    if (!selectedProduct || !selectedProduct.data) {
      setVariations([]);
      setSelectedProductData(null);
      return;
    }

    const productData = selectedProduct.data;
    setSelectedProductData(productData);

    // If variable product, set variations
    if (productData.type === "variable" && productData.variations) {
      setVariations(
        productData.variations.map((v) => ({
          label: v.name,
          value: v.id,
          data: v,
        })),
      );
    } else {
      setVariations([]);
      // Clear variation_id if switching from variable to simple
      form.setFieldValue("variation_id", "");
    }

    // Prefill subscription values from product (only if not editing or skipReset is false)
    if (!isEdit || !skipReset) {
      const subData = productData.subscription_data;
      if (subData) {
        // Use setTimeout to ensure form is ready
        setTimeout(() => {
          const period = subData.period || "month";
          form.setFieldsValue({
            recurring_amount: subData.price || "",
            billing_interval: period === "lifetime" ? 1 : subData.interval || 1,
            billing_period: period,
            subscription_length: subData.length || 0,
            trial_length: subData.trial_length || 0,
            trial_period: subData.trial_period || "day",
            signup_fee: subData.signup_fee || 0,
            enable_different_renewal_price:
              subData.enable_different_renewal_price || false,
            different_renewal_price: subData.different_renewal_price || "",
            different_renewal_price_after:
              subData.different_renewal_price_after || 1,
          });
          setBillingPeriod(period);
        }, 0);
      }
    }
  };

  /**
   * Handle variation selection and prefill
   */
  const handleVariationChange = (variationId) => {
    const selectedVariation = variations.find((v) => v.value === variationId);

    if (selectedVariation && selectedVariation.data) {
      const varData = selectedVariation.data;
      const subData = varData.subscription_data;

      if (subData) {
        // Use setTimeout to ensure form is ready
        setTimeout(() => {
          const period = subData.period || "month";
          form.setFieldsValue({
            recurring_amount: subData.price || "",
            billing_interval: period === "lifetime" ? 1 : subData.interval || 1,
            billing_period: period,
            subscription_length: subData.length || 0,
            trial_length: subData.trial_length || 0,
            trial_period: subData.trial_period || "day",
            signup_fee: subData.signup_fee || 0,
            enable_different_renewal_price:
              subData.enable_different_renewal_price || false,
            different_renewal_price: subData.different_renewal_price || "",
            different_renewal_price_after:
              subData.different_renewal_price_after || 1,
          });
          setBillingPeriod(period);
        }, 0);
      }
    }
  };

  /**
   * Submit form
   */
  const onFinish = async (values) => {
    setSubmitting(true);
    try {
      const billingAddress = {
        first_name: values.billing_first_name || "",
        last_name: values.billing_last_name || "",
        company: values.billing_company || "",
        address_1: values.billing_address_1 || "",
        address_2: values.billing_address_2 || "",
        city: values.billing_city || "",
        state: values.billing_state || "",
        postcode: values.billing_postcode || "",
        country: values.billing_country || "",
        phone: values.billing_phone || "",
      };

      const shippingAddress = {
        first_name: values.shipping_first_name || "",
        last_name: values.shipping_last_name || "",
        company: values.shipping_company || "",
        address_1: values.shipping_address_1 || "",
        address_2: values.shipping_address_2 || "",
        city: values.shipping_city || "",
        state: values.shipping_state || "",
        postcode: values.shipping_postcode || "",
        country: values.shipping_country || "",
      };

      const payload = {
        product_id: parseInt(values.product_id),
        variation_id: values.variation_id ? parseInt(values.variation_id) : 0,
        quantity: parseInt(values.quantity) || 1,
        recurring_amount: parseFloat(values.recurring_amount) || 0,
        billing_interval: parseInt(values.billing_interval) || 1,
        billing_period: values.billing_period,
        subscription_length: parseInt(values.subscription_length) || 0,
        trial_length: parseInt(values.trial_length) || 0,
        trial_period: values.trial_period || "day",
        signup_fee: parseFloat(values.signup_fee) || 0,
        enable_different_renewal_price:
          values.enable_different_renewal_price || false,
        different_renewal_price:
          parseFloat(values.different_renewal_price) || 0,
        different_renewal_price_after:
          parseInt(values.different_renewal_price_after) || 1,
        invoice_email: values.invoice_email || "",
        billing_address: JSON.stringify(billingAddress),
        shipping_address: JSON.stringify(shippingAddress),
      };

      let response;

      if (isEdit) {
        // Update existing subscription
        const url = buildUrl(
          `${env?.apiBaseUrl}arraysubs/v1/subscriptions/${id}/update`,
        );
        response = await fetch(url, {
          method: "POST",
          headers: {
            "X-WP-Nonce": env?.nonce,
            "Content-Type": "application/json",
          },
          body: JSON.stringify(payload),
        });
      } else {
        // Create new subscription via native REST API
        const url = buildUrl(`${env?.apiBaseUrl}wp/v2/arraysubs_data`);
        response = await fetch(url, {
          method: "POST",
          headers: {
            "X-WP-Nonce": env?.nonce,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            status: values.status || "arraysubs-pending",
            title: `Subscription #${Date.now()}`,
            meta: {
              _customer_id: parseInt(values.customer_id),
              _product_id: payload.product_id,
              _variation_id: payload.variation_id,
              _quantity: payload.quantity,
              _recurring_amount: payload.recurring_amount,
              _billing_interval: payload.billing_interval,
              _billing_period: payload.billing_period,
              _subscription_length: payload.subscription_length,
              _trial_length: payload.trial_length,
              _trial_period: payload.trial_period,
              _signup_fee: payload.signup_fee,
              _enable_different_renewal_price:
                payload.enable_different_renewal_price ? "yes" : "no",
              _different_renewal_price: payload.different_renewal_price,
              _different_renewal_price_after:
                payload.different_renewal_price_after,
              _invoice_email: payload.invoice_email,
              _billing_address: payload.billing_address,
              _shipping_address: payload.shipping_address,
            },
          }),
        });
      }

      if (!response.ok) {
        throw new Error(__("Failed to save", "arraysubs"));
      }

      showToast(
        isEdit
          ? __("Subscription updated successfully!", "arraysubs")
          : __("Subscription created successfully!", "arraysubs"),
        "success",
      );

      setTimeout(() => navigate("/subscriptions"), 1500);
    } catch (error) {
      showToast(error.message, "error");
    } finally {
      setSubmitting(false);
    }
  };

  /**
   * Form configuration
   */
  const formItems = [
    // General Section
    {
      field: "Card",
      children: [
        {
          field: "Title",
          heading: 3,
          text: __("General", "arraysubs"),
          subText: __("Customer and status information", "arraysubs"),
        },
        {
          field: "AutoGrid",
          cols: 2,
          children: [
            isEdit
              ? {
                  field: "Select",
                  name: "status",
                  label: __("Status", "arraysubs"),
                  data: [
                    {
                      label: __("Pending", "arraysubs"),
                      value: "arraysubs-pending",
                    },
                    {
                      label: __("Active", "arraysubs"),
                      value: "arraysubs-active",
                    },
                    {
                      label: __("On Hold", "arraysubs"),
                      value: "arraysubs-on-hold",
                    },
                    {
                      label: __("Cancelled", "arraysubs"),
                      value: "arraysubs-cancelled",
                    },
                    {
                      label: __("Expired", "arraysubs"),
                      value: "arraysubs-expired",
                    },
                    {
                      label: __("Trial", "arraysubs"),
                      value: "arraysubs-trial",
                    },
                  ],
                  rules: [
                    {
                      required: true,
                      message: __("Status is required", "arraysubs"),
                    },
                  ],
                }
              : null,
            {
              field: "Select",
              name: "customer_id",
              label: __("Customer", "arraysubs"),
              data: customerOptions,
              api: {
                url: `${env?.apiBaseUrl}wp/v2/users`,
                params: { context: "edit" },
                perPage: 5,
                searchOnly: true,
              },
              mapOption: (user) => ({
                label: user.email ? `${user.name} - ${user.email}` : user.name,
                value: user.id,
              }),
              placeholder: __("Select a customer", "arraysubs"),
              rules: [
                {
                  required: true,
                  message: __("Customer is required", "arraysubs"),
                },
              ],
            },
          ].filter(Boolean),
        },
      ],
    },

    // Product & Subscription Details
    {
      field: "Card",
      children: [
        {
          field: "Title",
          heading: 3,
          text: __("Product & Subscription Details", "arraysubs"),
          subText: __(
            "Select a product and configure billing schedule",
            "arraysubs",
          ),
        },
        {
          field: "AutoGrid",
          cols: 2,
          children: [
            {
              field: "Select",
              name: "product_id",
              label: __("Subscription Product", "arraysubs"),
              data: products,
              placeholder: __("Select a subscription product", "arraysubs"),
              onChange: handleProductChange,
              rules: [
                {
                  required: true,
                  message: __("Product is required", "arraysubs"),
                },
              ],
            },
            variations.length > 0
              ? {
                  field: "Select",
                  name: "variation_id",
                  label: __("Product Variation", "arraysubs"),
                  data: variations,
                  placeholder: __("Select a variation", "arraysubs"),
                  onChange: handleVariationChange,
                }
              : {
                  field: "Number",
                  name: "quantity",
                  label: __("Quantity", "arraysubs"),
                  min: 1,
                  rules: [
                    {
                      required: true,
                      message: __("Quantity is required", "arraysubs"),
                    },
                  ],
                },
          ],
        },
        variations.length > 0
          ? {
              field: "AutoGrid",
              cols: 2,
              children: [
                {
                  field: "Number",
                  name: "quantity",
                  label: __("Quantity", "arraysubs"),
                  min: 1,
                  rules: [
                    {
                      required: true,
                      message: __("Quantity is required", "arraysubs"),
                    },
                  ],
                },
                {
                  field: "Number",
                  name: "recurring_amount",
                  label: __("Recurring Amount", "arraysubs"),
                  min: 0,
                  step: 0.01,
                  helperText: __(
                    "Admin can override the recurring price",
                    "arraysubs",
                  ),
                  rules: [
                    {
                      required: true,
                      message: __("Recurring amount is required", "arraysubs"),
                    },
                  ],
                },
              ],
            }
          : null,
        {
          field: "AutoGrid",
          cols: 2,
          children: [
            variations.length > 0
              ? null
              : {
                  field: "Number",
                  name: "recurring_amount",
                  label: __("Recurring Amount", "arraysubs"),
                  min: 0,
                  step: 0.01,
                  helperText: __(
                    "Admin can override the recurring price",
                    "arraysubs",
                  ),
                  rules: [
                    {
                      required: true,
                      message: __("Recurring amount is required", "arraysubs"),
                    },
                  ],
                },
            {
              field: "Number",
              name: "billing_interval",
              label: __("Billing Interval", "arraysubs"),
              min: 1,
              disabled: billingPeriod === "lifetime",
              helperText:
                billingPeriod === "lifetime"
                  ? __("Not applicable for Lifetime Deal", "arraysubs")
                  : __("E.g., 1 for monthly, 2 for bi-monthly", "arraysubs"),
              rules:
                billingPeriod === "lifetime"
                  ? []
                  : [
                      {
                        required: true,
                        message: __(
                          "Billing interval is required",
                          "arraysubs",
                        ),
                      },
                    ],
            },
            {
              field: "Select",
              name: "billing_period",
              label: __("Billing Period", "arraysubs"),
              data: [
                { label: __("Day(s)", "arraysubs"), value: "day" },
                { label: __("Week(s)", "arraysubs"), value: "week" },
                { label: __("Month(s)", "arraysubs"), value: "month" },
                { label: __("Year(s)", "arraysubs"), value: "year" },
                { label: __("Lifetime Deal", "arraysubs"), value: "lifetime" },
              ],
              rules: [
                {
                  required: true,
                  message: __("Billing period is required", "arraysubs"),
                },
              ],
            },
          ].filter(Boolean),
        },
        {
          field: "AutoGrid",
          cols: 2,
          children: [
            {
              field: "Number",
              name: "subscription_length",
              label: __("Subscription Length (0 = Never Expires)", "arraysubs"),
              min: 0,
              helperText: __(
                "Number of billing cycles, 0 for unlimited",
                "arraysubs",
              ),
            },
            {
              field: "Number",
              name: "signup_fee",
              label: __("Signup Fee", "arraysubs"),
              min: 0,
              step: 0.01,
              helperText: __("One-time fee charged at signup", "arraysubs"),
            },
          ],
        },
        {
          field: "AutoGrid",
          cols: 2,
          children: [
            {
              field: "Number",
              name: "trial_length",
              label: __("Trial Length (0 = No Trial)", "arraysubs"),
              min: 0,
              helperText: __("Number of trial periods", "arraysubs"),
            },
            {
              field: "Select",
              name: "trial_period",
              label: __("Trial Period", "arraysubs"),
              data: [
                { label: __("Day(s)", "arraysubs"), value: "day" },
                { label: __("Week(s)", "arraysubs"), value: "week" },
                { label: __("Month(s)", "arraysubs"), value: "month" },
                { label: __("Year(s)", "arraysubs"), value: "year" },
              ],
            },
          ],
        },
      ].filter(Boolean),
    },

    // Different Renewal Price
    {
      field: "Card",
      children: [
        {
          field: "Title",
          heading: 3,
          text: __("Different Renewal Price", "arraysubs"),
          subText: __(
            "Optionally change the price after a number of billing cycles",
            "arraysubs",
          ),
        },
        {
          field: "Switch",
          name: "enable_different_renewal_price",
          label: __("Enable Different Renewal Price", "arraysubs"),
          help: __(
            "After a certain number of billing cycles, use a different renewal price",
            "arraysubs",
          ),
        },
        {
          field: "AutoGrid",
          cols: 2,
          showWhen: {
            field: "enable_different_renewal_price",
            operator: "=",
            value: true,
          },
          children: [
            {
              field: "Number",
              name: "different_renewal_price",
              label: __("Different Renewal Price", "arraysubs"),
              min: 0,
              step: 0.01,
              helperText: __(
                "The new recurring price after the specified periods",
                "arraysubs",
              ),
            },
            {
              field: "Number",
              name: "different_renewal_price_after",
              label: __("After How Many Payments", "arraysubs"),
              min: 1,
              helperText: __(
                "Number of completed payments before switching to the different renewal price",
                "arraysubs",
              ),
            },
          ],
        },
      ],
    },

    // Billing Information
    {
      field: "Card",
      children: [
        {
          field: "Title",
          heading: 3,
          text: __("Billing Information", "arraysubs"),
          subText: __("Invoice email and billing address", "arraysubs"),
        },
        {
          field: "Text",
          name: "invoice_email",
          label: __("Invoice Email", "arraysubs"),
          placeholder: __("customer@example.com", "arraysubs"),
          helperText: __(
            "Email for invoices (defaults to customer email)",
            "arraysubs",
          ),
        },
        {
          field: "Title",
          heading: 5,
          text: __("Billing Address", "arraysubs"),
        },
        {
          field: "AutoGrid",
          cols: 2,
          children: [
            {
              field: "Text",
              name: "billing_first_name",
              label: __("First Name", "arraysubs"),
            },
            {
              field: "Text",
              name: "billing_last_name",
              label: __("Last Name", "arraysubs"),
            },
          ],
        },
        {
          field: "AutoGrid",
          cols: 2,
          children: [
            {
              field: "Text",
              name: "billing_company",
              label: __("Company (optional)", "arraysubs"),
            },
            {
              field: "Text",
              name: "billing_address_1",
              label: __("Address Line 1", "arraysubs"),
            },
          ],
        },
        {
          field: "Text",
          name: "billing_address_2",
          label: __("Address Line 2 (optional)", "arraysubs"),
        },
        {
          field: "AutoGrid",
          cols: 3,
          children: [
            {
              field: "Text",
              name: "billing_city",
              label: __("City", "arraysubs"),
            },
            {
              field: "Text",
              name: "billing_state",
              label: __("State / Province", "arraysubs"),
            },
            {
              field: "Text",
              name: "billing_postcode",
              label: __("Postcode / ZIP", "arraysubs"),
            },
          ],
        },
        {
          field: "AutoGrid",
          cols: 2,
          children: [
            {
              field: "Text",
              name: "billing_country",
              label: __("Country", "arraysubs"),
            },
            {
              field: "Text",
              name: "billing_phone",
              label: __("Phone", "arraysubs"),
            },
          ],
        },
      ],
    },

    // Shipping Address
    {
      field: "Card",
      children: [
        {
          field: "Title",
          heading: 3,
          text: __("Shipping Address", "arraysubs"),
          subText: __("Shipping details for physical products", "arraysubs"),
        },
        {
          field: "AutoGrid",
          cols: 2,
          children: [
            {
              field: "Text",
              name: "shipping_first_name",
              label: __("First Name", "arraysubs"),
            },
            {
              field: "Text",
              name: "shipping_last_name",
              label: __("Last Name", "arraysubs"),
            },
          ],
        },
        {
          field: "AutoGrid",
          cols: 2,
          children: [
            {
              field: "Text",
              name: "shipping_company",
              label: __("Company (optional)", "arraysubs"),
            },
            {
              field: "Text",
              name: "shipping_address_1",
              label: __("Address Line 1", "arraysubs"),
            },
          ],
        },
        {
          field: "Text",
          name: "shipping_address_2",
          label: __("Address Line 2 (optional)", "arraysubs"),
        },
        {
          field: "AutoGrid",
          cols: 3,
          children: [
            {
              field: "Text",
              name: "shipping_city",
              label: __("City", "arraysubs"),
            },
            {
              field: "Text",
              name: "shipping_state",
              label: __("State / Province", "arraysubs"),
            },
            {
              field: "Text",
              name: "shipping_postcode",
              label: __("Postcode / ZIP", "arraysubs"),
            },
          ],
        },
        {
          field: "Text",
          name: "shipping_country",
          label: __("Country", "arraysubs"),
        },
      ],
    },
  ].filter(Boolean);

  if (loading) {
    return (
      <DefaultPageLayout title={__("Loading...", "arraysubs")}>
        <p>{__("Loading subscription data...", "arraysubs")}</p>
      </DefaultPageLayout>
    );
  }

  return (
    <DefaultPageLayout
      title={
        isEdit
          ? __("Edit Subscription", "arraysubs")
          : __("Add New Subscription", "arraysubs")
      }
      subtitle={
        isEdit
          ? __("Update subscription details", "arraysubs")
          : __("Create a new subscription manually", "arraysubs")
      }
    >
      <Form
        form={form}
        onFinish={onFinish}
        onValuesChange={(changedValues) => {
          if (changedValues.billing_period !== undefined) {
            setBillingPeriod(changedValues.billing_period);
            if (changedValues.billing_period === "lifetime") {
              form.setFieldValue("billing_interval", 1);
            }
          }
        }}
        initialValues={{
          status: "arraysubs-pending",
          quantity: 1,
          billing_interval: 1,
          billing_period: "month",
          subscription_length: 0,
          trial_length: 0,
          trial_period: "day",
          signup_fee: 0,
          recurring_amount: 0,
        }}
      >
        <FormBuilder formItems={formItems} form={form} />

        <div className="arraysubs-subscription-form__actions arraysubs-bottom-fixed-actions">
          <div>
            <button
              type="submit"
              className="button button-primary"
              disabled={submitting}
              onClick={() => form.submit()}
            >
              {submitting
                ? __("Saving...", "arraysubs")
                : isEdit
                ? __("Update Subscription", "arraysubs")
                : __("Create Subscription", "arraysubs")}
            </button>
            <Link to="/subscriptions" className="button">
              {__("Cancel", "arraysubs")}
            </Link>
          </div>
        </div>
      </Form>

      <ToastContainer toasts={toasts} removeToast={removeToast} />
    </DefaultPageLayout>
  );
};

export default SubscriptionForm;
