import React, { useState, useEffect } from "react";
import { Link, useParams, useNavigate } from "react-router-dom";
import { __, sprintf } 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 [customerShippingAddresses, setCustomerShippingAddresses] = useState([]);
  const [selectedProductData, setSelectedProductData] = useState(null);
  const [billingPeriod, setBillingPeriod] = useState("month");
  const { toasts, showToast, removeToast } = useToast();
  const isEdit = !!id;
  const { env } = window.arraySubs;
  const toSelectOptions = (options = {}) =>
    Object.entries(options || {}).map(([value, label]) => ({ value, label }));
  const countryOptions = toSelectOptions(env?.countries);
  const shippingCountryOptions = toSelectOptions(
    env?.shippingCountries && Object.keys(env.shippingCountries).length
      ? env.shippingCountries
      : env?.countries,
  );
  const getStateOptions = (countryField) =>
    toSelectOptions(env?.states?.[form.getFieldValue(countryField)] || {});
  const getShippingFieldValues = (shipping = {}) => ({
    shipping_first_name: shipping.first_name || "",
    shipping_last_name: shipping.last_name || "",
    shipping_company: shipping.company || "",
    shipping_address_1: shipping.address_1 || "",
    shipping_address_2: shipping.address_2 || "",
    shipping_city: shipping.city || "",
    shipping_state: shipping.state || "",
    shipping_postcode: shipping.postcode || "",
    shipping_country: shipping.country || "",
    shipping_phone: shipping.phone || "",
  });
  const applyShippingAddress = (addressKey) => {
    const selected = customerShippingAddresses.find(
      (address) => address.value === addressKey,
    );
    if (selected?.data) {
      form.setFieldsValue(getShippingFieldValues(selected.data));
    }
  };

  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_email: billingAddress.email || data.invoice_email || "",
        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 || "",
        shipping_phone: shippingAddress.phone || "",
      });

      // 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 customer selection and prefill billing/shipping info
   */
  const handleCustomerChange = async (customerId) => {
    if (!customerId) {
      setCustomerShippingAddresses([]);
      return;
    }

    try {
      const response = await fetch(
        buildUrl(
          `${env?.apiBaseUrl}arraysubs/v1/subscriptions/customer/${customerId}`,
        ),
        {
          headers: { "X-WP-Nonce": env?.nonce },
        },
      );

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

      const result = await response.json();
      const data = result.content || result.data || result;
      const billing = data.billing || {};
      const shipping = data.shipping || {};
      const additionalShipping = Array.isArray(
        data.additional_shipping_addresses,
      )
        ? data.additional_shipping_addresses
        : [];
      const savedShippingAddresses = [
        {
          label: __("Primary shipping address", "arraysubs"),
          value: "primary",
          data: shipping,
        },
        ...additionalShipping.map((address, index) => ({
          label:
            address.label ||
            sprintf(__("Shipping address %d", "arraysubs"), index + 2),
          value: `additional-${index}`,
          data: address,
        })),
      ];

      setCustomerShippingAddresses(savedShippingAddresses);

      form.setFieldsValue({
        invoice_email: data.email || "",
        // Billing address
        billing_first_name: billing.first_name || "",
        billing_last_name: billing.last_name || "",
        billing_company: billing.company || "",
        billing_address_1: billing.address_1 || "",
        billing_address_2: billing.address_2 || "",
        billing_city: billing.city || "",
        billing_state: billing.state || "",
        billing_postcode: billing.postcode || "",
        billing_country: billing.country || "",
        billing_email: billing.email || data.email || "",
        billing_phone: billing.phone || "",
        // Shipping address
        saved_shipping_address_key: "primary",
        ...getShippingFieldValues(shipping),
      });
    } catch (error) {
      showToast(error.message, "error");
    }
  };

  /**
   * 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 || "",
        email: values.billing_email || values.invoice_email || "",
        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 || "",
        phone: values.shipping_phone || "",
      };

      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,
              }),
              onChange: handleCustomerChange,
              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"),
            },
          ],
        },
      ].filter(Boolean),
    },

    // Trial Settings
    {
      field: "Card",
      children: [
        {
          field: "Title",
          heading: 3,
          text: __("Trial Settings", "arraysubs"),
          subText: __("Configure optional free trial timing", "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" },
              ],
            },
          ],
        },
      ],
    },

    // 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 & Addresses
    {
      field: "Card",
      children: [
        {
          field: "Title",
          heading: 3,
          text: __("Billing Information & Addresses", "arraysubs"),
          subText: __(
            "Invoice email, billing address, and shipping 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: "Select",
              name: "billing_state",
              label: __("State / Province", "arraysubs"),
              data: [],
              getOptions: () => getStateOptions("billing_country"),
              placeholder: __("Select a state", "arraysubs"),
            },
            {
              field: "Text",
              name: "billing_postcode",
              label: __("Postcode / ZIP", "arraysubs"),
            },
          ],
        },
        {
          field: "AutoGrid",
          cols: 2,
          children: [
            {
              field: "Select",
              name: "billing_country",
              label: __("Country", "arraysubs"),
              data: countryOptions,
              placeholder: __("Select a country", "arraysubs"),
              onChange: () => form.setFieldValue("billing_state", ""),
            },
            {
              field: "Text",
              name: "billing_phone",
              label: __("Phone", "arraysubs"),
            },
          ],
        },
        {
          field: "Text",
          name: "billing_email",
          label: __("Billing Email", "arraysubs"),
          placeholder: __("customer@example.com", "arraysubs"),
        },
        {
          field: "Title",
          heading: 5,
          text: __("Shipping Address", "arraysubs"),
        },
        ...(customerShippingAddresses.length > 1
          ? [
              {
                field: "Select",
                name: "saved_shipping_address_key",
                label: __("Saved Shipping Address", "arraysubs"),
                data: customerShippingAddresses,
                onChange: applyShippingAddress,
              },
            ]
          : []),
        {
          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: "Select",
              name: "shipping_state",
              label: __("State / Province", "arraysubs"),
              data: [],
              getOptions: () => getStateOptions("shipping_country"),
              placeholder: __("Select a state", "arraysubs"),
            },
            {
              field: "Text",
              name: "shipping_postcode",
              label: __("Postcode / ZIP", "arraysubs"),
            },
          ],
        },
        {
          field: "AutoGrid",
          cols: 2,
          children: [
            {
              field: "Select",
              name: "shipping_country",
              label: __("Country", "arraysubs"),
              data: shippingCountryOptions,
              placeholder: __("Select a country", "arraysubs"),
              onChange: () => form.setFieldValue("shipping_state", ""),
            },
            {
              field: "Text",
              name: "shipping_phone",
              label: __("Phone", "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;
