/**
 * URL Rules Tab
 *
 * Members Access to URL patterns with flexible conditions
 *
 * @package ArraySubs
 */

import React, { useState, useEffect, useCallback } from "react";
import { __ } from "@wordpress/i18n";
import { buildUrl } from "@libs/url";
import { ToastContainer } from "@libs/toast";
import { useToast } from "@libs/toast/useToast";
import { Skeleton } from "@libs/skeleton";
import RestrictionRuleBuilder, {
  defaultConditionTypes,
} from "@/components/RestrictionRuleBuilder";

/**
 * UrlRulesTab Component
 *
 * Manages URL pattern-based access restrictions
 */
const UrlRulesTab = () => {
  const { env } = window.arraySubs;
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [rules, setRules] = useState([]);
  const { toasts, showToast, removeToast } = useToast();

  /**
   * Pattern types available for URL matching
   */
  const patternTypes = [
    { value: "prefix", label: __("Starts with", "arraysubs") },
    { value: "contains", label: __("Contains", "arraysubs") },
    { value: "exact", label: __("Exact match", "arraysubs") },
    { value: "regex", label: __("Regular expression", "arraysubs") },
  ];

  /**
   * Actions available when access is denied
   */
  const actionTypes = [
    { value: "redirect", label: __("Redirect to URL", "arraysubs") },
    { value: "message", label: __("Show message", "arraysubs") },
    { value: "403", label: __("Show 403 forbidden", "arraysubs") },
    { value: "login", label: __("Redirect to login", "arraysubs") },
  ];

  /**
   * Load settings on mount
   */
  useEffect(() => {
    loadData();
  }, []);

  /**
   * Fetch URL rules
   */
  const loadData = async () => {
    setLoading(true);
    try {
      const response = await fetch(
        buildUrl(`${env?.apiBaseUrl}arraysubs/v1/members-access/settings`, {}),
        { headers: { "X-WP-Nonce": env?.nonce } },
      );

      if (!response.ok) {
        throw new Error(__("Failed to load data", "arraysubs"));
      }

      const data = await response.json();
      setRules(data.data?.url_rules || []);
    } catch (error) {
      console.error("Error loading URL rules:", error);
      showToast(__("Failed to load URL rules", "arraysubs"), "error");
    } finally {
      setLoading(false);
    }
  };

  /**
   * Save rules to server
   */
  const saveRules = async () => {
    setSaving(true);
    try {
      const response = await fetch(
        buildUrl(`${env?.apiBaseUrl}arraysubs/v1/members-access/settings`, {}),
        {
          method: "POST",
          headers: {
            "X-WP-Nonce": env?.nonce,
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            url_rules: rules,
          }),
        },
      );

      if (!response.ok) {
        throw new Error(__("Failed to save rules", "arraysubs"));
      }

      showToast(__("Rules saved successfully!", "arraysubs"), "success");
    } catch (error) {
      console.error("Error saving rules:", error);
      showToast(__("Failed to save rules", "arraysubs"), "error");
    } finally {
      setSaving(false);
    }
  };

  /**
   * Get default rule structure for URL rules
   */
  const getDefaultRule = useCallback(() => {
    return {
      enabled: true,
      name: __("New URL Rule", "arraysubs"),
      priority: 10,
      pattern: "",
      pattern_type: "prefix",
      exclusions: [],
      conditions: { logic: "and", rules: [] },
      action: "redirect",
      redirect_url: "",
      message: "",
      schedule_enabled: false,
      schedule_value: 0,
      schedule_unit: "days",
    };
  }, []);

  /**
   * Render target fields for the TARGET section
   */
  const renderTargetFields = useCallback(
    (rule, updateRule) => {
      return (
        <>
          <div className="arraysubs-rule-field-row">
            {/* Pattern Type */}
            <div className="arraysubs-rule-field">
              <label className="arraysubs-rule-field__label">
                {__("Pattern Type", "arraysubs")}
              </label>
              <select
                value={rule.pattern_type || "prefix"}
                onChange={(e) => updateRule({ pattern_type: e.target.value })}
                className="arraysubs-rule-field__select"
              >
                {patternTypes.map((type) => (
                  <option key={type.value} value={type.value}>
                    {type.label}
                  </option>
                ))}
              </select>
            </div>

            {/* URL Pattern */}
            <div className="arraysubs-rule-field arraysubs-rule-field--wide">
              <label className="arraysubs-rule-field__label">
                {__("URL Pattern", "arraysubs")}
              </label>
              <input
                type="text"
                className="arraysubs-rule-field__input"
                value={rule.pattern || ""}
                onChange={(e) => updateRule({ pattern: e.target.value })}
                placeholder={
                  rule.pattern_type === "prefix"
                    ? __("/members/", "arraysubs")
                    : rule.pattern_type === "regex"
                    ? __("^/premium/.*$", "arraysubs")
                    : __("/premium-content/", "arraysubs")
                }
              />
            </div>

            {/* Priority */}
            <div className="arraysubs-rule-field arraysubs-rule-field--small">
              <label className="arraysubs-rule-field__label">
                {__("Priority", "arraysubs")}
              </label>
              <input
                type="number"
                className="arraysubs-rule-field__input arraysubs-rule-field__input--small"
                value={rule.priority || 10}
                onChange={(e) =>
                  updateRule({ priority: parseInt(e.target.value) || 10 })
                }
                min={1}
                max={100}
              />
            </div>
          </div>

          {/* Exclusions */}
          <div className="arraysubs-rule-field">
            <label className="arraysubs-rule-field__label">
              {__("Exclusions", "arraysubs")}
            </label>
            <input
              type="text"
              className="arraysubs-rule-field__input"
              value={(rule.exclusions || []).join(", ")}
              onChange={(e) =>
                updateRule({
                  exclusions: e.target.value
                    .split(",")
                    .map((s) => s.trim())
                    .filter(Boolean),
                })
              }
              placeholder={__(
                "/members/public/, /members/signup/",
                "arraysubs",
              )}
            />
            <p className="arraysubs-rule-field__help">
              {__(
                "Comma-separated URLs to exclude from this rule",
                "arraysubs",
              )}
            </p>
          </div>
        </>
      );
    },
    [patternTypes],
  );

  /**
   * Render action fields for the THEN section
   */
  const renderActionFields = useCallback(
    (rule, updateRule) => {
      return (
        <>
          {/* Action */}
          <div className="arraysubs-rule-field">
            <label className="arraysubs-rule-field__label">
              {__("Action when denied", "arraysubs")}
            </label>
            <select
              value={rule.action || "redirect"}
              onChange={(e) => updateRule({ action: e.target.value })}
              className="arraysubs-rule-field__select"
            >
              {actionTypes.map((action) => (
                <option key={action.value} value={action.value}>
                  {action.label}
                </option>
              ))}
            </select>
          </div>

          {/* Redirect URL (conditional) */}
          {rule.action === "redirect" && (
            <div className="arraysubs-rule-field">
              <label className="arraysubs-rule-field__label">
                {__("Redirect URL", "arraysubs")}
              </label>
              <input
                type="text"
                className="arraysubs-rule-field__input"
                value={rule.redirect_url || ""}
                onChange={(e) => updateRule({ redirect_url: e.target.value })}
                placeholder={__("/pricing/", "arraysubs")}
              />
            </div>
          )}

          {/* Message (conditional) */}
          {rule.action === "message" && (
            <div className="arraysubs-rule-field">
              <label className="arraysubs-rule-field__label">
                {__("Access Denied Message", "arraysubs")}
              </label>
              <textarea
                className="arraysubs-rule-field__textarea"
                value={rule.message || ""}
                onChange={(e) => updateRule({ message: e.target.value })}
                placeholder={__(
                  "This content is restricted. Please subscribe to access.",
                  "arraysubs",
                )}
                rows={3}
              />
            </div>
          )}
        </>
      );
    },
    [actionTypes],
  );

  /**
   * Render loading state
   */
  if (loading) {
    return (
      <div className="arraysubs-members-access__tab-content">
        <Skeleton count={3} height={100} />
      </div>
    );
  }

  return (
    <div className="arraysubs-members-access__tab-content">
      {/* Header with description */}
      <div className="arraysubs-members-access__section-header">
        <div className="arraysubs-members-access__section-info">
          <h3>{__("URL Rules", "arraysubs")}</h3>
          <p>
            {__(
              "Members Access to specific URL patterns. Rules are processed by priority (lower number = higher priority).",
              "arraysubs",
            )}
          </p>
        </div>
      </div>

      <div className="arraysubs-members-access__info-box">
        <h4>{__("How URL Rules Work", "arraysubs")}</h4>
        <ol>
          <li>
            {__(
              "Define who qualifies using the IF conditions — for example, active members, customers with a matching product purchase, or users with a certain role.",
              "arraysubs",
            )}
          </li>
          <li>
            {__(
              "Choose what to protect in the TARGET section — starts with, contains, exact match, or regular expression — and optionally list exclusions that should stay public.",
              "arraysubs",
            )}
          </li>
          <li>
            {__(
              "Configure the THEN section — redirect the visitor, send them to login, or show an access denied message.",
              "arraysubs",
            )}
          </li>
          <li>
            {__(
              "Rules are processed by priority, so lower numbers run first. This lets you create broad protected areas with specific public exceptions above them.",
              "arraysubs",
            )}
          </li>
          <li>
            {__(
              "When a user meets the conditions, the protected URLs become accessible again without needing separate manual changes on each page.",
              "arraysubs",
            )}
          </li>
        </ol>
        <p className="arraysubs-members-access__info-note">
          <strong>{__("Note:", "arraysubs")}</strong>{" "}
          {__(
            "Use URL Rules for path-based gating such as /members/, /vip/, or landing-page groups. If you need product-specific purchase restrictions, use Ecommerce Rules instead.",
            "arraysubs",
          )}
        </p>
      </div>

      {/* Rule Builder */}
      <RestrictionRuleBuilder
        rules={rules}
        onChange={setRules}
        ruleType="url"
        conditionTypes={defaultConditionTypes}
        renderTargetFields={renderTargetFields}
        renderActionFields={renderActionFields}
        getDefaultRule={getDefaultRule}
        ruleLabel={__("URL Rule", "arraysubs")}
        showSchedule
      />

      {/* Save Button */}
      {rules.length > 0 && (
        <div className="arraysubs-members-access__actions arraysubs-bottom-fixed-actions">
          <div>
            <button
              type="button"
              className="button button-primary"
              onClick={saveRules}
              disabled={saving}
            >
              {saving
                ? __("Saving...", "arraysubs")
                : __("Save Rules", "arraysubs")}
            </button>
          </div>
        </div>
      )}

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

export default UrlRulesTab;
