// QuickCreateRuleController - Handles the quick create rule form functionality
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ["form", "toggle", "ruleTypeSelect", "actionSelect", "patternFields", "rateLimitFields", "redirectFields", "helpText", "conditionsField", "expiresAtField"]

  connect() {
    console.log("QuickCreateRuleController connected")
    this.initializeFieldVisibility()
  }

  toggle() {
    console.log("Toggle method called")
    console.log("Form target:", this.formTarget)

    if (this.formTarget) {
      this.formTarget.classList.toggle("hidden")
      console.log("Toggled hidden class, now:", this.formTarget.classList.contains("hidden"))

      if (this.formTarget.classList.contains("hidden")) {
        this.resetForm()
      } else {
        // Form is being shown, clear the expires_at field for Safari
        this.clearExpiresAtField()
      }
    } else {
      console.error("Form target not found!")
    }
  }

  updateRuleTypeFields() {
    if (!this.hasRuleTypeSelectTarget || !this.hasActionSelectTarget) return

    const ruleType = this.ruleTypeSelectTarget.value
    const action = this.actionSelectTarget.value

    // Hide all optional fields
    this.hideOptionalFields()

    // Show relevant fields based on rule type
    if (["path_pattern"].includes(ruleType)) {
      if (this.hasPatternFieldsTarget) {
        this.patternFieldsTarget.classList.remove("hidden")
        this.updatePatternHelpText(ruleType)
      }
    } else if (ruleType === "rate_limit") {
      if (this.hasRateLimitFieldsTarget) {
        this.rateLimitFieldsTarget.classList.remove("hidden")
      }
    }

    // Show redirect fields if action is redirect
    if (action === "redirect") {
      if (this.hasRedirectFieldsTarget) {
        this.redirectFieldsTarget.classList.remove("hidden")
      }
    }
  }

  updatePatternHelpText(ruleType) {
    if (!this.hasHelpTextTarget || !this.hasConditionsFieldTarget) return

    const helpTexts = {
      path_pattern: {
        text: "Regex pattern to match URL paths (e.g.,\\.env$|wp-admin|phpmyadmin)",
        placeholder: "Example: \\.env$|\\.git|config\\.php|wp-admin"
      }
    }

    const config = helpTexts[ruleType]
    if (config) {
      this.helpTextTarget.textContent = config.text
      this.conditionsFieldTarget.placeholder = config.placeholder
    }
  }

  hideOptionalFields() {
    if (this.hasPatternFieldsTarget) this.patternFieldsTarget.classList.add("hidden")
    if (this.hasRateLimitFieldsTarget) this.rateLimitFieldsTarget.classList.add("hidden")
    if (this.hasRedirectFieldsTarget) this.redirectFieldsTarget.classList.add("hidden")
  }

  clearExpiresAtField() {
    // Clear the expires_at field - much simpler with text field
    if (this.hasExpiresAtFieldTarget) {
      this.expiresAtFieldTarget.value = ''
    }
  }

  resetForm() {
    if (this.formTarget) {
      // Find the actual form element within the form target div
      const formElement = this.formTarget.querySelector('form')
      if (formElement) {
        formElement.reset()

        // Explicitly clear the expires_at field since browser reset might not clear datetime-local fields properly
        this.clearExpiresAtField()

        // Reset rule type to default
        if (this.hasRuleTypeSelectTarget) {
          this.ruleTypeSelectTarget.value = "network"
          this.updateRuleTypeFields()
        }
      }
    }
  }

  // Private methods

  setupEventListeners() {
    // Event listeners are handled via data-action attributes in the HTML
    // No manual event listeners needed
  }

  initializeFieldVisibility() {
    // Initialize field visibility on page load
    if (this.hasRuleTypeSelectTarget) {
      this.updateRuleTypeFields()
    }
  }
}