package com.codenetworkz.blog.web.controllers.dashboard;


import com.codenetworkz.blog.dtos.CategoryDto;
import com.codenetworkz.blog.dtos.PostDto;
import com.codenetworkz.blog.dtos.PostTagAndCategoryDto;
import com.codenetworkz.blog.exceptions.InternalServerException;
import com.codenetworkz.blog.exceptions.ResourceNotAvailable;
import com.codenetworkz.blog.mappers.PostMapper;
import com.codenetworkz.blog.models.Post;
import com.codenetworkz.blog.services.PostService;
import com.codenetworkz.blog.web.dtos.PostRequest;
import jakarta.validation.Valid;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.util.Optional;

@Controller
@RequestMapping("admin/posts")
public class AdminPostController {

    private final PostService postService;
    private final PostMapper postMapper;

    public AdminPostController(PostService postService, PostMapper postMapper) {
        this.postService = postService;
        this.postMapper = postMapper;
    }

    @GetMapping("save")
    public String savePostPage(Model model) throws InternalServerException {
        model.addAttribute("pageTitle", "Add new Post");
        Optional<PostTagAndCategoryDto> postRequestData = postService.getPostRequestData();
        PostRequest postRequest=new PostRequest();
        model.addAttribute("post",postRequest);
        model.addAttribute("tags", postRequestData.get().getTags());
        model.addAttribute("categories", postRequestData.get().getCategories());
        return "admin/blog/post/save";
    }

    @PostMapping("save")
    public String savePostetails(@Valid @ModelAttribute("post") PostRequest postRequest,
                                 @RequestParam("image") MultipartFile file,
                                 BindingResult rbindingResult, Model model) throws InternalServerException, FileUploadException, ResourceNotAvailable {
        if (rbindingResult.hasErrors()) {
            return "redirect:/admin/posts/save";
        }
        model.addAttribute("pageTitle", "Add new Post");
        postService.save(postRequest.getName(), postRequest.getContent(), postRequest.getTags(), postRequest.getCategories(), file, postRequest.getPublishedStatus(), null);
        return "admin/blog/post/save";
    }

    @GetMapping("views")
    public String viewPosts(@RequestParam(name = "page", defaultValue = "0") Integer page,
                            @RequestParam(name = "size", defaultValue = "10") Integer size, Model model) throws InternalServerException, ResourceNotAvailable {
        model.addAttribute("pageTitle", "List of Posts");
        Page<PostDto> postDtoList = postService.getPostWithPagination(page,size);
        model.addAttribute("posts",postDtoList);
        return "admin/blog/post/views";
    }

    @GetMapping("view/{slug}")
    public String viewSinglePost(@PathVariable String slug, Model model) throws InternalServerException, ResourceNotAvailable {
        model.addAttribute("pageTitle", "Update old Post");
        Optional<Post> post = postService.findByPostSlug(slug);
        Optional<PostDto> postDto = postMapper.postToPostDto(post);
        model.addAttribute("post", postDto.get());
        return "admin/blog/post/view";
    }

    @GetMapping("update/{slug}")
    public String updatePostPage(@PathVariable String slug,Model model) throws InternalServerException, ResourceNotAvailable {
        model.addAttribute("pageTitle", "Update old Post");
        Optional<Post> post = postService.findByPostSlug(slug);
        Optional<PostDto> postDto = postMapper.postToPostDto(post);
        model.addAttribute("post", postDto.get());
        Optional<PostTagAndCategoryDto> postRequestData = postService.getPostRequestData();
        model.addAttribute("tags", postRequestData.get().getTags());
        model.addAttribute("categories", postRequestData.get().getCategories());
        return "admin/blog/post/update";
    }

    @PostMapping("update")
    public String updatePostDetails(@Valid @ModelAttribute("post") PostRequest postRequest,
                                    @RequestParam("image") MultipartFile file,
                                    BindingResult rbindingResult, @PathVariable String slug, Model model) throws InternalServerException, FileUploadException, ResourceNotAvailable {
        model.addAttribute("pageTitle", "Update old Post");
        if (rbindingResult.hasErrors()) {
            return "redirect:/admin/posts/save";
        }
        postService.update(slug, postRequest.getName(), postRequest.getContent(), postRequest.getTags(), postRequest.getCategories(), file, postRequest.getPublishedStatus(), null);
        return "redirect:/admin/posts/views";
    }


    @DeleteMapping("delete/{slug}")
    public String deleteSinglePost(@PathVariable String slug, Model model) throws InternalServerException, ResourceNotAvailable {
        model.addAttribute("pageTitle", "Delete old Post");
        Optional<PostDto> postDto = postService.delete(slug);
        return "redirect:/admin/posts/views";
    }

    @GetMapping("list")
    public String viewlistPosts(@RequestParam(name = "page", defaultValue = "0") Integer page,
                                @RequestParam(name = "size", defaultValue = "10") Integer size, Model model) throws InternalServerException, ResourceNotAvailable {
        model.addAttribute("pageTitle", "List of Posts");
        Page<PostDto> postDtoList = postService.getPostWithPagination(page,size);
        model.addAttribute("posts",postDtoList);
        return "admin/blog/post/views";
    }

    @PostMapping("change-status/{slug}")
    public String changeActiveStatus(@PathVariable String slug, Model model) throws InternalServerException, ResourceNotAvailable {
        Optional<PostDto> postDto = postService.changeActivateStatus(slug);
        if(postDto.isPresent()){
            model.addAttribute("message", "Successfully changed status category");
            return "redirect:/admin/categories/views";
        }
        return "redirect:/admin/categories/views";
    }

    @PostMapping("admin-approve/{slug}")
    public String approveCategoryCategory(@PathVariable String slug, Model model) throws InternalServerException, ResourceNotAvailable {
//        Optional<CategoryDto> categoryDto = categoryService.changeApprovalStatus(slug);
//        if(categoryDto.isPresent()){
//            model.addAttribute("message", "Successfully changed status category");
//            return "redirect:/admin/categories/views";
//        }
        return "redirect:/admin/categories/views";
    }
}
