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";
import { useConfirm } from "@libs/confirm-dialog";
import SpinnerButton from "@libs/confirm-dialog/SpinnerButton";

/**
 * Subscription Edit Page
 * For editing limited fields on an existing subscription
 * (Not for creating new subscriptions - use SubscriptionForm for that)
 */
const SubscriptionEdit = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [form] = useForm();
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [subscription, setSubscription] = useState(null);
  const [selectedStatus, setSelectedStatus] = useState("");
  const [statusChanging, setStatusChanging] = useState(false);
  const { toasts, showToast, removeToast } = useToast();
  const { confirm, confirmDialog } = useConfirm();
  const { env } = window.arraySubs;

  // Status options for dropdown
  const statusOptions = [
    { 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" },
  ];

  // Status labels for display
  const statusLabels = {
    "arraysubs-pending": __("Pending", "arraysubs"),
    "arraysubs-active": __("Active", "arraysubs"),
    "arraysubs-on-hold": __("On Hold", "arraysubs"),
    "arraysubs-cancelled": __("Cancelled", "arraysubs"),
    "arraysubs-expired": __("Expired", "arraysubs"),
    "arraysubs-trial": __("Trial", "arraysubs"),
  };

  const getStatusLabel = (status) => {
    return statusLabels[status] || status;
  };

  useEffect(() => {
    if (id) {
      fetchSubscription();
    } else {
      // Redirect to new subscription form if no ID
      navigate("/subscriptions/form");
    }
  }, [id]);

  /**
   * Fetch existing subscription data
   */
  const fetchSubscription = 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 subscription", "arraysubs"));
      }

      const result = await response.json();
      const data = result.content;
      setSubscription(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
        : {};

      // Set editable form fields
      form.setFieldsValue({
        status: data.status,
        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 || "",
      });
    } catch (error) {
      showToast(error.message, "error");
    } finally {
      setLoading(false);
    }
  };

  /**
   * 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 = {
        invoice_email: values.invoice_email || "",
        billing_address: billingAddress,
        shipping_address: shippingAddress,
      };

      // Update subscription via custom REST endpoint
      const url = buildUrl(
        `${env?.apiBaseUrl}arraysubs/v1/subscriptions/${id}/update`,
      );
      const response = await fetch(url, {
        method: "POST",
        headers: {
          "X-WP-Nonce": env?.nonce,
          "Content-Type": "application/json",
        },
        body: JSON.stringify(payload),
      });

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

      showToast(
        __("Subscription updated successfully!", "arraysubs"),
        "success",
      );

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

  /**
   * Handle status change
   */
  const handleStatusChange = async (newStatus) => {
    const targetLabel = getStatusLabel(newStatus);
    let confirmMessage = `${__(
      "Change subscription status to",
      "arraysubs",
    )} ${targetLabel}?`;
    let variant = "info";

    if (newStatus === "arraysubs-cancelled") {
      confirmMessage = __(
        "This will cancel the subscription immediately. All scheduled renewals will be removed. Continue?",
        "arraysubs",
      );
      variant = "danger";
    } else if (newStatus === "arraysubs-on-hold") {
      confirmMessage = __(
        "This will put the subscription on hold. Scheduled renewals will be paused until the subscription is reactivated. Continue?",
        "arraysubs",
      );
      variant = "warning";
    } else if (newStatus === "arraysubs-active") {
      confirmMessage = __(
        "This will activate the subscription and schedule renewal payments. Continue?",
        "arraysubs",
      );
    }

    try {
      await confirm({
        title: `${__("Change Status", "arraysubs")} → ${targetLabel}`,
        message: confirmMessage,
        confirmText: `${__("Change to", "arraysubs")} ${targetLabel}`,
        loadingText: __("Updating…", "arraysubs"),
        variant,
        onConfirm: async () => {
          setStatusChanging(true);
          try {
            const url = buildUrl(
              `${env?.apiBaseUrl}arraysubs/v1/subscriptions/${id}/status`,
            );
            const response = await fetch(url, {
              method: "POST",
              headers: {
                "X-WP-Nonce": env?.nonce,
                "Content-Type": "application/json",
              },
              body: JSON.stringify({ status: newStatus }),
            });

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

            showToast(
              __("Status updated successfully!", "arraysubs"),
              "success",
            );
            setSelectedStatus("");
            fetchSubscription();
          } finally {
            setStatusChanging(false);
          }
        },
      });
    } catch (error) {
      showToast(error.message, "error");
    }
  };

  /**
   * Form configuration - Limited editable fields
   */
  const formItems = [
    // Contact
    {
      field: "Card",
      children: [
        {
          field: "Title",
          heading: 3,
          text: __("Contact", "arraysubs"),
          subText: __("Manage invoice and contact details", "arraysubs"),
        },
        {
          field: "Text",
          name: "invoice_email",
          label: __("Invoice Email", "arraysubs"),
          placeholder: __("customer@example.com", "arraysubs"),
          helperText: __(
            "Email for invoices (defaults to customer email)",
            "arraysubs",
          ),
        },
      ],
    },

    // Billing Address
    {
      field: "Card",
      children: [
        {
          field: "Title",
          heading: 3,
          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", "arraysubs"),
            },
            {
              field: "Text",
              name: "billing_phone",
              label: __("Phone", "arraysubs"),
            },
          ],
        },
        {
          field: "AutoGrid",
          cols: 2,
          children: [
            {
              field: "Text",
              name: "billing_address_1",
              label: __("Address Line 1", "arraysubs"),
            },
            {
              field: "Text",
              name: "billing_address_2",
              label: __("Address Line 2", "arraysubs"),
            },
          ],
        },
        {
          field: "AutoGrid",
          cols: 3,
          children: [
            {
              field: "Text",
              name: "billing_city",
              label: __("City", "arraysubs"),
            },
            {
              field: "Text",
              name: "billing_state",
              label: __("State", "arraysubs"),
            },
            {
              field: "Text",
              name: "billing_postcode",
              label: __("Postcode", "arraysubs"),
            },
          ],
        },
        {
          field: "Text",
          name: "billing_country",
          label: __("Country", "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", "arraysubs"),
            },
            {
              field: "Text",
              name: "shipping_address_1",
              label: __("Address Line 1", "arraysubs"),
            },
          ],
        },
        {
          field: "Text",
          name: "shipping_address_2",
          label: __("Address Line 2", "arraysubs"),
        },
        {
          field: "AutoGrid",
          cols: 3,
          children: [
            {
              field: "Text",
              name: "shipping_city",
              label: __("City", "arraysubs"),
            },
            {
              field: "Text",
              name: "shipping_state",
              label: __("State", "arraysubs"),
            },
            {
              field: "Text",
              name: "shipping_postcode",
              label: __("Postcode", "arraysubs"),
            },
          ],
        },
        {
          field: "Text",
          name: "shipping_country",
          label: __("Country", "arraysubs"),
        },
      ],
    },
  ];

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

  if (!subscription) {
    return (
      <DefaultPageLayout title={__("Not Found", "arraysubs")}>
        <p>{__("Subscription not found.", "arraysubs")}</p>
        <Link to="/subscriptions" className="button">
          {__("Back to Subscriptions", "arraysubs")}
        </Link>
      </DefaultPageLayout>
    );
  }

  return (
    <DefaultPageLayout
      title={__("Edit Subscription", "arraysubs")}
      subtitle={`#${id} - ${
        subscription.customer?.display_name ||
        subscription.customer?.user_login ||
        subscription.customer_name ||
        subscription.customer_email
      }`}
    >
      {/* Subscription Summary (Read-only info) */}
      <div className="arraysubs-edit-summary">
        <div className="arraysubs-edit-summary__grid">
          <div className="arraysubs-edit-summary__item">
            <strong>{__("Product", "arraysubs")}</strong>
            <span>
              {subscription.product?.parent_name ||
                subscription.product?.name ||
                subscription.product_name ||
                `Product #${subscription.product_id}`}
              {subscription.product?.variation_attributes &&
                subscription.product.variation_attributes.length > 0 && (
                  <span className="arraysubs-edit-summary__variation">
                    {subscription.product.variation_attributes.map(
                      (attr, i) => (
                        <span key={i}>
                          {attr.name}: {attr.value}
                          {i <
                          subscription.product.variation_attributes.length - 1
                            ? ", "
                            : ""}
                        </span>
                      ),
                    )}
                  </span>
                )}
            </span>
          </div>
          <div className="arraysubs-edit-summary__item">
            <strong>{__("Recurring Amount", "arraysubs")}</strong>
            <span>
              {new Intl.NumberFormat("en-US", {
                style: "currency",
                currency: subscription.currency || "USD",
              }).format(subscription.recurring_amount)}
              {" / "}
              {subscription.billing_interval} {subscription.billing_period}(s)
            </span>
          </div>
          <div className="arraysubs-edit-summary__item">
            <strong>{__("Customer", "arraysubs")}</strong>
            <span>
              {subscription.customer?.display_name ||
                subscription.customer?.user_login ||
                subscription.customer_name ||
                subscription.customer_email}
              {subscription.customer_email && (
                <span className="arraysubs-edit-summary__muted">
                  {" "}
                  ({subscription.customer_email})
                </span>
              )}
            </span>
          </div>
          <div className="arraysubs-edit-summary__item">
            <strong>
              {__("Status", "arraysubs")}
              <span className="arraysubs-edit-summary__status">
                {getStatusLabel(subscription.status)}
              </span>
            </strong>
            <div className="arraysubs-edit-summary__status-change">
              <select
                value={selectedStatus}
                onChange={(e) => setSelectedStatus(e.target.value)}
                className="arraysubs-edit-summary__select"
              >
                <option value="">{__("Change to...", "arraysubs")}</option>
                {statusOptions
                  .filter((s) => s.value !== subscription.status)
                  .map((s) => (
                    <option key={s.value} value={s.value}>
                      {s.label}
                    </option>
                  ))}
              </select>
              <SpinnerButton
                type="button"
                className="button"
                disabled={!selectedStatus}
                loading={statusChanging}
                loadingText={__("Updating…", "arraysubs")}
                onClick={() => {
                  if (selectedStatus) {
                    handleStatusChange(selectedStatus);
                  }
                }}
              >
                {__("Change Status", "arraysubs")}
              </SpinnerButton>
            </div>
          </div>
        </div>
      </div>

      {/* Editable Form */}
      <Form form={form} onFinish={onFinish}>
        <FormBuilder formItems={formItems} form={form} />

        <div className="arraysubs-subscription-form__actions arraysubs-bottom-fixed-actions">
          <div>
            <SpinnerButton
              type="submit"
              className="button button-primary"
              loading={submitting}
              loadingText={__("Saving…", "arraysubs")}
              onClick={() => form.submit()}
            >
              {__("Save Changes", "arraysubs")}
            </SpinnerButton>
            <Link to={`/subscriptions/detail/${id}`} className="button">
              {__("View Details", "arraysubs")}
            </Link>
          </div>
        </div>
      </Form>

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

export default SubscriptionEdit;
