using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using survey_beta.DataBaseContext;
using survey_beta.DTOs.Default;
using survey_beta.DTOs.Update;
using survey_beta.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

public class AnalyticsServices
{
    private readonly AppDbContext _context;
    private readonly IMapper _mapper;

    public AnalyticsServices(AppDbContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    public void UpdateAnalytics(string surveyId)
    {
        var responses = _context.Responses
            .Where(r => r.SurveyId == surveyId)
            .Include(r => r.Answers)
                .ThenInclude(a => a.Choice)
            .ToList();

        var analyticsData = CalculateAnalytics(responses);

        SaveAnalytics(surveyId, analyticsData);
    }

    private SurveyStats CalculateAnalytics(List<Response> responses)
    {
        var answerFrequency = new Dictionary<string, int>();
        var questionFrequency = new Dictionary<string, int>();

        foreach (var response in responses)
        {
            foreach (var answer in response.Answers)
            {
                var choiceText = answer.Choice?.Letter;
                if (!string.IsNullOrEmpty(choiceText))
                {
                    if (answerFrequency.ContainsKey(choiceText))
                        answerFrequency[choiceText]++;
                    else
                        answerFrequency[choiceText] = 1;
                }

                var questionText = answer.Question?.Text;
                if (!string.IsNullOrEmpty(questionText))
                {
                    if (questionFrequency.ContainsKey(questionText))
                        questionFrequency[questionText]++;
                    else
                        questionFrequency[questionText] = 1;
                }
            }
        }

        return new SurveyStats
        {
            SurveyId = responses.FirstOrDefault()?.SurveyId,
            TotalResponses = responses.Count,
            AnswerFrequency = answerFrequency,
            QuestionFrequency = questionFrequency
        };
    }

    private void SaveAnalytics(string surveyId, SurveyStats analyticsData)
    {
        var analytics = _mapper.Map<SurveyAnalytics>(analyticsData);
        analytics.SurveyId = surveyId;
        analytics.CreatedAt = DateTime.UtcNow;

        _context.Add(analytics);
        _context.SaveChanges();
    }

    public SurveyStats GetAggregatedSurveyResponses(string surveyId)
    {
        var responses = _context.Responses
            .Where(r => r.SurveyId == surveyId)
            .Include(r => r.Answers)
                .ThenInclude(a => a.Choice)
            .ToList();

        return CalculateAnalytics(responses);
    }

    public async Task<IActionResult> ExportResponsesToCsv(string surveyId)
    {
        var responses = await _context.Responses
            .Where(r => r.SurveyId == surveyId)
            .Include(r => r.Answers)
            .ThenInclude(a => a.Question)
            .Include(r => r.Answers)
            .ThenInclude(a => a.Choice)
            .ToListAsync();

        var csvLines = new List<string>
    {
        "ResponseId,Question,ChoiceText"
    };

        foreach (var response in responses)
        {
            foreach (var answer in response.Answers)
            {
                var questionText = answer.Question.Content;
                csvLines.Add($"{response.Id},{questionText}");
            }
        }

        var fileName = "Survey_Responses.csv";
        var fileBytes = Encoding.UTF8.GetBytes(string.Join(Environment.NewLine, csvLines));

        return new FileContentResult(fileBytes, "text/csv")
        {
            FileDownloadName = fileName
        };
    }
}
