package com.honey.honey.controller;

import com.honey.honey.dto.*;
import com.honey.honey.service.AdminPromotionService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/admin/promotions")
@RequiredArgsConstructor
@PreAuthorize("hasRole('ADMIN')")
public class AdminPromotionController {

    private final AdminPromotionService adminPromotionService;

    @GetMapping
    public ResponseEntity<List<AdminPromotionDto>> listPromotions() {
        return ResponseEntity.ok(adminPromotionService.listPromotions());
    }

    @GetMapping("/{id}")
    public ResponseEntity<AdminPromotionDto> getPromotion(@PathVariable int id) {
        return adminPromotionService.getPromotion(id)
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<AdminPromotionDto> createPromotion(@Valid @RequestBody AdminPromotionRequest request) {
        try {
            AdminPromotionDto dto = adminPromotionService.createPromotion(request);
            return ResponseEntity.status(HttpStatus.CREATED).body(dto);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<AdminPromotionDto> updatePromotion(
            @PathVariable int id,
            @Valid @RequestBody AdminPromotionRequest request) {
        try {
            return adminPromotionService.updatePromotion(id, request)
                    .map(ResponseEntity::ok)
                    .orElseGet(() -> ResponseEntity.notFound().build());
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deletePromotion(@PathVariable int id) {
        return adminPromotionService.deletePromotion(id)
                ? ResponseEntity.noContent().build()
                : ResponseEntity.notFound().build();
    }

    // --- Rewards ---

    @GetMapping("/{promoId}/rewards")
    public ResponseEntity<List<AdminPromotionRewardDto>> listRewards(@PathVariable int promoId) {
        return ResponseEntity.ok(adminPromotionService.listRewards(promoId));
    }

    @PostMapping("/{promoId}/rewards")
    public ResponseEntity<AdminPromotionRewardDto> createReward(
            @PathVariable int promoId,
            @Valid @RequestBody AdminPromotionRewardRequest request) {
        try {
            AdminPromotionRewardDto dto = adminPromotionService.createReward(promoId, request);
            return ResponseEntity.status(HttpStatus.CREATED).body(dto);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @PutMapping("/rewards/{rewardId}")
    public ResponseEntity<AdminPromotionRewardDto> updateReward(
            @PathVariable int rewardId,
            @Valid @RequestBody AdminPromotionRewardRequest request) {
        try {
            return adminPromotionService.updateReward(rewardId, request)
                    .map(ResponseEntity::ok)
                    .orElseGet(() -> ResponseEntity.notFound().build());
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @DeleteMapping("/rewards/{rewardId}")
    public ResponseEntity<Void> deleteReward(@PathVariable int rewardId) {
        return adminPromotionService.deleteReward(rewardId)
                ? ResponseEntity.noContent().build()
                : ResponseEntity.notFound().build();
    }

    // --- Promotion users (leaderboard / results) ---

    @GetMapping("/{promoId}/users")
    public ResponseEntity<Map<String, Object>> getPromotionUsers(
            @PathVariable int promoId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "50") int size,
            @RequestParam(required = false) String sortBy,
            @RequestParam(required = false) String sortDir,
            @RequestParam(required = false) Integer userId) {
        Page<AdminPromotionUserDto> dtoPage = adminPromotionService.getPromotionUsers(
                promoId, page, size, sortBy, sortDir, userId);
        Map<String, Object> response = new HashMap<>();
        response.put("content", dtoPage.getContent());
        response.put("totalElements", dtoPage.getTotalElements());
        response.put("totalPages", dtoPage.getTotalPages());
        response.put("currentPage", dtoPage.getNumber());
        response.put("size", dtoPage.getSize());
        response.put("hasNext", dtoPage.hasNext());
        response.put("hasPrevious", dtoPage.hasPrevious());
        return ResponseEntity.ok(response);
    }

    @PatchMapping("/{promoId}/users/{userId}/points")
    public ResponseEntity<AdminPromotionUserDto> updatePromotionUserPoints(
            @PathVariable int promoId,
            @PathVariable int userId,
            @Valid @RequestBody AdminPromotionUserPointsRequest request) {
        Optional<AdminPromotionUserDto> updated = adminPromotionService.updatePromotionUserPoints(
                promoId, userId, request.getPoints());
        return updated.map(ResponseEntity::ok).orElseGet(() -> ResponseEntity.notFound().build());
    }
}
