# frozen_string_literal: true

class UsersController < ApplicationController
  before_action :set_user, only: %i[show edit update destroy]
  before_action :admin_needed
  # GET /users
  def index
    User.per_page = 100
    @users = User.includes(:team).order('approved desc').paginate(page: params[:page])
    @user_rewards = Reward.ytd_rewards_by_user_id
    @user_gc_unassigned = GiftCard.unscoped.unassigned.group(:user_id).count
  end

  # GET /users/1
  def show
    @changes = PaperTrail::Version.where(whodunnit: @user.id)
                                  .order(created_at: :desc)
                                  .page(params[:changes_page])
    around_now = Time.zone.now - 7.days..Time.zone.now + 7.days
    @sessions = ResearchSession.includes(:user)
                               .where(start_datetime: around_now, user_id: @user.id)
                               .page(params[:sessions_page])
  end

  # GET /users/new
  def new
    @user = User.new
  end

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

  def changes
    @changes = PaperTrail::Version.order('id desc').page(params[:page])
  end

  def finance
    @start_date = params[:start_date].presence || Time.current.beginning_of_year
    @end_date = params[:end_date].presence || Time.current
    codes = Reward.distinct.pluck(:finance_code).compact
    @results = codes.map do |code|
      amt = Money.new(Reward.where(created_at: @start_date..@end_date, finance_code: code).sum(:amount_cents), 'USD')
      count = Reward.where(created_at: @start_date..@end_date, finance_code: code).size
      { code: code, amount: amt, count: count }
    end
  end

  # POST /users
  def create
    @user = User.new(user_create_params)

    if @user.save
      redirect_to @user, notice: I18n.t('user.successfully_created')
    else
      render :new
    end
  end

  # PATCH/PUT /users/1
  def update
    respond_to do |format|
      if @user.update(user_params)
        format.html { redirect_to(@user, notice: I18n.t('user.successfully_updated')) }
      else
        format.html { render :edit }
      end
      format.json { respond_with_bip(@user) }
    end
  end

  # DELETE /users/1
  def destroy
    @user.destroy
    redirect_to users_url, notice: 'User was successfully destroyed.'
  end

  def admin
    @new_people = Person.active.includes(:taggings).order('created_at DESC').where('signup_at > :startdate', startdate: 1.month.ago)

    @my_todo_sessions = ResearchSession.where(user_id: current_user.id).includes(:invitations, :people).order('created_at DESC').reject(&:complete?)
    @verified_count = Person.active.verified.size
    @unverified_count = Person.active.not_verified.size
    @deactivated_count = Person.deactivated.where('deactivated_at > ?', 1.month.ago).size
    @deactivated_people = Person.deactivated.where(active: false).order('deactivated_at DESC').limit(10)

    @last_logins = User.approved.order('last_sign_in_at DESC').all
    @one_month_reward = Reward.where('created_at > ?', 1.month.ago).sum(&:amount)
    @six_month_reward = Reward.where('created_at > ?', 6.months.ago).sum(&:amount)
    @twelve_month_reward = Reward.where('created_at > ?', 1.year.ago).sum(&:amount)

    @one_month_people = Person.active.where(id: Reward.select('distinct person_id').where('created_at > ?', 1.month.ago).pluck(:person_id).uniq).size
    @six_month_people = Person.active.where(id: Reward.select('distinct person_id').where('created_at > ?', 6.months.ago).pluck(:person_id).uniq).size
    @twelve_month_people = Person.active.where(id: Reward.select('distinct person_id').where('created_at > ?', 1.year.ago).pluck(:person_id).uniq).size

    @popular_tags   = Person.includes(:taggings).active.tag_counts.order('taggings_count DESC').limit(10)
    @new_tags       = Person.includes(:taggings).active.tag_counts.order('id desc').limit(10)

    @recent_participants = ResearchSession.includes(:invitations, :people).order('research_sessions.created_at DESC').where('start_datetime < ?', Time.current).limit(10).map(&:people).flatten.uniq.take(10)
    @recent_sessions = ResearchSession.includes(:invitations).order('created_at DESC').limit(10)

    @upcoming_participants = ResearchSession.includes(:invitations).where('research_sessions.start_datetime between NOW() and ?', 1.week.from_now).map(&:people).flatten.uniq
    @upcoming_sessions = ResearchSession.includes(:invitations).where('start_datetime between NOW() and ?', 1.week.from_now)
    @cart_people = CartsPerson.includes(:cart, :person).all.limit(20)
  end

  private

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

  # Only allow a trusted parameter "white list" through.
  def user_params
    params.require(:user).permit(:name,
                                 :approved,
                                 :phone_number,
                                 :email_address,
                                 :team_id)
  end

  def user_create_params
    params.require(:user).permit(:name,
                                 :approved,
                                 :phone_number,
                                 :email_address,
                                 :team_id,
                                 :password,
                                 :password_confirmation)
  end
end
