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 Refunds settings
const formStructure = [
  // Refund Behavior
  {
    field: "Card",
    children: [
      {
        field: "Title",
        heading: 3,
        text: __("Refund Settings", "arraysubs"),
        subText: __(
          "Configure how subscription refunds are processed",
          "arraysubs",
        ),
      },
      {
        field: "Radio",
        name: "refunds.cancellation_behavior",
        label: __("Refund on Cancellation", "arraysubs"),
        orientation: "vertical",
        data: [
          {
            label: __("Allow Immediate Refund", "arraysubs"),
            value: "immediate",
          },
          {
            label: __("Refund at End of Period", "arraysubs"),
            value: "end_of_period",
          },
          {
            label: __("No Automatic Refund", "arraysubs"),
            value: "none",
          },
        ],
      },
      {
        field: "Alert",
        type: "info",
        message: __(
          "This determines what refund options are available when a subscription is cancelled. Admins can always issue manual refunds from the order page.",
          "arraysubs",
        ),
      },
    ],
  },

  // Gateway Refunds
  {
    field: "Card",
    children: [
      {
        field: "Title",
        heading: 3,
        text: __("Gateway Refunds", "arraysubs"),
        subText: __(
          "Automatic refund processing through payment gateways",
          "arraysubs",
        ),
      },
      {
        field: "Switch",
        name: "refunds.auto_gateway_refund",
        label: __("Automatic Gateway Refund", "arraysubs"),
      },
      {
        field: "Alert",
        type: "info",
        message: __(
          "When enabled, refunds will be sent through the active WooCommerce payment gateway when supported. When disabled, refunds are recorded in WooCommerce and can be completed manually outside the plugin.",
          "arraysubs",
        ),
      },
    ],
  },

  // Prorated Refunds
  {
    field: "Card",
    children: [
      {
        field: "Title",
        heading: 3,
        text: __("Prorated Refunds", "arraysubs"),
        subText: __(
          "Allow refunds based on unused subscription time",
          "arraysubs",
        ),
      },
      {
        field: "Switch",
        name: "refunds.allow_prorated_refunds",
        label: __("Allow Prorated Refunds", "arraysubs"),
      },
      {
        field: "Alert",
        type: "info",
        message: __(
          "When enabled, admins can issue prorated refunds based on the unused days remaining in the current billing cycle. The refund amount is calculated automatically.",
          "arraysubs",
        ),
      },
      {
        field: "Divider",
      },
      {
        field: "Number",
        name: "refunds.minimum_amount",
        label: __("Minimum Refund Amount", "arraysubs"),
        min: 0,
        step: 0.01,
      },
      {
        field: "Alert",
        type: "info",
        message: __(
          "Refunds below this amount will not be processed. This helps avoid processing fees on very small refunds. Set to 0 to allow any amount.",
          "arraysubs",
        ),
      },
    ],
  },
];

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

  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={__("Refunds", "arraysubs")}>
        <Skeleton variant="rectangle" width="100%" height={400} />
      </DefaultPageLayout>
    );
  }

  return (
    <DefaultPageLayout
      title={__("Refunds", "arraysubs")}
      subtitle={__("Configure refund policies", "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 RefundsSettings;
