class SectionsReportsController < ApplicationController
  before_action :set_sections_report
  before_action :set_ancestors

  include ExcelSanitizable

  def show
    @respondents = @sections_report.respondents.includes(:tags).order(:first_name)

    master_sections = MasterSection.where(id: @sections_report.section_ids)
                                   .order(:position)
                                   .pluck(:id)

    @sections = @sections_report.respondents.joins(:transcript_sections)
                                .where(transcript_sections: { master_section_id: master_sections })
                                .select("transcript_sections.name, transcript_sections.master_section_id")
                                .group("transcript_sections.name, transcript_sections.master_section_id")
                                .order(Arel.sql("array_position(ARRAY[#{master_sections.join(',')}], transcript_sections.master_section_id)"))
                                .pluck("transcript_sections.name", "transcript_sections.master_section_id")
  end

  def generate_section_report_summary
    SectionReportSummaryJob.perform_later(
      metadata: { section_report_id: params[:id].to_i,
                  respondent_category_id: @respondent_category.id,
                  llm_model: @sections_report.llm_model,
                  all_data: false }, user_id: current_user.id
    )
    redirect_to analysis_reports_project_respondent_category_path(@project, @respondent_category),
                notice: "Section Report Summarization Queued"
  end

  def download_report
    @respondents = @sections_report.respondents.includes(:transcript_sections).order(:first_name)

    section_data = MasterSection.where(id: @sections_report.section_ids)
                                .order(:position)
                                .pluck(:id, :name)

    @highlight_themes = @sections_report.respondent_category.highlight_themes
    @respondents_with_highlights = @sections_report.respondents.distinct
                                                   .joins(:transcript_highlights)
                                                   .where(transcript_highlights: {
                                                            highlight_theme_id: @highlight_themes.select(:id)
                                                          })

    sections_with_highlights = section_data.collect(&:first) & TranscriptHighlight.where(highlight_theme: @highlight_themes).pluck(:master_section_id)
    @highlight_table_data = MasterSection.where(id: sections_with_highlights).order(:position).map do |section|
      {
        section:,
        themes_data: @highlight_themes.order(:position).map do |theme|
          {
            theme:,
            highlights_by_respondent: @respondents_with_highlights.map do |respondent|
              highlights = respondent.transcript_highlights.includes(:highlight_theme, :master_section)
                                     .where(
                                       highlight_theme: theme,
                                       master_section: section
                                     )
              {
                respondent_id: respondent.id,
                highlights:
              }
            end
          }
        end
      }
    end

    rows = []
    summary_rows = []
    aggregate_rows = []
    highlight_rows = []

    header_row = ["Section"]
    highlight_header_row = ["Section | Theme"]

    require "csv"
    @respondents.each do |respondent|
      header_row << respondent.name
    end

    @respondents_with_highlights.each do |respondent|
      highlight_header_row << respondent.name
    end

    rows << header_row
    summary_rows << header_row
    highlight_rows << highlight_header_row
    aggregate_rows << ["Section", "Aggregate Summary"]

    section_data.each do |master_section_id, section_name|
      section_row = []
      section_summary_row = []
      aggr_row = []
      section_row << sanitize_and_truncate_for_excel(section_name)
      section_summary_row << sanitize_and_truncate_for_excel(section_name)
      aggr_row << sanitize_and_truncate_for_excel(section_name)
      @respondents.each do |r|
        section = r.transcript_sections.where(master_section_id:).first
        section_row << if section
                         sanitize_and_truncate_for_excel(section.content)
                       else
                         " NOT FOUND "
                       end
        section_summary_row << if section
                                 sanitize_and_truncate_for_excel(section.ai_summary)
                               else
                                 " NOT FOUND "
                               end
      end
      rows << section_row
      summary_rows << section_summary_row

      aggr_summary = SectionSummary.where(master_section_id:, all_data: false, groupable: @sections_report).last
      aggr_row << if aggr_summary
                    sanitize_and_truncate_for_excel(aggr_summary.summary)
                  else
                    " NOT FOUND "
                  end

      aggregate_rows << aggr_row
    end

    @highlight_table_data.each do |highlight_sections|
      highlight_sections[:themes_data].each do |theme_data|
        row = []
        row << "#{highlight_sections[:section].name} | #{theme_data[:theme].theme}"
        theme_data[:highlights_by_respondent].each do |respondent_highlights|
          row << "NOT FOUND" if respondent_highlights[:highlights].blank?

          respondent_highlights[:highlights].each do |highlight|
            row << sanitize_and_truncate_for_excel(highlight.verbose_to_text)
          end
        end
        highlight_rows << row
      end
    end

    require "axlsx"
    p = Axlsx::Package.new
    p.workbook.add_worksheet(name: "Sections") do |sheet|
      wrap_text_style = sheet.styles.add_style(alignment: { wrap_text: true, vertical: :top })
      rows.each do |row|
        sheet.add_row row, style: wrap_text_style
      end

      # Set column widths
      sheet.column_widths 30, 100
    end

    p.workbook.add_worksheet(name: "Section Summaries") do |sheet|
      wrap_text_style = sheet.styles.add_style(alignment: { wrap_text: true, vertical: :top })
      summary_rows.each do |row|
        sheet.add_row row, style: wrap_text_style
      end

      # Set column widths
      sheet.column_widths 30, 100
    end

    p.workbook.add_worksheet(name: "Aggregate Summaries") do |sheet|
      wrap_text_style = sheet.styles.add_style(alignment: { wrap_text: true, vertical: :top })
      aggregate_rows.each do |row|
        sheet.add_row row, style: wrap_text_style
      end

      # Set column widths
      sheet.column_widths 30, 100
    end

    p.workbook.add_worksheet(name: "Highlights") do |sheet|
      wrap_text_style = sheet.styles.add_style(alignment: { wrap_text: true, vertical: :top })
      highlight_rows.each do |row|
        sheet.add_row row, style: wrap_text_style
      end

      # Set column widths
      sheet.column_widths 30, 100
    end

    excel_data = p.to_stream.read

    send_data excel_data, filename: "#{@sections_report.name.parameterize}_sections_report.xlsx",
                          type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  end

  def delete_report
    report = SectionsReport.find(params[:id])
    report&.destroy
    flash[:notice] = "Section Report Successfully Deleted"
    redirect_to analysis_reports_project_respondent_category_path(@project, @respondent_category)
  end

  private

  def set_ancestors
    @project = Project.find(params[:project_id])
    @respondent_category = RespondentCategory.find(params[:respondent_category_id])
  end

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