package com.example.demo.service.Impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.example.demo.dto.RecipeDto;
import com.example.demo.dto.UserDto;
import com.example.demo.dto.StepDto;
import com.example.demo.dto.TagDto;
import com.example.demo.dto.ImageDto;
import com.example.demo.dto.RecipeIngredientDto;
import com.example.demo.entity.Image;
import com.example.demo.entity.Ingredient;
import com.example.demo.entity.Recipe;
import com.example.demo.entity.RecipeIngredient;
import com.example.demo.entity.Step;
import com.example.demo.entity.Tag;
import com.example.demo.entity.User;
import com.example.demo.exception.NotFoundException;
import com.example.demo.repository.ImageRepo;
import com.example.demo.repository.IngredientRepo;
import com.example.demo.repository.RecipeIngredientRepo;
import com.example.demo.repository.RecipeRepo;
import com.example.demo.repository.StepRepo;
import com.example.demo.repository.TagRepo;
import com.example.demo.repository.UserRepo;
import com.example.demo.repository.FavoriteRepo;
import com.example.demo.service.RecipeService;

import jakarta.transaction.Transactional;

@Service
public class RecipeServiceImpl implements RecipeService {

	private RecipeRepo recipeRepository;
	private IngredientRepo ingredientRepository;
	private RecipeIngredientRepo recipeIngredientRepository;
	private UserRepo userRepository;
	private StepRepo stepRepository;
	private ImageRepo imageRepository;
	private TagRepo tagRepository;
	private FavoriteRepo favoriteRepo;

	public RecipeServiceImpl(
			RecipeRepo recipeRepository,
			IngredientRepo ingredientRepository,
			RecipeIngredientRepo recipeIngredientRepository,
			UserRepo userRepository,
			StepRepo stepRepository,
			ImageRepo imageRepository,
			TagRepo tagRepository,
			FavoriteRepo favoriteRepo
	) {
		this.recipeRepository = recipeRepository;
		this.ingredientRepository = ingredientRepository;
		this.recipeIngredientRepository = recipeIngredientRepository;
		this.userRepository = userRepository;
		this.stepRepository = stepRepository;
		this.imageRepository = imageRepository;
		this.tagRepository = tagRepository;
		this.favoriteRepo = favoriteRepo;
	}

	@Override
	public void updateRecipeImage(Integer id, MultipartFile image) {
	    if (image == null || image.isEmpty()) {
	        return;
	    }
	}

	@Override
	public RecipeDto convertToDto(Recipe recipe) {

		List<RecipeIngredientDto> ingredientDtos = recipe.getRecipeIngredients().stream()
				.map(ri -> new RecipeIngredientDto(ri.getIngredient().getName(), ri.getQuantity(), ri.getUnit(),
						ri.getNotes()))
				.toList();

		List<StepDto> stepDtos = recipe.getSteps().stream()
				.map(ri -> new StepDto(ri.getStepNumber(), ri.getInstruction()))
				.toList();

		List<ImageDto> imageDtos = recipe.getImages().stream()
				.map(ri -> new ImageDto(ri.getImageUrl()))
				.toList();

		List<TagDto> tagDtos = recipe.getTags().stream()
				.map(ri -> new TagDto(ri.getName()))
				.toList();

		UserDto userDto = new UserDto(
				recipe.getUser().getId(),
				recipe.getUser().getUsername(),
				recipe.getUser().getEmail(),
				recipe.getUser().getDisplayName(),
				recipe.getUser().getBio()
		);

		RecipeDto dto = new RecipeDto(
				recipe.getTitle(),
				recipe.getDescription(),
				recipe.getPrepTimeMinutes(),
				recipe.getCookTimeMinutes(),
				recipe.getServings(),
				userDto,
				recipe.getStatus(),
				ingredientDtos,
				stepDtos,
				imageDtos,
				tagDtos,
				recipe.getCost()
		);

		dto.setId(recipe.getId());
		return dto;
	}

	private User getCurrentUser(String currentUsername) {
		return userRepository.findByUsername(currentUsername)
				.orElseThrow(() -> new NotFoundException("User", "username", currentUsername));
	}

	private boolean isAdmin(User user) {
		return "ROLE_ADMIN".equals(user.getRole());
	}

	private void ensureUserNotBanned(User user) {
		if (user.isBanned()) {
			throw new AccessDeniedException("Banned users cannot perform this action.");
		}
	}

	private void enforceUploadLimit(User user) {
		if (isAdmin(user)) return;

		LocalDateTime cutoff = LocalDateTime.now().minusHours(24);
		long uploadsInLast24Hours = recipeRepository.countByUserIdAndCreatedAtAfter(user.getId(), cutoff);

		if (uploadsInLast24Hours >= 10) {
			throw new AccessDeniedException("Upload limit reached. Maximum is 10 recipes per 24 hours.");
		}
	}

