/**
 * Checkout Builder constants and utilities.
 *
 * @package ArraySubsPro
 */
import { __ } from "@wordpress/i18n";

export const ORDER_INFO_PAYMENT_TYPE = "order_info_payment";
export const ORDER_INFO_PAYMENT_KEY = "arraysubs_order_info_payment";
export const CHECKOUT_COUPON_NOTICES_TYPE = "checkout_coupon_notices";
export const CHECKOUT_COUPON_NOTICES_KEY = "arraysubs_checkout_coupon_notices";
export const ORDER_NOTES_TYPE = "order_notes";
export const ORDER_NOTES_KEY = "arraysubs_order_notes";

/** Default design settings for multistep mode. */
export const DEFAULT_DESIGN = {
  color_scheme: "light",
  primary_color: "#2563eb",
  secondary_color: "#64748b",
  accent_color: "#10b981",
  error_color: "#ef4444",
  background_color: "#ffffff",
  text_color: "#1e293b",
  container_width: "medium",
  container_max_width: "",
  border_radius: 8,
  step_position: "top",
  step_indicator_style: "numbers",
  spacing: "comfortable",
};

/** Column options for section elements. */
export const SECTION_COLUMN_OPTIONS = [
  { value: 1, label: __("1 Column", "arraysubs") },
  { value: 2, label: __("2 Columns", "arraysubs") },
  { value: 3, label: __("3 Columns", "arraysubs") },
];

/** Fields that cannot be removed from checkout. */
export const LOCKED_FIELDS = [
  "billing_email",
  "billing_first_name",
  "billing_last_name",
  "billing_country",
];

/** Generate a unique key from a label. */
export const generateFieldKey = (label) => {
  if (!label) return "";
  return label
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "_")
    .replace(/^_|_$/g, "")
    .substring(0, 40);
};

/**
 * Generate a unique key from a label, deduplicating against existing keys.
 * If the base key already exists, append _2, _3, etc.
 */
export const generateUniqueFieldKey = (label, existingKeys = []) => {
  const base = generateFieldKey(label);
  if (!base) return "";
  if (!existingKeys.includes(base)) return base;

  let counter = 2;
  while (existingKeys.includes(`${base}_${counter}`)) {
    counter++;
  }
  return `${base}_${counter}`;
};

/** Generate a unique step ID. */
export const generateStepId = () =>
  `step_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`;

/** Generate a unique field ID. */
export const generateFieldId = () =>
  `cf_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`;

/** Create the special order info and payment element. */
export const createOrderInfoPaymentElement = (overrides = {}) => ({
  key: ORDER_INFO_PAYMENT_KEY,
  type: ORDER_INFO_PAYMENT_TYPE,
  label: __("Order Info and Payment", "arraysubs"),
  column_width: "full",
  is_required: false,
  is_builtin: false,
  is_custom: false,
  ...overrides,
});

/** Create the special coupon and notices element. */
export const createCheckoutCouponNoticesElement = (overrides = {}) => ({
  key: CHECKOUT_COUPON_NOTICES_KEY,
  type: CHECKOUT_COUPON_NOTICES_TYPE,
  label: __("Coupon and Notices", "arraysubs"),
  column_width: "full",
  is_required: false,
  is_builtin: false,
  is_custom: false,
  ...overrides,
});

const DEFAULT_TYPE_LABELS = {
  text: __("Text", "arraysubs"),
  number: __("Number", "arraysubs"),
  email: __("Email", "arraysubs"),
  phone: __("Phone", "arraysubs"),
  select: __("Select", "arraysubs"),
  multi_select: __("Multi Select", "arraysubs"),
  textarea: __("Textarea", "arraysubs"),
  checkbox: __("Checkbox", "arraysubs"),
  toggle: __("Toggle", "arraysubs"),
  upload: __("File Upload", "arraysubs"),
  image_select: __("Image Select", "arraysubs"),
  grid_select: __("Grid Select", "arraysubs"),
  color_picker: __("Color Picker", "arraysubs"),
  calendar: __("Calendar", "arraysubs"),
  date: __("Date", "arraysubs"),
  datetime: __("Date & Time", "arraysubs"),
  time: __("Time", "arraysubs"),
  date_range: __("Date Range", "arraysubs"),
  heading: __("Heading", "arraysubs"),
  section: __("Section", "arraysubs"),
  paragraph: __("Paragraph", "arraysubs"),
  alert: __("Alert", "arraysubs"),
  checkout_coupon_notices: __("Coupon and Notices", "arraysubs"),
  billing_address: __("Billing Address", "arraysubs"),
  shipping_address: __("Shipping Address", "arraysubs"),
  order_notes: __("Order Notes", "arraysubs"),
  product_table: __("Product Table", "arraysubs"),
};

export const PRODUCT_TABLE_COLUMNS = [
  { key: "thumbnail", label: __("Thumbnail", "arraysubs") },
  { key: "title", label: __("Title", "arraysubs") },
  { key: "quantity", label: __("Quantity", "arraysubs") },
  { key: "sku", label: __("SKU", "arraysubs") },
  { key: "price", label: __("Price", "arraysubs") },
  { key: "sale_price", label: __("Sale Price", "arraysubs") },
  {
    key: "short_description",
    label: __("Short Description", "arraysubs"),
  },
];

