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 Skip & Pause settings
const formStructure = [
  // Skip Renewal Settings
  {
    field: "Card",
    children: [
      {
        field: "Title",
        heading: 3,
        text: __("Skip Next Renewal", "arraysubs"),
        subText: __(
          "Allow customers and admins to skip upcoming billing cycles without cancelling",
          "arraysubs",
        ),
      },
      {
        field: "Switch",
        name: "skip_renewal.enabled",
        label: __("Enable Skip Renewal", "arraysubs"),
        helperText: __(
          "When enabled, subscriptions can skip upcoming renewal cycles",
          "arraysubs",
        ),
      },
      {
        field: "AutoGrid",
        cols: 2,
        showWhen: {
          field: "skip_renewal.enabled",
          operator: "is_true",
        },
        children: [
          {
            field: "Number",
            name: "skip_renewal.max_cycles",
            label: __("Maximum Cycles to Skip", "arraysubs"),
            min: 1,
            max: 12,
            helperText: __(
              "Maximum number of billing cycles that can be skipped at once",
              "arraysubs",
            ),
          },
          {
            field: "Number",
            name: "skip_renewal.cutoff_days",
            label: __("Skip Cutoff (Days)", "arraysubs"),
            min: 0,
            max: 30,
            helperText: __(
              "Days before renewal when skip is no longer allowed",
              "arraysubs",
            ),
          },
        ],
      },
      {
        field: "Switch",
        name: "skip_renewal.customer_can_skip",
        label: __("Allow Customers to Skip", "arraysubs"),
        helperText: __(
          "Enable skip controls in the customer My Account portal",
          "arraysubs",
        ),
        showWhen: {
          field: "skip_renewal.enabled",
          operator: "is_true",
        },
      },
      {
        field: "Alert",
        type: "info",
        message: __(
          "When a customer skips cycles, their next payment date is pushed forward by the skipped period. The subscription remains active.",
          "arraysubs",
        ),
        showWhen: {
          field: "skip_renewal.enabled",
          operator: "is_true",
        },
      },
    ],
  },

  // Pause Subscription Settings
  {
    field: "Card",
    children: [
      {
        field: "Title",
        heading: 3,
        text: __("Pause Subscription (Vacation Mode)", "arraysubs"),
        subText: __(
          "Allow customers and admins to temporarily pause subscriptions",
          "arraysubs",
        ),
      },
      {
        field: "Switch",
        name: "pause_subscription.enabled",
        label: __("Enable Pause Subscription", "arraysubs"),
        helperText: __(
          "When enabled, subscriptions can be temporarily paused",
          "arraysubs",
        ),
      },
      {
        field: "AutoGrid",
        cols: 2,
        showWhen: {
          field: "pause_subscription.enabled",
          operator: "is_true",
        },
        children: [
          {
            field: "Number",
            name: "pause_subscription.max_duration_days",
            label: __("Maximum Pause Duration (Days)", "arraysubs"),
            min: 1,
            max: 365,
            helperText: __(
              "Maximum number of days a subscription can be paused",
              "arraysubs",
            ),
          },
          {
            field: "Number",
            name: "pause_subscription.max_pauses_per_subscription",
            label: __("Maximum Pauses per Subscription", "arraysubs"),
            min: 1,
            max: 10,
            helperText: __(
              "How many times a subscription can be paused in its lifetime",
              "arraysubs",
            ),
          },
        ],
      },
      {
        field: "Number",
        name: "pause_subscription.min_days_between_pauses",
        label: __("Cooldown Between Pauses (Days)", "arraysubs"),
        min: 0,
        max: 365,
        helperText: __(
          "Minimum days that must pass before a subscription can be paused again",
          "arraysubs",
        ),
        showWhen: {
          field: "pause_subscription.enabled",
          operator: "is_true",
        },
      },
      {
        field: "Divider",
        showWhen: {
          field: "pause_subscription.enabled",
          operator: "is_true",
        },
      },
      {
        field: "Switch",
        name: "pause_subscription.customer_can_pause",
        label: __("Allow Customers to Pause", "arraysubs"),
        helperText: __(
          "Enable pause controls in the customer My Account portal",
          "arraysubs",
        ),
        showWhen: {
          field: "pause_subscription.enabled",
          operator: "is_true",
        },
      },
      {
        field: "Switch",
        name: "pause_subscription.require_reason",
        label: __("Require Pause Reason", "arraysubs"),
        helperText: __(
          "Customers must provide a reason when pausing their subscription",
          "arraysubs",
        ),
        showWhen: {
          field: "pause_subscription.enabled",
          operator: "is_true",
        },
      },
      {
        field: "Alert",
        type: "warning",
        message: __(
          "During a pause, the subscription status changes to On-Hold, no charges occur, and the subscription end date is extended by the pause duration.",
          "arraysubs",
        ),
        showWhen: {
          field: "pause_subscription.enabled",
          operator: "is_true",
        },
      },
    ],
  },

  // Access During Pause
  {
    field: "Card",
    showWhen: {
      field: "pause_subscription.enabled",
      operator: "is_true",
    },
    children: [
      {
        field: "Title",
        heading: 3,
        text: __("Access During Pause", "arraysubs"),
        subText: __(
          "Configure what access customers have while paused",
          "arraysubs",
        ),
      },
      {
        field: "Select",
        name: "pause_subscription.access_during_pause",
        label: __("Content Access", "arraysubs"),
        data: [
          {
            value: "none",
            label: __("No access (fully restricted)", "arraysubs"),
          },
          {
            value: "limited",
            label: __("Limited access (view-only)", "arraysubs"),
          },
          {
            value: "full",
            label: __("Full access (same as active)", "arraysubs"),
          },
        ],
        helperText: __(
          "Determines what restricted content customers can access while paused",
          "arraysubs",
        ),
      },
      {
        field: "Alert",
        type: "info",
        message: __(
          "This setting works with the Members Access feature. If Members Access is disabled, this setting has no effect.",
          "arraysubs",
        ),
      },
    ],
  },
];

const SkipPauseSettings = () => {
  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 () => {
    try {
      const data = await fetchSettings();
      const flatData = nestedToDot(data);
      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={__("Skip & Pause", "arraysubs")}>
        <Skeleton variant="rectangle" width="100%" height={400} />
      </DefaultPageLayout>
    );
  }

  return (
    <DefaultPageLayout
      title={__("Skip & Pause", "arraysubs")}
      subtitle={__(
        "Configure skip renewal and pause subscription settings",
        "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 SkipPauseSettings;