	private void enforceOwnerOrAdmin(User currentUser, Recipe recipe) {
		if (isAdmin(currentUser)) return;

		if (!recipe.getUser().getId().equals(currentUser.getId())) {
			throw new AccessDeniedException("You do not have permission to modify this recipe.");
		}
	}

	@Override
	@Transactional
	public void deleteRecipe(Integer id, String currentUsername) {

		User currentUser = getCurrentUser(currentUsername);
		ensureUserNotBanned(currentUser);

		Recipe recipe = recipeRepository.findById(id)
				.orElseThrow(() -> new NotFoundException("Recipe", "id", id));

		enforceOwnerOrAdmin(currentUser, recipe);

		favoriteRepo.deleteById_RecipeId(id);

		recipeRepository.delete(recipe);
	}

	@Override
	@Transactional
	public RecipeDto saveRecipe(RecipeDto dto, String currentUsername) {

		User currentUser = getCurrentUser(currentUsername);
		ensureUserNotBanned(currentUser);
		enforceUploadLimit(currentUser);

		Recipe recipe = new Recipe(
				dto.getTitle(),
				dto.getDescription(),
				dto.getPrepTimeMinutes(),
				dto.getCookTimeMinutes(),
				dto.getServings(),
				currentUser,
				dto.getStatus(),
				dto.getCost()
		);

		if (dto.getIngredients() != null) {
			java.util.Set<String> seenIngredientNames = new java.util.HashSet<>();
			java.util.Set<Integer> seenIngredientIds = new java.util.HashSet<>();

			for (int i = 0; i < dto.getIngredients().size(); i++) {
				RecipeIngredientDto riDto = dto.getIngredients().get(i);

				String rawName = riDto.getIngredientName();
				String normalizedName = rawName == null ? "" : rawName.trim().toLowerCase();

				if (normalizedName.isBlank()) {
					continue;
				}

				if (!seenIngredientNames.add(normalizedName)) {
					throw new IllegalArgumentException("Duplicate ingredient entry: " + rawName.trim());
				}

				Ingredient ingredient = ingredientRepository.findByNameIgnoreCase(rawName.trim())
						.orElseGet(() -> new Ingredient(rawName.trim()));

				if (ingredient.getId() == null) {
					ingredientRepository.save(ingredient);
				}

				if (ingredient.getId() != null && !seenIngredientIds.add(ingredient.getId())) {
					throw new IllegalArgumentException("Duplicate ingredient entry: " + rawName.trim());
				}

				RecipeIngredient ri = new RecipeIngredient(
						recipe,
						ingredient,
						riDto.getQuantity(),
						riDto.getUnit(),
						riDto.getNotes()
				);

				ri.setOrderIndex(i);
				recipe.getRecipeIngredients().add(ri);
			}
		}

		if (dto.getSteps() != null) {
			for (StepDto stepDto : dto.getSteps()) {
				Step step = new Step(recipe, stepDto.getStepNumber(), stepDto.getInstruction());
				recipe.getSteps().add(step);
			}
		}

		if (dto.getImages() != null) {
			for (ImageDto imageDto : dto.getImages()) {
				Image image = new Image(recipe, imageDto.getImageUrl());
				recipe.getImages().add(image);
			}
		}

		if (dto.getTags() != null) {
			for (TagDto tDto : dto.getTags()) {
				Tag tag = tagRepository.findByName(tDto.getName()).orElseGet(() -> new Tag(tDto.getName()));

				if (tag.getId() == null) {
					tagRepository.save(tag);
				}
				recipe.getTags().add(tag);
			}
		}

		Recipe saved = recipeRepository.save(recipe);

		return getRecipeById(saved.getId());
	}


	@Override
	@Transactional
	public List<RecipeDto> getAllRecipes() {
		List<RecipeDto> list = new ArrayList<>();
		for (Recipe recipe : recipeRepository.findAll()) {
			list.add(convertToDto(recipe));
		}
		return list;
	}

	@Override
	@Transactional
	public RecipeDto getRecipeById(Integer Id) {
		return convertToDto(
				recipeRepository.findById(Id)
						.orElseThrow(() -> new NotFoundException("Recipe", "id", Id))
		);
	}

