import React, { useEffect, useState } from "react";
import { __ } from "@wordpress/i18n";
import Form from "rc-field-form";
import DefaultPageLayout from "@/components/DefaultPageLayout";
import SpinnerButton from "@libs/confirm-dialog/SpinnerButton";
import FormBuilder from "@libs/form-builder";
import { Skeleton } from "@libs/skeleton";
import { ToastContainer } from "@libs/toast";
import { useToast } from "@libs/toast/useToast";
import {
  dotToNested,
  fetchSettings,
  nestedToDot,
  saveSettings,
} from "./Settings/settingsHelpers";

const DEFAULT_VALUES = {
  "cart_info_editor.hide_first_billing_cycle_info": false,
  "cart_info_editor.hide_shipping_charge_info": false,
  "cart_info_editor.hide_duration_info": false,
};

const formStructure = [
  {
    field: "Title",
    heading: 3,
    text: __("Cart Info Editor", "arraysubs"),
    subText: __(
      "Choose which subscription details are hidden from customers.",
      "arraysubs",
    ),
  },
  {
    field: "Switch",
    name: "cart_info_editor.hide_first_billing_cycle_info",
    label: __("Hide First billing cycle info", "arraysubs"),
  },
  {
    field: "Switch",
    name: "cart_info_editor.hide_shipping_charge_info",
    label: __("Hide shipping charge info", "arraysubs"),
  },
  {
    field: "Switch",
    name: "cart_info_editor.hide_duration_info",
    label: __("Hide Duration info", "arraysubs"),
  },
];

const getFormValues = (settings) => {
  const savedValues = nestedToDot(settings);

  return Object.keys(DEFAULT_VALUES).reduce(
    (values, key) => ({
      ...values,
      [key]: savedValues[key] ?? DEFAULT_VALUES[key],
    }),
    {},
  );
};

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

  useEffect(() => {
    const loadSettings = async () => {
      try {
        const settings = await fetchSettings();
        const values = getFormValues(settings);

        setFormData(values);
        form.setFieldsValue(values);
      } catch (error) {
        showToast(
          error.message || __("Failed to load settings.", "arraysubs"),
          "error",
        );
      } finally {
        setLoading(false);
      }
    };

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

  const handleSubmit = async (values) => {
    setSaving(true);

    try {
      await saveSettings(dotToNested({ ...DEFAULT_VALUES, ...values }));
      setFormData({ ...DEFAULT_VALUES, ...values });
      showToast(__("Settings saved!", "arraysubs"), "success");
    } catch (error) {
      showToast(
        error.message || __("Failed to save settings.", "arraysubs"),
        "error",
      );
    } finally {
      setSaving(false);
    }
  };

  const handleDiscard = () => {
    form.setFieldsValue(formData);
  };

  if (loading) {
    return (
      <DefaultPageLayout title={__("Cart Info Editor", "arraysubs")}>
        <Skeleton variant="rectangle" width="100%" height={260} />
        <ToastContainer toasts={toasts} removeToast={removeToast} />
      </DefaultPageLayout>
    );
  }

  return (
    <DefaultPageLayout
      title={__("Cart Info Editor", "arraysubs")}
      subtitle={__(
        "Control the subscription details shown throughout the purchasing experience.",
        "arraysubs",
      )}
    >
      <Form form={form} onFinish={handleSubmit} layout="vertical">
        <div className="arraysubs-fb-card">
          <FormBuilder formItems={formStructure} form={form} />
        </div>

        <div className="arraysubs-settings-actions arraysubs-bottom-fixed-actions">
          <div>
            <SpinnerButton
              type="submit"
              className="button button-primary"
              loading={saving}
              loadingText={__("Saving…", "arraysubs")}
            >
              {__("Save Settings", "arraysubs")}
            </SpinnerButton>
            <button
              type="button"
              className="button"
              onClick={handleDiscard}
              disabled={saving}
            >
              {__("Discard Changes", "arraysubs")}
            </button>
          </div>
        </div>
      </Form>

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

export default CartInfoEditor;
