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";

// Form structure for Store Credit settings
const formStructure = [
  // General Settings
  {
    field: "Card",
    children: [
      {
        field: "Title",
        heading: 3,
        text: __("Store Credit Settings", "arraysubs"),
        subText: __(
          "Configure how store credits work in your subscription system",
          "arraysubs",
        ),
      },
      {
        field: "Switch",
        name: "store_credit.enabled",
        label: __("Enable Store Credit System", "arraysubs"),
      },
      {
        field: "Alert",
        type: "info",
        message: __(
          "When enabled, customers can accumulate store credits from downgrades, refunds, or promotional offers and use them for future renewals or purchases.",
          "arraysubs",
        ),
      },
    ],
  },

  // Credit Application
  {
    field: "Card",
    children: [
      {
        field: "Title",
        heading: 3,
        text: __("Credit Application", "arraysubs"),
        subText: __("Configure when and how credits are applied", "arraysubs"),
      },
      {
        field: "Switch",
        name: "store_credit.auto_apply_to_renewals",
        label: __("Auto-Apply to Renewals", "arraysubs"),
      },
      {
        field: "Alert",
        type: "info",
        message: __(
          "When enabled, available credits will automatically be applied to subscription renewal orders to reduce the payment amount.",
          "arraysubs",
        ),
      },
      {
        field: "Divider",
      },
      {
        field: "Switch",
        name: "store_credit.apply_at_checkout",
        label: __("Allow at Checkout", "arraysubs"),
      },
      {
        field: "Alert",
        type: "info",
        message: __(
          "When enabled, customers can use their store credits at checkout for new subscription purchases.",
          "arraysubs",
        ),
      },
      {
        field: "Divider",
      },
      {
        field: "Number",
        name: "store_credit.min_order_amount",
        label: __("Minimum Order Amount", "arraysubs"),
        min: 0,
        step: 0.01,
      },
      {
        field: "Alert",
        type: "info",
        message: __(
          "Credits can only be applied to orders above this amount. Set to 0 to allow any order amount.",
          "arraysubs",
        ),
      },
    ],
  },

  // Credit Expiration
  {
    field: "Card",
    children: [
      {
        field: "Title",
        heading: 3,
        text: __("Credit Expiration", "arraysubs"),
        subText: __("Configure credit expiration settings", "arraysubs"),
      },
      {
        field: "Number",
        name: "store_credit.expiration_days",
        label: __("Expiration Period (Days)", "arraysubs"),
        min: 0,
        step: 1,
      },
      {
        field: "Alert",
        type: "info",
        message: __(
          "Number of days before credits expire. Set to 0 for credits that never expire.",
          "arraysubs",
        ),
      },
    ],
  },

  // Credit Purchase
  {
    field: "Card",
    children: [
      {
        field: "Title",
        heading: 3,
        text: __("Credit Purchase", "arraysubs"),
        subText: __("Allow customers to purchase store credits", "arraysubs"),
      },
      {
        field: "Switch",
        name: "store_credit.enable_purchase",
        label: __("Enable Credit Purchases", "arraysubs"),
      },
      {
        field: "Alert",
        type: "info",
        message: __(
          "When enabled, customers can purchase store credits via WooCommerce orders.",
          "arraysubs",
        ),
      },
      {
        field: "Divider",
      },
      {
        field: "Number",
        name: "store_credit.min_purchase_amount",
        label: __("Minimum Purchase Amount", "arraysubs"),
        min: 1,
        step: 1,
      },
      {
        field: "Number",
        name: "store_credit.max_purchase_amount",
        label: __("Maximum Purchase Amount", "arraysubs"),
        min: 1,
        step: 1,
      },
      {
        field: "Number",
        name: "store_credit.default_purchase_amount",
        label: __("Default Purchase Amount", "arraysubs"),
        min: 1,
        step: 1,
      },
    ],
  },
];

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

  // Load settings
  useEffect(() => {
    const loadSettings = async () => {
      try {
        const response = await fetch(
          `${env?.apiBaseUrl}arraysubs/v1/store-credit/settings`,
          {
            headers: {
              "X-WP-Nonce": env?.nonce,
            },
          },
        );

        const data = await response.json();
        if (data.success) {
          // Convert nested object to dot notation for form
          const flatSettings = {};
          Object.entries(data.data).forEach(([key, value]) => {
            flatSettings[`store_credit.${key}`] = value;
          });
          form.setFieldsValue(flatSettings);
        }
      } catch (error) {
        console.error("Load settings error:", error);
        showToast(__("Failed to load settings", "arraysubs"), "error");
      } finally {
        setLoading(false);
      }
    };

    loadSettings();
  }, [env, form]);

  // Save settings
  const handleSave = async (values) => {
    setSaving(true);
    try {
      // Convert dot notation back to nested object
      const settings = {};
      Object.entries(values).forEach(([key, value]) => {
        const parts = key.split(".");
        if (parts[0] === "store_credit" && parts[1]) {
          settings[parts[1]] = value;
        }
      });

      const response = await fetch(
        `${env?.apiBaseUrl}arraysubs/v1/store-credit/settings`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-WP-Nonce": env?.nonce,
          },
          body: JSON.stringify({ settings }),
        },
      );

      const data = await response.json();
      if (data.success) {
        showToast(__("Settings saved successfully", "arraysubs"), "success");
      } else {
        showToast(
          data.message || __("Failed to save settings", "arraysubs"),
          "error",
        );
      }
    } catch (error) {
      console.error("Save settings error:", error);
      showToast(__("Failed to save settings", "arraysubs"), "error");
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <DefaultPageLayout title={__("Store Credit Settings", "arraysubs")}>
        <Skeleton height={400} />
      </DefaultPageLayout>
    );
  }

  return (
    <DefaultPageLayout
      title={__("Store Credit Settings", "arraysubs")}
      subtitle={__("Configure store credit behavior and options", "arraysubs")}
    >
      <Form
        form={form}
        onFinish={handleSave}
        initialValues={{
          "store_credit.enabled": true,
          "store_credit.auto_apply_to_renewals": true,
          "store_credit.apply_at_checkout": false,
          "store_credit.min_order_amount": 0,
          "store_credit.expiration_days": 0,
          "store_credit.enable_purchase": false,
          "store_credit.min_purchase_amount": 10,
          "store_credit.max_purchase_amount": 500,
          "store_credit.default_purchase_amount": 50,
        }}
      >
        <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>
          </div>
        </div>
      </Form>

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

export default StoreCreditSettings;