	@Override
	@Transactional
	public RecipeDto updateRecipe(RecipeDto recipeDto, Integer id, String currentUsername) {

		User currentUser = getCurrentUser(currentUsername);
		ensureUserNotBanned(currentUser);

		Recipe existingRecipe = recipeRepository.findById(id)
				.orElseThrow(() -> new NotFoundException("Recipe", "id", id));

		enforceOwnerOrAdmin(currentUser, existingRecipe);

		existingRecipe.setTitle(recipeDto.getTitle());
		existingRecipe.setDescription(recipeDto.getDescription());
		existingRecipe.setPrepTimeMinutes(recipeDto.getPrepTimeMinutes());
		existingRecipe.setCookTimeMinutes(recipeDto.getCookTimeMinutes());
		existingRecipe.setServings(recipeDto.getServings());
		existingRecipe.setStatus(recipeDto.getStatus());
		existingRecipe.setStatus(recipeDto.getStatus());
		existingRecipe.setCost(recipeDto.getCost());

		List<RecipeIngredientDto> updatedIngredients = recipeDto.getIngredients();
		List<RecipeIngredient> ingredientsToRemove = new ArrayList<>();

		List<StepDto> updatedSteps = recipeDto.getSteps();
		List<Step> stepsToRemove = new ArrayList<>();

		List<ImageDto> updatedImages = recipeDto.getImages();
		List<Image> imagesToRemove = new ArrayList<>();

		List<TagDto> updatedTags = recipeDto.getTags();
		List<Tag> tagsToRemove = new ArrayList<>();

		if (updatedIngredients != null) {
			
			for (int i = 0; i < updatedIngredients.size(); i++) {
			    RecipeIngredientDto riDto = updatedIngredients.get(i);

			    RecipeIngredient existingRI = existingRecipe.getRecipeIngredients().stream()
			            .filter(ri -> java.util.Objects.equals(ri.getIngredient().getName(), riDto.getIngredientName()))
			            .findFirst()
			            .orElse(null);

			    if (existingRI != null) {
			        existingRI.setQuantity(riDto.getQuantity());
			        existingRI.setUnit(riDto.getUnit());
			        existingRI.setNotes(riDto.getNotes());
			        existingRI.setOrderIndex(i);
			    } else {
			        Ingredient ingredient = ingredientRepository.findByNameIgnoreCase(riDto.getIngredientName())
			                .orElseGet(() -> new Ingredient(riDto.getIngredientName()));

			        if (ingredient.getId() == null) {
			            ingredientRepository.save(ingredient);
			        }

			        RecipeIngredient newRI = new RecipeIngredient(existingRecipe, ingredient, riDto.getQuantity(),
			                riDto.getUnit(), riDto.getNotes());
			        newRI.setOrderIndex(i);

			        existingRecipe.getRecipeIngredients().add(newRI);
			    }
			}

			existingRecipe.getRecipeIngredients().removeAll(ingredientsToRemove);

			for (RecipeIngredientDto riDto : updatedIngredients) {

				RecipeIngredient existingRI = existingRecipe.getRecipeIngredients().stream()
						.filter(ri -> java.util.Objects.equals(ri.getIngredient().getName(), riDto.getIngredientName()))
						.findFirst()
						.orElse(null);

				if (existingRI != null) {

					existingRI.setQuantity(riDto.getQuantity());
					existingRI.setUnit(riDto.getUnit());
					existingRI.setNotes(riDto.getNotes());
				}

				else {

					Ingredient ingredient = ingredientRepository.findByNameIgnoreCase(riDto.getIngredientName())
							.orElseGet(() -> new Ingredient(riDto.getIngredientName()));

					if (ingredient.getId() == null) {
						ingredientRepository.save(ingredient);
					}

					RecipeIngredient newRI = new RecipeIngredient(existingRecipe, ingredient, riDto.getQuantity(),
							riDto.getUnit(), riDto.getNotes());

					existingRecipe.getRecipeIngredients().add(newRI);
				}
			}
		}

		if (updatedSteps != null) {
			for (Step step : existingRecipe.getSteps()) {
				boolean existsInUpdatedList = updatedSteps.stream()
						.anyMatch(dto -> dto.getStepNumber().equals(step.getStepNumber()));

				if (!existsInUpdatedList)
					stepsToRemove.add(step);
			}
			existingRecipe.getSteps().removeAll(stepsToRemove);

			for (StepDto stepDto : updatedSteps) {

				Step existingStep = existingRecipe.getSteps().stream()
						.filter(s -> s.getStepNumber().equals(stepDto.getStepNumber())).findFirst().orElse(null);

				if (existingStep != null) {
					existingStep.setInstruction(stepDto.getInstruction());
				}

				else {
					Step newStep = new Step(existingRecipe, stepDto.getStepNumber(), stepDto.getInstruction());
					existingRecipe.getSteps().add(newStep);
				}
			}
		}

		if (updatedImages != null) {
			for (Image image : existingRecipe.getImages()) {
				boolean existsInUpdatedList = updatedImages.stream()
						.anyMatch(dto -> java.util.Objects.equals(dto.getImageUrl(), image.getImageUrl()));
				if (!existsInUpdatedList)
					imagesToRemove.add(image);
			}

			existingRecipe.getImages().removeAll(imagesToRemove);

			for (ImageDto imageDto : updatedImages) {
				Image existingImage = existingRecipe.getImages().stream()
						.filter(img -> java.util.Objects.equals(img.getImageUrl(), imageDto.getImageUrl()))
						.findFirst()
						.orElse(null);

				if (existingImage != null) {
					existingImage.setImageUrl(imageDto.getImageUrl());
				} else {
					Image newImage = new Image(existingRecipe, imageDto.getImageUrl());
					existingRecipe.getImages().add(newImage);
				}
			}
		}

		if (updatedTags != null) {
			for (Tag tag : existingRecipe.getTags()) {
				boolean existsInUpdatedList = updatedTags.stream()
						.anyMatch(dto -> java.util.Objects.equals(dto.getName(), tag.getName()));
				if (!existsInUpdatedList)
					tagsToRemove.add(tag);
			}

			existingRecipe.getTags().removeAll(tagsToRemove);

			for (TagDto tagDto : updatedTags) {
				Tag existingTag = existingRecipe.getTags().stream()
						.filter(tag -> java.util.Objects.equals(tag.getName(), tagDto.getName()))
						.findFirst()
						.orElse(null);

				if (existingTag != null) {
					existingTag.setName(tagDto.getName());
				} else {
					Tag newTag = tagRepository.findByName(tagDto.getName())
							.orElseGet(() -> tagRepository.save(new Tag(tagDto.getName())));

					existingRecipe.getTags().add(newTag);
				}
			}
		}		
		recipeRepository.save(existingRecipe);
		return convertToDto(existingRecipe);
	}


