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 Plan Switching settings
const formStructure = [
  // Enable/Disable
  {
    field: "Card",
    children: [
      {
        field: "Title",
        heading: 3,
        text: __("Plan Switching", "arraysubs"),
        subText: __(
          "Allow customers to upgrade, downgrade, or change their subscription plans",
          "arraysubs",
        ),
      },
      {
        field: "Switch",
        name: "plan_switching.enabled",
        label: __("Enable Plan Switching", "arraysubs"),
      },
      {
        field: "Alert",
        type: "info",
        message: __(
          "Plan switching allows customers to change their subscription to a different product or variation. You must configure upgrade/downgrade paths in each product's settings.",
          "arraysubs",
        ),
      },
    ],
  },

  // Switch Types
  {
    field: "Card",
    showWhen: {
      field: "plan_switching.enabled",
      operator: "=",
      value: true,
    },
    children: [
      {
        field: "Title",
        heading: 3,
        text: __("Allowed Switch Types", "arraysubs"),
        subText: __(
          "Control which types of plan changes are allowed",
          "arraysubs",
        ),
      },
      {
        field: "Switch",
        name: "plan_switching.allow_upgrades",
        label: __("Allow Upgrades", "arraysubs"),
      },
      {
        field: "Switch",
        name: "plan_switching.allow_downgrades",
        label: __("Allow Downgrades", "arraysubs"),
      },
      {
        field: "Switch",
        name: "plan_switching.allow_crossgrades",
        label: __("Allow Crossgrades (Same Tier)", "arraysubs"),
      },
      {
        field: "Divider",
      },
      {
        field: "Switch",
        name: "plan_switching.allow_customer_switch",
        label: __("Allow Customer-Initiated Switches", "arraysubs"),
      },
      {
        field: "Alert",
        type: "info",
        message: __(
          "When enabled, customers can initiate plan switches from their My Account area. When disabled, only admins can change subscription plans.",
          "arraysubs",
        ),
      },
    ],
  },

  // Proration Settings
  {
    field: "Card",
    showWhen: {
      field: "plan_switching.enabled",
      operator: "=",
      value: true,
    },
    children: [
      {
        field: "Title",
        heading: 3,
        text: __("Proration Settings", "arraysubs"),
        subText: __("How to handle billing when switching plans", "arraysubs"),
      },
      {
        field: "Select",
        name: "plan_switching.proration_type",
        label: __("Default Proration Type", "arraysubs"),
        data: [
          {
            label: __("Prorate Immediately", "arraysubs"),
            value: "prorate_immediately",
          },
          {
            label: __("Apply at Next Renewal", "arraysubs"),
            value: "apply_at_renewal",
          },
          {
            label: __("No Proration", "arraysubs"),
            value: "no_proration",
          },
        ],
      },
      {
        field: "Alert",
        type: "info",
        title: __("Proration Types Explained", "arraysubs"),
        message: __(
          "Prorate Immediately: Calculate credit/charge for remaining time and process immediately. Apply at Renewal: New plan pricing takes effect at next renewal. No Proration: Switch immediately with no billing adjustment.",
          "arraysubs",
        ),
      },
      {
        field: "Divider",
      },
      {
        field: "Select",
        name: "proration.rounding_method",
        label: __("Proration Rounding", "arraysubs"),
        data: [
          { label: __("Round to nearest cent", "arraysubs"), value: "round" },
          { label: __("Round up", "arraysubs"), value: "round_up" },
          { label: __("Round down", "arraysubs"), value: "round_down" },
        ],
      },
      {
        field: "Number",
        name: "proration.minimum_charge",
        label: __("Minimum Proration Charge", "arraysubs"),
        min: 0,
        step: 0.01,
      },
      {
        field: "Alert",
        type: "info",
        message: __(
          "If the calculated proration amount is less than this, no charge will be made.",
          "arraysubs",
        ),
      },
    ],
  },

  // Switch Fees
  {
    field: "Card",
    showWhen: {
      field: "plan_switching.enabled",
      operator: "=",
      value: true,
    },
    children: [
      {
        field: "Title",
        heading: 3,
        text: __("Switch Fees (Optional)", "arraysubs"),
        subText: __("Add a fee when customers switch plans", "arraysubs"),
      },
      {
        field: "AutoGrid",
        cols: 3,
        children: [
          {
            field: "Number",
            name: "proration.switch_fees.upgrade",
            label: __("Upgrade Fee", "arraysubs"),
            min: 0,
            step: 0.01,
          },
          {
            field: "Number",
            name: "proration.switch_fees.downgrade",
            label: __("Downgrade Fee", "arraysubs"),
            min: 0,
            step: 0.01,
          },
          {
            field: "Number",
            name: "proration.switch_fees.crossgrade",
            label: __("Crossgrade Fee", "arraysubs"),
            min: 0,
            step: 0.01,
          },
        ],
      },
      {
        field: "Alert",
        type: "info",
        message: __(
          "These fees will be added to any proration charge when the customer switches plans. Set to 0 for no fee.",
          "arraysubs",
        ),
      },
    ],
  },

  // Auto-Downgrade
  {
    field: "Card",
    children: [
      {
        field: "Title",
        heading: 3,
        text: __("Auto-Downgrade", "arraysubs"),
        subText: __(
          "Automatically switch subscriptions to a fallback plan when they expire or are cancelled",
          "arraysubs",
        ),
      },
      {
        field: "Select",
        name: "plan_switching.auto_downgrade_timing",
        label: __("Auto-Downgrade Timing", "arraysubs"),
        data: [
          {
            label: __("On Expiration", "arraysubs"),
            value: "on_expire",
          },
          {
            label: __("On Cancellation", "arraysubs"),
            value: "on_cancel",
          },
          {
            label: __("On Trial Expiry", "arraysubs"),
            value: "on_trial_expire",
          },
        ],
      },
      {
        field: "Alert",
        type: "info",
        title: __("Auto-Downgrade Setup", "arraysubs"),
        message: __(
          "Configure target products in each subscription product's Linked Products tab. The auto-downgrade product field determines which plan the subscription switches to. If no target is set, no downgrade occurs.",
          "arraysubs",
        ),
      },
    ],
  },
];

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

  return (
    <DefaultPageLayout
      title={__("Plan Switching", "arraysubs")}
      subtitle={__(
        "Configure upgrade, downgrade, and crossgrade options",
        "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 PlanSwitchingSettings;
