package incheon.ags.mrb.gallery.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import incheon.ags.ias.comCd.mapper.ComCdMapper;
import incheon.ags.ias.comCd.vo.ComCdVO;
import incheon.ags.ias.comCd.vo.ComGroupCdVO;
import incheon.ags.mrb.main.service.BoardObjectService;
import incheon.ags.mrb.main.service.RecipeService;
import incheon.ags.mrb.main.vo.BoardObjectVO;
import incheon.ags.mrb.main.dto.RecipeDetailDTO;
import incheon.com.cmm.context.RequestContext;
import incheon.com.security.annotation.RequirePermission;
import incheon.com.security.vo.LoginVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.Map;

@Slf4j
@RequiredArgsConstructor
@Controller
@RequestMapping("/ags/mrb/gallery")
public class GalleryController {

    private final RecipeService recipeService;
    private final BoardObjectService boardObjectService;
    private final ComCdMapper comCdMapper;
    /**
     * 나의 레시피 갤러리 페이지
     */
    @GetMapping("/mine.do")
    public String galleryMine(@RequestParam(value = "searchKeyword", required = false) String searchKeyword,
                              @RequestParam(value = "pageIndex", required = false, defaultValue = "1") int pageIndex,
                              @RequestParam(value = "recordCountPerPage", required = false, defaultValue = "6") int recordCountPerPage,
                              Model model) throws Exception {
        log.info("나의 레시피 갤러리 - searchKeyword: {}, pageIndex: {}", searchKeyword, pageIndex);

        LoginVO loginUser = RequestContext.getCurrentUser();
        if (loginUser == null) {
            throw new AuthenticationCredentialsNotFoundException("로그인이 필요합니다.");
        }

        model.addAttribute("currentTab", "mine");
        model.addAttribute("searchKeyword", searchKeyword != null ? searchKeyword : "");
        model.addAttribute("currentPage", pageIndex);
        model.addAttribute("pageSize", recordCountPerPage);

        // 레시피 통계 조회 (galleryMine, galleryShared, galleryApprovals)
        Map<String, Object> statistics = recipeService.getRecipeStatistics(loginUser.getUserId());
        model.addAttribute("mineCount", statistics.get("galleryMine"));
        model.addAttribute("myShareCount", statistics.get("galleryShared"));
        model.addAttribute("sharedCount", statistics.get("galleryApprovals"));
        return "ags/mrb/gallery/gallery";
    }

    /**
     * 공유받은 레시피 갤러리 페이지
     */
    @GetMapping("/shared.do")
    public String galleryShared(@RequestParam(value = "searchKeyword", required = false) String searchKeyword,
                                @RequestParam(value = "pageIndex", required = false, defaultValue = "1") int pageIndex,
                                @RequestParam(value = "recordCountPerPage", required = false, defaultValue = "6") int recordCountPerPage,
                                Model model) throws Exception {
        log.info("공유받은 레시피 갤러리 - searchKeyword: {}, pageIndex: {}", searchKeyword, pageIndex);

        LoginVO loginUser = RequestContext.getCurrentUser();
        if (loginUser == null) {
            throw new AuthenticationCredentialsNotFoundException("로그인이 필요합니다.");
        }

        model.addAttribute("currentTab", "shared");
        model.addAttribute("searchKeyword", searchKeyword != null ? searchKeyword : "");
        model.addAttribute("currentPage", pageIndex);
        model.addAttribute("pageSize", recordCountPerPage);

        Map<String, Object> statistics = recipeService.getRecipeStatistics(loginUser.getUserId());
        model.addAttribute("mineCount", statistics.get("galleryMine"));
        model.addAttribute("myShareCount", statistics.get("galleryShared"));
        model.addAttribute("sharedCount", statistics.get("galleryApprovals"));
        return "ags/mrb/gallery/gallery";
    }

    /**
     * 승인 요청 갤러리 페이지 (관리자 전용)
     */
    @GetMapping("/approvals.do")
    @RequirePermission(system = "AGS", permissions = "PERM_MENU_ACCESS")
    public String galleryApprovals(@RequestParam(value = "searchKeyword", required = false) String searchKeyword,
                                   @RequestParam(value = "pageIndex", required = false, defaultValue = "1") int pageIndex,
                                   @RequestParam(value = "recordCountPerPage", required = false, defaultValue = "6") int recordCountPerPage,
                                   Model model) throws Exception {
        log.info("승인 요청 갤러리 - searchKeyword: {}, pageIndex: {}", searchKeyword, pageIndex);

        LoginVO loginUser = RequestContext.getCurrentUser();
        if (loginUser == null) {
            throw new AuthenticationCredentialsNotFoundException("로그인이 필요합니다.");
        }

        model.addAttribute("currentTab", "approvals");
        model.addAttribute("searchKeyword", searchKeyword != null ? searchKeyword : "");
        model.addAttribute("currentPage", pageIndex);
        model.addAttribute("pageSize", recordCountPerPage);

        // 레시피 통계 조회 (galleryMine, galleryShared, galleryApprovals)
        Map<String, Object> statistics = recipeService.getRecipeStatistics(loginUser.getUserId());
        model.addAttribute("mineCount", statistics.get("galleryMine"));
        model.addAttribute("myShareCount", statistics.get("galleryShared"));
        model.addAttribute("sharedCount", statistics.get("galleryApprovals"));
        return "ags/mrb/gallery/gallery";
    }

