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 "./settingsHelpers";

// Form structure for Feature Manager settings
const formStructure = [
  // Feature Manager Enable
  {
    field: "Card",
    children: [
      {
        field: "Title",
        heading: 3,
        text: __("Feature Manager", "arraysubs"),
        subText: __(
          "Define and display product features/entitlements for subscriptions",
          "arraysubs",
        ),
      },
      {
        field: "Switch",
        name: "feature_manager.enabled",
        label: __("Enable Feature Manager", "arraysubs"),
        helperText: __(
          "Allow defining features on products and displaying them to customers",
          "arraysubs",
        ),
      },
    ],
  },

  // Display Settings
  {
    field: "Card",
    children: [
      {
        field: "Title",
        heading: 3,
        text: __("Display Settings", "arraysubs"),
        subText: __("Configure where features are displayed", "arraysubs"),
      },
      {
        field: "Switch",
        name: "feature_manager.show_on_product_page",
        label: __("Show on Product Page", "arraysubs"),
        helperText: __(
          "Display features list on the frontend product page",
          "arraysubs",
        ),
        showWhen: {
          field: "feature_manager.enabled",
          operator: "is_true",
        },
      },
      {
        field: "Switch",
        name: "feature_manager.show_in_my_account",
        label: __("Show in My Account", "arraysubs"),
        helperText: __(
          'Display a "My Features" page in the customer My Account area',
          "arraysubs",
        ),
        showWhen: {
          field: "feature_manager.enabled",
          operator: "is_true",
        },
      },
      {
        field: "Text",
        name: "feature_manager.my_account_page_title",
        label: __("My Account Page Title", "arraysubs"),
        helperText: __(
          'Optional custom heading for the My Account feature page. Leave blank to use "My Features".',
          "arraysubs",
        ),
        showWhen: {
          field: "feature_manager.show_in_my_account",
          operator: "is_true",
        },
      },
      {
        field: "Switch",
        name: "feature_manager.show_usage_count_in_my_account",
        label: __("Show Usage Count in My Account", "arraysubs"),
        helperText: __(
          "Display current feature usage alongside entitlements for customers.",
          "arraysubs",
        ),
        showWhen: {
          field: "feature_manager.show_in_my_account",
          operator: "is_true",
        },
      },
      {
        field: "Switch",
        name: "feature_manager.show_usage_count_in_admin",
        label: __("Show Usage Count in Admin", "arraysubs"),
        helperText: __(
          "Display current feature usage in admin subscription feature views.",
          "arraysubs",
        ),
        showWhen: {
          field: "feature_manager.enabled",
          operator: "is_true",
        },
      },
      {
        field: "Switch",
        name: "feature_manager.show_comparison",
        label: __("Enable Feature Comparison", "arraysubs"),
        helperText: __(
          "Show feature comparison table when customers consider an upgrade",
          "arraysubs",
        ),
        showWhen: {
          field: "feature_manager.enabled",
          operator: "is_true",
        },
      },
    ],
  },

  // Aggregation Settings
  {
    field: "Card",
    children: [
      {
        field: "Title",
        heading: 3,
        text: __("Aggregation Settings", "arraysubs"),
        subText: __(
          "How to handle features when customer has multiple subscriptions",
          "arraysubs",
        ),
      },
      {
        field: "Radio",
        name: "feature_manager.aggregation_mode",
        label: __("Feature Aggregation Mode", "arraysubs"),
        data: [
          {
            value: "per_subscription",
            label: __("Per Subscription", "arraysubs"),
            description: __(
              "Show features separately for each active subscription",
              "arraysubs",
            ),
          },
          {
            value: "combine",
            label: __("Combine", "arraysubs"),
            description: __(
              "Sum numeric values, OR boolean values across subscriptions",
              "arraysubs",
            ),
          },
        ],
        showWhen: {
          field: "feature_manager.enabled",
          operator: "is_true",
        },
      },
    ],
  },
];

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

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

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

  const handleSubmit = async () => {
    setSaving(true);
    try {
      const values = form.getFieldsValue();
      const nestedValues = dotToNested(values);
      await saveSettings(nestedValues);
      showToast(__("Settings saved successfully!", "arraysubs"), "success");
    } catch (error) {
      showToast(__("Failed to save settings", "arraysubs"), "error", 5000);
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <DefaultPageLayout
        title={__("Feature Manager Settings", "arraysubs")}
        subtitle={__(
          "Configure product features and entitlements display",
          "arraysubs",
        )}
      >
        <Skeleton count={5} height={40} />
      </DefaultPageLayout>
    );
  }

  return (
    <DefaultPageLayout
      title={__("Feature Manager Settings", "arraysubs")}
      subtitle={__(
        "Configure product features and entitlements display",
        "arraysubs",
      )}
    >
      <Form form={form} onFinish={handleSubmit}>
        <FormBuilder formItems={formStructure} form={form} />

        <div className="arraysubs-settings-actions arraysubs-bottom-fixed-actions">
          <div>
            <button
              type="submit"
              className="button button-primary"
              disabled={saving}
              onClick={() => form.submit()}
            >
              {saving
                ? __("Saving...", "arraysubs")
                : __("Save Settings", "arraysubs")}
            </button>
          </div>
        </div>
      </Form>

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

export default FeatureManagerSettings;
