# frozen_string_literal: true

class ElementsController < ApplicationController
  before_action :set_page, only: %i[index new create]
  before_action :set_element, only: %i[show edit update destroy]

  # GET /elements
  def index
    @elements = Element.all
  end

  # GET /elements/1
  def show; end

  # GET /elements/new
  def new
    @element = Element.new(page_id: params[:page_id])
    @element.page = @page
  end

  # GET /elements/1/edit
  def edit; end

  # POST /elements
  def create
    # checklist_id = element_params.delete(:checklist_id)
    # checklist = Checklist.find(checklist_id)
    @element = Element.new(element_params)
    @element.page = @page
    # @element.title = checklist.name if @element.title.blank?

    if @element.save
      # checklist.checks.each do |check|
      #   @element.success_criteria.create!(
      #     check:,
      #     title: check.t_name,
      #     level: check.conformity_level,
      #     quick_criterion: check.t_quick_criterion)
      # end
      respond_to do |format|
        format.html { redirect_to @element.report, notice: "Element was successfully created." }
        format.turbo_stream
      end
    else
      render :new, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /elements/1
  def update
    if @element.update(element_params)
      redirect_to @element, notice: "Element was successfully updated.", status: :see_other
    else
      render :edit, status: :unprocessable_entity
    end
  end

  # DELETE /elements/1
  def destroy
    @element.destroy!
    redirect_to elements_url, notice: "Element was successfully destroyed.", status: :see_other
  end

  private

  # Use callbacks to share common setup or constraints between actions.
  def set_element
    @element = Element.find(params[:id])
  end

  def set_page
    @page = Page.find(params[:page_id])
  end

  # Only allow a list of trusted parameters through.
  def element_params
    params.require(:element).permit(:page_id, :title, :description)
  end
end
