/**
 * Checkout Builder Settings — Builder-specific global behavior toggles.
 *
 * @package ArraySubsPro
 */
import React, { useState, useEffect } from "react";
import { __ } from "@wordpress/i18n";
import Form from "rc-field-form";
import FormBuilder from "@libs/form-builder";
import { Skeleton } from "@libs/skeleton";
import { ToastContainer } from "@libs/toast";
import { useToast } from "@libs/toast/useToast";
import DefaultPageLayout from "@/components/DefaultPageLayout";
import {
  dotToNested,
  nestedToDot,
  fetchSettings,
  saveSettings,
} from "../Settings/settingsHelpers";

const buildFormStructure = () => [
  {
    field: "Card",
    children: [
      {
        field: "Title",
        text: __("General", "arraysubs"),
        heading: 4,
      },
      {
        field: "Switch",
        name: "checkout_builder.enabled",
        label: __("Enable Checkout Builder", "arraysubs"),
        help: __(
          "When disabled, WooCommerce default checkout is used.",
          "arraysubs",
        ),
      },
      {
        field: "Switch",
        name: "checkout_builder.copy_to_subscription",
        label: __("Copy Custom Fields to Subscriptions", "arraysubs"),
        help: __(
          "When a subscription is created, copy all custom checkout fields to the subscription.",
          "arraysubs",
        ),
        showWhen: {
          field: "checkout_builder.enabled",
          operator: "is_true",
        },
      },
      {
        field: "Switch",
        name: "checkout_builder.copy_to_renewal",
        label: __("Copy Custom Fields to Renewal Orders", "arraysubs"),
        help: __(
          "When a renewal order is generated, carry forward custom fields from the subscription.",
          "arraysubs",
        ),
        showWhen: {
          field: "checkout_builder.enabled",
          operator: "is_true",
        },
      },
    ],
  },
  {
    field: "Card",
    children: [
      {
        field: "Title",
        text: __("Order Display", "arraysubs"),
        heading: 4,
      },
      {
        field: "Switch",
        name: "checkout_builder.show_on_order_admin",
        label: __("Show on Admin Order Details", "arraysubs"),
        help: __(
          "Display custom checkout fields in a meta box on the order edit screen.",
          "arraysubs",
        ),
        showWhen: {
          field: "checkout_builder.enabled",
          operator: "is_true",
        },
      },
      {
        field: "Switch",
        name: "checkout_builder.show_on_order_customer",
        label: __("Show on Customer Order Details", "arraysubs"),
        help: __(
          "Display custom checkout fields on the Thank You page and My Account order view.",
          "arraysubs",
        ),
        showWhen: {
          field: "checkout_builder.enabled",
          operator: "is_true",
        },
      },
      {
        field: "Switch",
        name: "checkout_builder.show_on_subscription_detail",
        label: __("Show on Subscription Details", "arraysubs"),
        help: __(
          "Display custom checkout fields on the subscription detail view.",
          "arraysubs",
        ),
        showWhen: {
          field: "checkout_builder.enabled",
          operator: "is_true",
        },
      },
    ],
  },
  {
    field: "Card",
    children: [
      {
        field: "Title",
        text: __("File Uploads", "arraysubs"),
        heading: 4,
      },
      {
        field: "Switch",
        name: "checkout_builder.uploads_enabled",
        label: __("Allow File Uploads", "arraysubs"),
        help: __(
          "Enable file upload fields on the checkout. Files are stored privately in the uploads directory.",
          "arraysubs",
        ),
        showWhen: {
          field: "checkout_builder.enabled",
          operator: "is_true",
        },
      },
      {
        field: "Number",
        name: "checkout_builder.uploads_max_size",
        label: __("Default Max File Size (MB)", "arraysubs"),
        min: 1,
        max: 100,
        help: __(
          "Default maximum file size for upload fields. Can be overridden per field.",
          "arraysubs",
        ),
        showWhen: [
          { field: "checkout_builder.enabled", operator: "is_true" },
          { field: "checkout_builder.uploads_enabled", operator: "is_true" },
        ],
      },
    ],
  },
];

const CheckoutBuilderSettings = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [formData, setFormData] = useState({});
  const { toasts, showToast, removeToast } = useToast();

  const formStructure = buildFormStructure();

  useEffect(() => {
    loadSettings();
  }, []);

  const loadSettings = async () => {
    setLoading(true);
    try {
      const settings = await fetchSettings();
      const flatData = nestedToDot(settings);
      setFormData(flatData);
      form.setFieldsValue(flatData);
    } catch (err) {
      showToast(
        err.message || __("Failed to load settings.", "arraysubs"),
        "error",
      );
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (values) => {
    setSaving(true);
    try {
      const nestedData = dotToNested(values);
      await saveSettings(nestedData);
      setFormData(values);
      showToast(__("Settings saved!", "arraysubs"), "success");
    } catch (err) {
      showToast(
        err.message || __("Failed to save settings.", "arraysubs"),
        "error",
      );
    } finally {
      setSaving(false);
    }
  };

  const handleDiscard = () => {
    form.setFieldsValue(formData);
  };

  if (loading) {
    return (
      <DefaultPageLayout title={__("Checkout Builder Settings", "arraysubs")}>
        <Skeleton variant="rectangle" width="100%" height={300} />
      </DefaultPageLayout>
    );
  }

  return (
    <DefaultPageLayout
      title={__("Checkout Builder Settings", "arraysubs")}
      subtitle={__(
        "Global behavior settings for the Checkout Builder.",
        "arraysubs",
      )}
    >
      <Form form={form} onFinish={handleSubmit} layout="vertical">
        <FormBuilder formItems={formStructure} form={form} />
        <div className="arraysubs-settings-actions arraysubs-bottom-fixed-actions">
          <div>
            <button
              type="submit"
              className="button button-primary"
              disabled={saving}
            >
              {saving
                ? __("Saving...", "arraysubs")
                : __("Save Settings", "arraysubs")}
            </button>
            <button
              type="button"
              className="button"
              onClick={handleDiscard}
              disabled={saving}
            >
              {__("Discard Changes", "arraysubs")}
            </button>
          </div>
        </div>
      </Form>
      <ToastContainer toasts={toasts} removeToast={removeToast} />
    </DefaultPageLayout>
  );
};

export default CheckoutBuilderSettings;
