package fr.eni.enchere.controllers;

import fr.eni.enchere.bll.*;
import fr.eni.enchere.bo.Article;
import fr.eni.enchere.bo.SearchArticleCritere;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;


@Controller
public class AccueilController {

    @Autowired
    private static final Logger logger = LoggerFactory.getLogger(AccueilController.class);
    private ArticleService articleService;
    private CategorieService categorieService;
    private UserService userService;
    private FileService fileService;

    public AccueilController(ArticleService articleService, CategorieService categorieService, UserService userService, FileService fileService) {
        super();
        this.categorieService = categorieService;
        this.articleService = articleService;
        this.userService = userService;
        this.fileService = fileService;
    }

    @GetMapping({"/", "/enchere"})
    public String viewAccueil(HttpServletRequest request, @AuthenticationPrincipal UserDetails userDetails,
                              @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "6") int size, Model model,
                              HttpSession session) {
        logger.error("test du logger");

        // Récupérer les critères de recherche de la session
        String searchTitle = (String) session.getAttribute("searchTitle");
        Integer searchCategory = (Integer) session.getAttribute("searchCategory");
        String[] venteOptions = (String[]) session.getAttribute("venteOptions");
        String[] achatOptions = (String[]) session.getAttribute("achatOptions");
        String typeTransaction = (String) session.getAttribute("typeTransaction");
        model.addAttribute("SessionTypeTransaction", typeTransaction);
        model.addAttribute("sessionVenteOptions", venteOptions);
        model.addAttribute("sessionAchatOptions", achatOptions);

        // Utiliser les valeurs des critères de recherche dans votre logique métier
        SearchArticleCritere critere = new SearchArticleCritere();
        critere.setNoCategorie(searchCategory);
        critere.setTitle(searchTitle);
        if (userDetails != null) {
            critere.setNoVendeur(userService.utilisateurByName(userDetails.getUsername()).getId());
        }
        critere.setVenteOptions(venteOptions);
        critere.setAchatOptions(achatOptions);

        if (page > 0) {
            page -= 1;
        }

        // Pagination
        Page<Article> articlePage = articleService.searchArticlePageable(critere, PageRequest.of(page, size));
        model.addAttribute("articles", articlePage.getContent());

        int currentPage = page + 1;
        model.addAttribute("currentPage", currentPage);
        model.addAttribute("critere", critere);
        model.addAttribute("totalPages", articlePage.getTotalPages());
        model.addAttribute("categories", categorieService.findAllCategories());
        model.addAttribute("requestURI", request.getRequestURI());

        return "accueil";
    }

    @PostMapping("/enchere")
    public String handleSearch(HttpServletRequest request, @AuthenticationPrincipal UserDetails userDetails,
                               @RequestParam(required = false) String searchTitle, @RequestParam(required = false) Integer searchCategory,
                               @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "6") int size, Model model,
                               @RequestParam(value = "venteOption", required = false) String[] venteOptions,
                               @RequestParam(value = "achatOption", required = false) String[] achatOptions,
                               @RequestParam(required = false) String typeTransaction, HttpSession session) {

        // Mettre à jour les critères de recherche dans la session
        session.setAttribute("searchCategory", searchCategory);
        session.setAttribute("searchTitle", searchTitle);
        session.setAttribute("venteOptions", venteOptions);
        session.setAttribute("achatOptions", achatOptions);
        session.setAttribute("typeTransaction", typeTransaction);

        // Rediriger vers la page d'accueil
        return "redirect:/enchere";
    }


}
