/**
 * Checkout Builder — Main admin page.
 *
 * Landing view:  "Open Builder" button.
 * Fullscreen:    Builder workspace with toolbar (save/discard/reset/back).
 *
 * @package ArraySubsPro
 */
import React, { useState, useEffect, useCallback } from "react";
import { __ } from "@wordpress/i18n";
import {
  RotateCcw,
  AlertTriangle,
  ArrowLeft,
  Maximize2,
  Settings,
} from "lucide-react";
import DefaultPageLayout from "@/components/DefaultPageLayout";
import { Skeleton } from "@libs/skeleton";
import { ToastContainer } from "@libs/toast";
import { useToast } from "@libs/toast/useToast";
import { useConfirm } from "@libs/confirm-dialog";
import { fetchConfig, saveConfig, fetchDefaults, fetchFieldTypes } from "./api";
import MultistepModeEditor, { buildDefaultSteps } from "./MultistepModeEditor";
import { DEFAULT_DESIGN, buildSingleStepFromSections } from "./utils";

const CheckoutBuilder = () => {
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [builderOpen, setBuilderOpen] = useState(false);
  const [builderConfig, setBuilderConfig] = useState(null);
  const [snapshot, setSnapshot] = useState(null);
  const [wcDefaults, setWcDefaults] = useState(null);
  const [fieldTypes, setFieldTypes] = useState({});
  const [enabled, setEnabled] = useState(false);
  const { toasts, showToast, removeToast } = useToast();
  const { confirm, confirmDialog } = useConfirm();

  const normalizeBuilderConfig = useCallback((data, wcDefaultSections) => {
    const multistepConfig = data?.multistep || {};
    let steps = multistepConfig.steps || [];

    if (!steps.length && data?.default?.sections?.length) {
      steps = [buildSingleStepFromSections(data.default.sections)];
    }

    if (!steps.length) {
      steps = buildDefaultSteps({ sections: wcDefaultSections });
    }

    return {
      design: multistepConfig.design || DEFAULT_DESIGN,
      steps,
    };
  }, []);

  const loadConfig = useCallback(async () => {
    setLoading(true);
    try {
      const [config, defaults, types] = await Promise.all([
        fetchConfig(),
        fetchDefaults(),
        fetchFieldTypes(),
      ]);

      const data = config?.data || config || {};
      const wcDefaultData = defaults?.data || defaults || {};
      const wcDefaultSections = wcDefaultData.sections || [];
      const fieldTypeData = types?.data || types || {};

      setEnabled(Boolean(data.enabled));
      setFieldTypes(fieldTypeData);

      const normalizedConfig = normalizeBuilderConfig(data, wcDefaultSections);

      setBuilderConfig(normalizedConfig);
      setWcDefaults(wcDefaultData);

      setSnapshot(normalizedConfig);
    } catch (err) {
      showToast(
        err.message || __("Failed to load configuration.", "arraysubs"),
        "error",
      );
    } finally {
      setLoading(false);
    }
  }, [showToast]);

  useEffect(() => {
    loadConfig();
  }, [loadConfig]);

  /* ── Hide WP admin chrome while fullscreen ─────────── */

  useEffect(() => {
    const cls = "arraysubs-cb-fullscreen-active";
    if (builderOpen) {
      document.body.classList.add(cls);
    } else {
      document.body.classList.remove(cls);
    }
    return () => document.body.classList.remove(cls);
  }, [builderOpen]);

  const handleSave = async () => {
    setSaving(true);
    try {
      const payload = {
        mode: "multistep",
        multistep: builderConfig,
      };
      await saveConfig(payload);

      setSnapshot({ ...builderConfig });
      showToast(__("Configuration saved!", "arraysubs"), "success");
    } catch (err) {
      showToast(
        err.message || __("Failed to save configuration.", "arraysubs"),
        "error",
      );
    } finally {
      setSaving(false);
    }
  };

  const handleDiscard = () => {
    if (!snapshot) return;
    setBuilderConfig(snapshot);
    showToast(__("Changes discarded.", "arraysubs"), "info");
  };

  const handleReset = async () => {
    try {
      await confirm({
        title: __("Reset Checkout Builder", "arraysubs"),
        message: __(
          "Reset to WooCommerce defaults? Your custom configuration will be lost.",
          "arraysubs",
        ),
        confirmText: __("Reset to Defaults", "arraysubs"),
        loadingText: __("Resetting…", "arraysubs"),
        variant: "danger",
        onConfirm: async () => {
          const defaults = await fetchDefaults();
          const data = defaults?.data || defaults || {};
          const normalizedConfig = {
            design: DEFAULT_DESIGN,
            steps: buildDefaultSteps(data),
          };

          setBuilderConfig(normalizedConfig);
          setSnapshot(normalizedConfig);
          showToast(
            __("Configuration reset to WooCommerce defaults.", "arraysubs"),
            "info",
          );
        },
      });
    } catch (err) {
      showToast(
        err.message || __("Failed to load defaults.", "arraysubs"),
        "error",
      );
    }
  };

  /* ── Loading skeleton ──────────────────────────────── */

  if (loading) {
    return (
      <DefaultPageLayout title={__("Checkout Builder", "arraysubs")}>
        <Skeleton variant="rectangle" width="100%" height={400} />
      </DefaultPageLayout>
    );
  }

  /* ── Fullscreen builder ────────────────────────────── */

  if (builderOpen) {
    return (
      <div className="arraysubs-cb-fullscreen">
        <div className="arraysubs-cb-fullscreen__toolbar">
          <div className="arraysubs-cb-fullscreen__toolbar-left">
            <button
              type="button"
              className="arraysubs-cb-fullscreen__back button flex-button"
              onClick={() => setBuilderOpen(false)}
            >
              <ArrowLeft size={16} />
              {__("Back", "arraysubs")}
            </button>
            <span className="arraysubs-cb-fullscreen__title">
              {__("Checkout Builder", "arraysubs")}
            </span>
          </div>

          <div className="arraysubs-cb-fullscreen__toolbar-right">
            <button
              type="button"
              className="button arraysubs-cb-fullscreen__reset-btn flex-button"
              onClick={handleReset}
              disabled={saving}
            >
              <RotateCcw size={13} />
              {__("Reset", "arraysubs")}
            </button>
            <button
              type="button"
              className="button"
              onClick={handleDiscard}
              disabled={saving}
            >
              {__("Discard", "arraysubs")}
            </button>
            <button
              type="button"
              className="button button-primary"
              onClick={handleSave}
              disabled={saving}
            >
              {saving ? __("Saving…", "arraysubs") : __("Save", "arraysubs")}
            </button>
          </div>
        </div>

        <div className="arraysubs-cb-fullscreen__body">
          <MultistepModeEditor
            config={builderConfig}
            onChange={setBuilderConfig}
            wcDefaults={wcDefaults}
            fieldTypes={fieldTypes}
          />
        </div>

        {confirmDialog}
        <ToastContainer toasts={toasts} removeToast={removeToast} />
      </div>
    );
  }

  /* ── Landing page ──────────────────────────────────── */

  return (
    <DefaultPageLayout
      title={__("Checkout Builder", "arraysubs")}
      subtitle={__(
        "Customize your WooCommerce checkout experience.",
        "arraysubs",
      )}
    >
      <div className="arraysubs-cb-landing">
        <div className="arraysubs-cb-landing__card">
          {!enabled && (
            <div className="arraysubs-cb-warning">
              <AlertTriangle size={18} />
              <span>
                {__(
                  "The Checkout Builder is currently disabled. Your changes will be saved but won't appear on the frontend until you enable the feature in",
                  "arraysubs",
                )}{" "}
                <a href="#/checkout-builder/settings">
                  {__("Checkout Builder Settings", "arraysubs")}
                </a>
                .
              </span>
            </div>
          )}

          <Maximize2 size={36} className="arraysubs-cb-landing__icon" />
          <h3 className="arraysubs-cb-landing__heading">
            {__("Checkout Form Builder", "arraysubs")}
          </h3>
          <p className="arraysubs-cb-landing__desc">
            {__(
              "Drag and drop fields, sections, and layout elements to build your custom checkout experience.",
              "arraysubs",
            )}
          </p>

          <div className="arraysubs-cb-landing__actions">
            <button
              type="button"
              className="button button-primary button-hero arraysubs-cb-landing__open flex-button"
              onClick={() => setBuilderOpen(true)}
            >
              <Maximize2 size={18} />
              {__("Open Builder", "arraysubs")}
            </button>

            <a
              href="#/checkout-builder/settings"
              className="arraysubs-cb-landing__settings-link"
            >
              <Settings size={16} />
              {__("Checkout Builder Settings", "arraysubs")}
            </a>
          </div>
        </div>
        <div className="arraysubs-cb-landing__help">
          <div className="arraysubs-cb-landing__help-card">
            <h4 className="arraysubs-cb-landing__help-title">
              {__("How to use the Checkout Builder", "arraysubs")}
            </h4>
            <p className="arraysubs-cb-landing__help-note">
              <strong>{__("Important:", "arraysubs")}</strong>{" "}
              {__(
                "To make your builder layout effective on the frontend, use the classic WooCommerce checkout page or place the",
                "arraysubs",
              )}{" "}
              <code>[woocommerce_checkout]</code>{" "}
              {__(
                "shortcode on your checkout page. If the page is using the WooCommerce Checkout block, this editor layout will not be applied the same way.",
                "arraysubs",
              )}
            </p>
            <ol className="arraysubs-cb-landing__help-list">
              <li>
                <strong>{__("Open the editor:", "arraysubs")}</strong>{" "}
                {__(
                  "Click Open Builder to launch the fullscreen editor and start working on your checkout layout.",
                  "arraysubs",
                )}
              </li>
              <li>
                <strong>{__("Arrange your steps:", "arraysubs")}</strong>{" "}
                {__(
                  "Keep one step for a regular single-page checkout, or add more steps to turn the frontend into a multi-step checkout flow.",
                  "arraysubs",
                )}
              </li>
              <li>
                <strong>{__("Build each step:", "arraysubs")}</strong>{" "}
                {__(
                  "Drag in fields, sections, headings, alerts, and other layout elements, then reorder them until the checkout matches the experience you want customers to follow.",
                  "arraysubs",
                )}
              </li>
              <li>
                <strong>{__("Place payment correctly:", "arraysubs")}</strong>{" "}
                {__(
                  "Keep the Order Info and Payment element in the step where you want the order summary, payment methods, and final place-order area to appear.",
                  "arraysubs",
                )}
              </li>
              <li>
                <strong>{__("Save and test:", "arraysubs")}</strong>{" "}
                {__(
                  "Save your builder changes, make sure the feature is enabled in Checkout Builder Settings, and then test the live checkout page from start to finish.",
                  "arraysubs",
                )}
              </li>
            </ol>
          </div>

          <div className="arraysubs-cb-landing__help-card">
            <h4 className="arraysubs-cb-landing__help-title">
              {__("How the checkout flow works", "arraysubs")}
            </h4>
            <ol className="arraysubs-cb-landing__help-list">
              <li>
                <strong>{__("One configured step:", "arraysubs")}</strong>{" "}
                {__(
                  "The checkout behaves like a normal single-page checkout and no step navigation is shown to the customer.",
                  "arraysubs",
                )}
              </li>
              <li>
                <strong>{__("Two or more steps:", "arraysubs")}</strong>{" "}
                {__(
                  "The checkout becomes a multi-step flow, and customers move through the steps in the order you define in the builder.",
                  "arraysubs",
                )}
              </li>
              <li>
                <strong>{__("Element order matters:", "arraysubs")}</strong>{" "}
                {__(
                  "Fields, sections, and layout blocks are rendered in the same order you arrange them inside each step.",
                  "arraysubs",
                )}
              </li>
              <li>
                <strong>{__("Final review and payment:", "arraysubs")}</strong>{" "}
                {__(
                  "The step containing the Order Info and Payment element becomes the customer’s review and payment stage before the order is submitted.",
                  "arraysubs",
                )}
              </li>
              <li>
                <strong>
                  {__("Validation happens on checkout:", "arraysubs")}
                </strong>{" "}
                {__(
                  "Required fields and checkout validation are enforced when the customer completes the checkout, so always run a real frontend test after major layout changes.",
                  "arraysubs",
                )}
              </li>
            </ol>
          </div>
        </div>
      </div>

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

export default CheckoutBuilder;