export const DEFAULT_PRODUCT_TABLE_COLUMNS = {
  thumbnail: false,
  title: true,
  quantity: true,
  sku: false,
  price: true,
  sale_price: false,
  short_description: false,
};

/** Create the special order notes element. */
export const createOrderNotesElement = (overrides = {}) => ({
  key: ORDER_NOTES_KEY,
  type: ORDER_NOTES_TYPE,
  label: __("Order Notes", "arraysubs"),
  column_width: "full",
  is_required: false,
  is_builtin: true,
  is_custom: false,
  fields_config: {},
  ...overrides,
});

export const createDraftFieldFromType = (type, label = "") => {
  if (type === ORDER_INFO_PAYMENT_TYPE) {
    return createOrderInfoPaymentElement();
  }

  if (type === CHECKOUT_COUPON_NOTICES_TYPE) {
    return createCheckoutCouponNoticesElement();
  }

  if (type === ORDER_NOTES_TYPE) {
    return createOrderNotesElement();
  }

  const defaultLabel =
    label || DEFAULT_TYPE_LABELS[type] || __("Field", "arraysubs");

  const draft = {
    key: generateFieldId(),
    type,
    label: defaultLabel,
    placeholder: "",
    is_required: false,
    help_text: "",
    default_value: "",
    css_class: "",
    visibility_rules: [],
    is_builtin: false,
    is_custom: true,
  };

  if (
    ["select", "multi_select", "image_select", "grid_select"].includes(type)
  ) {
    draft.type_settings = {
      options: [
        { value: "option_1", label: __("Option 1", "arraysubs") },
        { value: "option_2", label: __("Option 2", "arraysubs") },
      ],
    };
  }

  if (type === "color_picker") {
    draft.type_settings = {
      ...(draft.type_settings || {}),
      default_color: "#2563eb",
    };
  }

  if (type === "heading") {
    draft.heading_level = "h3";
    draft.content = "";
  }

  if (type === "paragraph") {
    draft.content = "";
  }

  if (type === "alert") {
    draft.content = "";
    draft.alert_type = "info";
  }

  if (type === "section") {
    draft.columns = 1;
    draft.children = [[]];
  }

  if (type === "product_table") {
    draft.type_settings = {
      ...(draft.type_settings || {}),
      product_ids: [],
      category_ids: [],
      columns: { ...DEFAULT_PRODUCT_TABLE_COLUMNS },
      product_options_data: [],
      category_options_data: [],
    };
  }

  if (type === "billing_address" || type === "shipping_address") {
    draft.is_builtin = true;
    draft.is_custom = false;
    draft.key =
      type === "billing_address"
        ? "arraysubs_billing_address"
        : "arraysubs_shipping_address";
    draft.address_countries = [];
    draft.fields_config = {};
  }

  return draft;
};

/** Ensure the special order info and payment element exists once at the end. */
export const ensureOrderInfoPaymentElement = (elements = []) => {
  const filteredElements = (elements || []).filter(
    (element) => element?.type !== ORDER_INFO_PAYMENT_TYPE,
  );

  return [...filteredElements, createOrderInfoPaymentElement()];
};

/**
 * Build a single checkout step from WooCommerce or legacy sections.
 *
 * Billing and shipping sections are collapsed into their respective group
 * elements (`billing_address` / `shipping_address`) so the builder shows a
 * single draggable card per address block instead of individual fields.
 * Order section fields are replaced with the `order_notes` group element.
 */
export const buildSingleStepFromSections = (sections = [], overrides = {}) => {
  const elements = [];

  (sections || []).forEach((section) => {
    const sectionId = section?.id || "";

    if (sectionId === "billing") {
      elements.push(createDraftFieldFromType("billing_address"));
      return;
    }

    if (sectionId === "shipping") {
      elements.push(createDraftFieldFromType("shipping_address"));
      return;
    }

    if (sectionId === "order") {
      elements.push(createOrderNotesElement());
      return;
    }

    // Account and other sections: keep individual fields.
    const fields = section?.fields || [];
    elements.push(...fields);
  });

  return {
    id: overrides.id || generateStepId(),
    name: overrides.name || __("Checkout", "arraysubs"),
    icon: overrides.icon || "shopping-cart",
    fields: ensureOrderInfoPaymentElement(elements),
  };
};

/** Check if a field is a built-in WooCommerce field. */
export const isBuiltinField = (field) => Boolean(field?.is_builtin);

/** Check if a field is locked (cannot be removed). */
export const isLockedField = (fieldKey) => LOCKED_FIELDS.includes(fieldKey);

/** Check if a field type is a layout/display-only type. */
export const isLayoutField = (type) =>
  [
    "heading",
    "section",
    "paragraph",
    "alert",
    CHECKOUT_COUPON_NOTICES_TYPE,
    "billing_address",
    "shipping_address",
    ORDER_NOTES_TYPE,
    ORDER_INFO_PAYMENT_TYPE,
    "product_table",
  ].includes(type);

/** Check if a field type is an address group element. */
export const isAddressField = (type) =>
  ["billing_address", "shipping_address"].includes(type);

/**
 * Merge WooCommerce default fields with saved config fields.
 * Ensures built-in fields are present even after WooCommerce changes.
 */
export const mergeWithDefaults = (savedSections, defaultSections) => {
  if (!savedSections || !savedSections.length) return defaultSections;
  return savedSections;
};
