class Admin::ImagesController < ApplicationController
  before_action :authorize_admin
  before_action :set_image, only: [ :show, :edit, :update, :destroy, :approve, :reject, :add_tags, :remove_tag ]
  before_action :set_tag, only: [ :index, :new, :create ], if: -> { params[:tag_id].present? }

  def index
    if params[:tag_id].present?
      # When accessed via /admin/tags/:tag_id/images
      @q = @tag.images.includes(:user, :tags).ransack(params[:q])
      @images = @q.result(distinct: true).with_attached_file.order(created_at: :desc).page(params[:page]).per(20)

      render inertia: "admin/tags/images/Index", props: {
        tag: @tag.as_json(only: [ :id, :name, :catalog ], methods: [ :images_count ]),
        images: @images.as_json(include: [ :user, :tags ], methods: [ :file_url, :thumbnail_url, :medium_url ]),
        filters: params[:q] || {},
        pagination: {
          current_page: @images.current_page,
          total_pages: @images.total_pages,
          total_count: @images.total_count
        }
      }
    else
      # Regular /admin/images index
      @q = Image.includes(:user, :tags).ransack(params[:q])
      @images = @q.result(distinct: true).with_attached_file.order(created_at: :desc).page(params[:page]).per(20)

      render inertia: "admin/images/Index", props: {
        images: @images.as_json(include: [ :user, :tags ], methods: [ :file_url, :thumbnail_url, :medium_url ]),
        filters: params[:q] || {},
        pagination: {
          current_page: @images.current_page,
          total_pages: @images.total_pages,
          total_count: @images.total_count
        },
        pending_count: Image.pending.count,
        approved_count: Image.approved.count,
        rejected_count: Image.rejected.count
      }
    end
  end

  def show
    render inertia: "admin/images/Show", props: {
      image: @image.as_json(include: [ :user, :tags ], methods: [ :file_url, :thumbnail_url, :medium_url ])
    }
  end

  def edit
    render inertia: "admin/images/Edit", props: {
      image: @image.as_json(include: [ :user, :tags ], methods: [ :file_url, :thumbnail_url, :medium_url ])
    }
  end

  def new
    if params[:tag_id].present?
      render inertia: "admin/tags/images/New", props: {
        tag: @tag.as_json(only: [ :id, :name, :catalog ], methods: [ :images_count ])
      }
    else
      render inertia: "admin/images/New", props: {}
    end
  end

  def create
    @image = Current.user.images.new(image_create_params)

    if @image.save
      # 处理标签 - 从表单数据中获取tag_ids
      if params[:image] && params[:image][:tag_ids].present?
        @image.set_tags_by_ids(params[:image][:tag_ids])
      end

      # Add the tag if we're creating from a tag context
      if params[:tag_id].present? && @tag
        @image.tags << @tag unless @image.tags.include?(@tag)
      end

      if params[:tag_id].present?
        redirect_to admin_tag_images_path(@tag), notice: "Image was successfully created and tagged."
      else
        redirect_to admin_images_path, notice: "Image was successfully created."
      end
    else
      if params[:tag_id].present?
        render inertia: "admin/tags/images/New", props: {
          tag: @tag.as_json(only: [ :id, :name, :catalog ], methods: [ :images_count ]),
          errors: @image.errors
        }, status: :unprocessable_entity
      else
        render inertia: "admin/images/New", props: {
          errors: @image.errors
        }, status: :unprocessable_entity
      end
    end
  end

  def update
    if @image.update(image_params)
      # 处理标签 - 从表单数据中获取tag_ids
      if params[:image] && params[:image][:tag_ids].present?
        @image.set_tags_by_ids(params[:image][:tag_ids])
      end

      redirect_to admin_image_path(@image), notice: "Image was successfully updated."
    else
      render inertia: "admin/images/Edit", props: {
        image: @image.as_json(include: [ :user, :tags ], methods: [ :file_url, :thumbnail_url, :medium_url, :errors ]),
        errors: @image.errors
      }, status: :unprocessable_entity
    end
  end

  def destroy
    @image.destroy!
    redirect_to admin_images_path, notice: "Image was successfully deleted."
  end

  def approve
    Image.transaction do
      @image.approved!
      @image.set_tags_by_ids(params[:tag_ids]) if params[:tag_ids].present?
    end

    redirect_to admin_image_path(@image), notice: "Image was successfully approved."
  end

  def reject
    @image.rejected!
    redirect_to admin_image_path(@image), notice: "Image was rejected."
  end

  def add_tags
    if params[:tags].present?
      @image.add_tags(params[:tags].split(","))
      redirect_to admin_image_path(@image), notice: "Tags were successfully added."
    else
      redirect_to admin_image_path(@image), alert: "No tags were provided."
    end
  end

  def remove_tag
    tag = Tag.find(params[:tag_id])
    @image.tags.delete(tag)
    redirect_to admin_image_path(@image), notice: "Tag was successfully removed."
  end

  private

  def set_image
    @image = Image.find(params[:id])
  end

  def set_tag
    @tag = Tag.find(params[:tag_id])
  end

  def image_params
    params.require(:image).permit(:title, :status, tag_ids: [])
  end

  def image_create_params
    params.require(:image).permit(:title, :file, :status, tag_ids: [])
  end

  def authorize_admin
    unless Current.user&.admin?
      redirect_to root_path, alert: "You are not authorized to access this area."
    end
  end
end