module Agent
  class ServiceRequestsController < ApplicationController
    before_action :authenticate_user!
    before_action -> { authenticate_role!(:agent) }

    def index
      @service_requests = ServiceRequest.order(created_at: :desc)
      @service_request = ServiceRequest.where(id: params[:service_request_id])&.first

      if turbo_frame_request?
        @service_requests = @service_requests.search(params[:term]) if params[:term].present?
        render partial: "agent/service_requests/search_results",
               locals: { service_requests: @service_requests, id: :agent_all_service_requests }
      else
        render :index
      end
    end

    def show
      service_request
    end

    def new
      @service_request_id = params[:service_request_id]
      @service_request = ServiceRequest.new(client_id: params[:client_id])
    end

    def create
      @service_request_id = params[:service_request_id]
      @service_request = ServiceRequest.create(service_request_params)

      if @service_request.persisted?
        @service_request.prepend_to_todays_requests_list
        @service_request.prepend_to_all_service_requests_list

        render template: "agent/service_requests/show", locals: { service_request: }
      else
        render :new, status: :unprocessable_entity
      end
    end

    def update
      service_request.update(service_request_params)

      service_request.broadcast_update

      if service_request.saved_change_to_status?
        service_request.broadcast_replace_to service_request,
                                             target: helpers.dom_id(service_request, :agent_sidebar),
                                             partial: "agent/service_requests/sidebar",
                                             locals: {
                                               current_user: service_request.agent,
                                               service_request:
                                             }
      end

      flash.now[:info] = t(".saved")
      render turbo_stream: update_flash_messages_turbo_stream
    end

    def call
      @nav_disabled = true

      return redirect_to agent_home_path unless service_request.start_video_chat?(current_user)

      service_request.update(agent: current_user, status: :waiting_for_answer) if service_request.waiting?

      service_request.broadcast_append_to service_request.client,
                                          target: "flash_messages",
                                          partial: "agent/service_requests/incoming_call",
                                          locals: { service_request: }

      service_request.broadcast_update_to_reserved_requests
    end

    def mute_video
      service_request.toggle!(:is_agent_video_muted)
    end

    def mute_audio
      service_request.toggle!(:is_agent_audio_muted)
      service_request.broadcast_replace_to service_request.client,
                                           target: helpers.dom_id(service_request, :agent_audio_mute_indicator),
                                           partial: "client/service_requests/audio_mute_indicator",
                                           locals: { service_request: }
    end

    def switch
      previous_request = ServiceRequest.find(params[:service_request_id])
      call_duration = previous_request.call_started_at ? Time.current - previous_request.call_started_at : 0
      previous_request.logs.create(type: :switch_from, call_duration:)
      previous_request.update(call_duration:, status: :finished)

      if service_request.waiting? || service_request.waiting_for_answer? || service_request.finished?
        service_request.update(agent: current_user, status: :in_progress,
                               call_started_at: Time.current)
      end
      service_request.logs.create(type: :switch_to)

      service_request.broadcast_replace_to previous_request.client,
                                           target: helpers.dom_id(previous_request, :chat),
                                           partial: "client/service_requests/chat",
                                           locals: {
                                             current_user: previous_request.client,
                                             service_request:
                                           }

      render turbo_stream: [
        turbo_stream.replace(
          helpers.dom_id(previous_request, :agent_call_sidebar),
          partial: "agent/service_requests/call_sidebar", locals: { current_user:, service_request: }
        )
      ]
    end

    def other_requests
      @link_to_show = params[:link_to_show]
      @other_requests = service_request
                        .client.client_service_requests
                        .today
                        .where(status: %i[waiting waiting_for_answer in_progress finished])
                        .order(created_at: :desc)
    end

    def finish
      call_duration = service_request.call_started_at ? Time.current - service_request.call_started_at : 0
      target = service_request.waiting_for_answer? ? :call : :chat

      if service_request.waiting_for_answer? || service_request.in_progress?
        service_request.update(status: :finished, call_ended_at: Time.current, call_duration:)
        service_request.logs.create(type: :call_ended, call_duration:)
      end

      service_request.broadcast_append_to service_request.client,
                                          target: helpers.dom_id(service_request, target),
                                          partial: "agent/service_requests/cancelled_call",
                                          locals: {
                                            current_user:,
                                            service_request:
                                          }

      service_request.broadcast_update_to_reserved_requests

      redirect_to agent_home_path, status: :see_other
    end

    def cancel
      service_request = current_user.agent_service_requests.find(params[:id])
      service_request.update(status: :cancelled) if service_request.in_progress?

      service_request.broadcast_update_to %i[agent todays_service_requests],
                                          target: helpers.dom_id(service_request),
                                          partial: "agent/service_requests/service_request",
                                          locals: {
                                            service_request:
                                          }

      service_request.broadcast_update_to %i[agent all_service_requests],
                                          target: helpers.dom_id(service_request),
                                          partial: "agent/service_requests/service_request",
                                          locals: {
                                            service_request:
                                          }

      redirect_to agent_home_path, status: :see_other
    end

    private

    def service_request
      @service_request ||= ServiceRequest.find(params[:id])
    end

    def service_request_params
      params.require(:service_request)
            .permit(:status, :internal_comment, :category_id, :title, :description, :client_id)
    end
  end
end