    /**
     * 나의 지도 레시피 설정 페이지 (관리자 전용)
     */
    @GetMapping("/settings.do")
    @RequirePermission(system = "AGS", permissions = "PERM_MENU_ACCESS")
    public String gallerySettings(Model model) throws Exception {
        LoginVO loginUser = RequestContext.getCurrentUser();
        if (loginUser == null) {
            throw new AuthenticationCredentialsNotFoundException("로그인이 필요합니다.");
        }
        log.info("나의 지도 레시피 설정 페이지 - userId: {}", loginUser.getUserId());

        model.addAttribute("currentTab", "settings");

        // 1. 자동 삭제 여부 조회 (MRB_RECIPE_DEL_GBN)
        ComGroupCdVO delGbnGroup = comCdMapper.selectComGroupCdDetail("MRB_RECIPE_DEL_GBN");
        boolean autoDeleteEnabled = delGbnGroup != null && "Y".equals(delGbnGroup.getUseYn());

        // 2. 삭제 주기 조회 (MRB_RECIPE_DEL_CYC에서 USE_YN = 'Y'인 코드 찾기)
        List<ComCdVO> delCycList = comCdMapper.getComCdByGroupCd("MRB_RECIPE_DEL_CYC");
        String deletePeriod = "01"; // 기본값
        for (ComCdVO code : delCycList) {
            if ("Y".equals(code.getUseYn())) {
                deletePeriod = code.getCd();
                break;
            }
        }

        log.info("레시피 설정 조회 완료 - userId: {}, 자동삭제: {}, 삭제주기: {}",
                loginUser.getUserId(), autoDeleteEnabled, deletePeriod);

        model.addAttribute("deletePeriod", deletePeriod);
        model.addAttribute("autoDeleteEnabled", autoDeleteEnabled);

        return "ags/mrb/gallery/gallery";
    }

    /**
     * 레시피 상세보기 팝업
     */
    @GetMapping("/recipe-detail.do")
    public String recipeDetail(@RequestParam("recipeId") Integer recipeId, Model model) {
        LoginVO loginUser = RequestContext.getCurrentUser();
        if (loginUser == null) {
            throw new AuthenticationCredentialsNotFoundException("로그인이 필요합니다.");
        }
        log.info("레시피 상세보기 팝업 - recipeId: {}, userId: {}", recipeId, loginUser.getUserId());

        // 레시피 상세 조회
        RecipeDetailDTO recipeDetail = recipeService.getRecipeDetail(recipeId, loginUser);

        // 대시보드 객체 목록 조회
        List<BoardObjectVO> boardObjectList = null;
        try {
            boardObjectList = boardObjectService.selectBoardObjectListByRecipeId(recipeId);
        } catch (JsonProcessingException e) {
            log.error("레시피 대쉬보드 파싱 오류 - recipeId={}", recipeId, e);
            throw new IllegalStateException("레시피 대쉬보드 데이터가 손상되었습니다.");
        }

        // 레시피 기본 정보
        model.addAttribute("recipe", recipeDetail);

        // 레이어 목록 (recipeDetail에 포함되어 있음)
        model.addAttribute("layers", recipeDetail.getRecipeLayerList());
        model.addAttribute("layerCount", recipeDetail.getRecipeLayerList() != null ? recipeDetail.getRecipeLayerList().size() : 0);

        // 차트 대시보드 목록
        model.addAttribute("charts", boardObjectList);
        model.addAttribute("chartCount", boardObjectList != null ? boardObjectList.size() : 0);

        log.info("레시피 상세보기 데이터 로드 완료 - recipeId: {}, layers: {}, charts: {}",
                recipeId,
                recipeDetail.getRecipeLayerList() != null ? recipeDetail.getRecipeLayerList().size() : 0,
                boardObjectList != null ? boardObjectList.size() : 0);

        return "ags/mrb/main/modal/recipe-detail";
    }

}