	@Override
	@Transactional
	public List<RecipeDto> getNewestRecipes(int limit) {
		return recipeRepository.findAll().stream()
				.filter(r -> r.getCreatedAt() != null)
				.sorted((a, b) -> b.getCreatedAt().compareTo(a.getCreatedAt()))
				.limit(limit)
				.map(this::convertToDto)
				.collect(Collectors.toList());
	}

	@Override
	@Transactional
	public List<RecipeDto> getRecipes(String name, List<String> tags, List<Integer> prices, List<Integer> cookTime, List<Integer> prepTime) {

		List<Recipe> recipes;

		if ((name != null) && (!name.isBlank())) {
			recipes = recipeRepository.findByTitleContainingIgnoreCase(name);
		}

		else {
			recipes = recipeRepository.findAll();
		}

		if ((tags != null) && (!tags.isEmpty()) && !recipes.isEmpty()) {
			recipes = recipes.stream()
					.filter(recipe -> recipe.getTags().stream().anyMatch(tag -> tags.contains(tag.getName())))
					.collect(Collectors.toList());
		}

		if (prices != null && !prices.isEmpty() && !recipes.isEmpty()) {
		    recipes = recipes.stream()
		            .filter(recipe -> {
		            	Integer cost = recipe.getCost();
		            	if (cost == null) {
		            		return false;
		            	}

		            	for (Integer price : prices) {
		            		if (price == 4 && cost >= 4) {
		            			return true;
		            		}
		            		if (price != 4 && cost.equals(price)) {
		            			return true;
		            		}
		            	}
		            	return false;
		            })
		            .collect(Collectors.toList());
		}

		if (cookTime != null && !cookTime.isEmpty() && !recipes.isEmpty()) {
		    recipes = recipes.stream()
		    		.filter(recipe -> {
		    		    int minutes = recipe.getCookTimeMinutes();
		    		    for (Integer ct : cookTime) {
		    		        if (ct == 15  && minutes <= 15)          return true;
		    		        if (ct == 30  && minutes > 15 && minutes <= 30)  return true;
		    		        if (ct == 60  && minutes > 30 && minutes <= 60)  return true;
		    		        if (ct == 120 && minutes > 60 && minutes <= 120) return true;
		    		        if (ct == 121 && minutes > 120)          return true;
		    		    }
		    		    return false;
		    		})
		            .collect(Collectors.toList());
		}

		if (prepTime != null && !prepTime.isEmpty() && !recipes.isEmpty()) {
		    recipes = recipes.stream()
		    		.filter(recipe -> {
		    		    int minutes = recipe.getPrepTimeMinutes();
		    		    for (Integer ct : prepTime) {
		    		        if (ct == 15  && minutes <= 15)          return true;
		    		        if (ct == 30  && minutes > 15 && minutes <= 30)  return true;
		    		        if (ct == 60  && minutes > 30 && minutes <= 60)  return true;
		    		        if (ct == 240 && minutes > 60 && minutes <= 240) return true;
		    		        if (ct == 241 && minutes > 240)          return true;
		    		    }
		    		    return false;
		    		})
		            .collect(Collectors.toList());
		}

		List<RecipeDto> recipeList = new ArrayList<>();

		for (Recipe recipe : recipes) {
			RecipeDto dto = convertToDto(recipe);
			recipeList.add(dto);
		}

		return recipeList;
	}

}