package com.mvrent.carrental.controller;

import com.mvrent.carrental.model.CategoryType;
import com.mvrent.carrental.model.Organization;
import com.mvrent.carrental.model.SystemConfig;
import com.mvrent.carrental.service.ConfigService;
import com.mvrent.carrental.service.NotificationService;
import com.mvrent.carrental.service.SmsService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
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.servlet.mvc.support.RedirectAttributes;

import java.util.Map;

@Controller
@RequestMapping("/admin/settings")
@RequiredArgsConstructor
@PreAuthorize("hasRole('ADMIN') or hasAuthority('MANAGE_CONFIG')")
public class AdminSettingsController {

    private final ConfigService configService;
    private final NotificationService notificationService;
    private final SmsService smsService;

    /* ---------- Organization + System config ---------- */

    @GetMapping
    public String settings(Model model) {
        if (!model.containsAttribute("organization")) {
            model.addAttribute("organization", configService.getOrganization());
        }
        if (!model.containsAttribute("config")) {
            model.addAttribute("config", configService.getSystemConfig());
        }
        model.addAttribute("mailReady", notificationService.isReady());
        model.addAttribute("smsEnabled", smsService.isEnabled());
        model.addAttribute("adminEmail", notificationService.adminEmail());
        return "admin/settings";
    }

    @PostMapping("/test-email")
    @ResponseBody
    public ResponseEntity<?> testEmail(@RequestParam String to) {
        try {
            notificationService.sendTest(to);
            return ResponseEntity.ok(Map.of("ok", true));
        } catch (RuntimeException ex) {
            return ResponseEntity.badRequest().body(Map.of("ok", false, "message", ex.getMessage()));
        }
    }

    @PostMapping("/organization")
    public String saveOrganization(@Valid @ModelAttribute("organization") Organization organization,
                                   BindingResult result,
                                   Model model,
                                   RedirectAttributes ra) {
        if (result.hasErrors()) {
            model.addAttribute("config", configService.getSystemConfig());
            return "admin/settings";
        }
        configService.saveOrganization(organization);
        ra.addFlashAttribute("success", "Organization profile saved");
        return "redirect:/admin/settings";
    }

    @PostMapping("/config")
    public String saveConfig(@Valid @ModelAttribute("config") SystemConfig config,
                             BindingResult result,
                             Model model,
                             RedirectAttributes ra) {
        if (result.hasErrors()) {
            model.addAttribute("organization", configService.getOrganization());
            return "admin/settings";
        }
        configService.saveSystemConfig(config);
        ra.addFlashAttribute("success", "System configuration saved");
        return "redirect:/admin/settings";
    }

    /* ---------- Category masters ---------- */

    @GetMapping("/categories")
    public String categories(Model model) {
        model.addAttribute("categories", configService.allCategories());
        model.addAttribute("types", CategoryType.values());
        return "admin/categories";
    }

    @PostMapping("/categories")
    public String addCategory(@RequestParam CategoryType type,
                              @RequestParam String name,
                              @RequestParam(required = false) String description,
                              RedirectAttributes ra) {
        try {
            configService.addCategory(type, name.trim(), description);
            ra.addFlashAttribute("success", type + " category '" + name + "' added");
        } catch (IllegalArgumentException ex) {
            ra.addFlashAttribute("error", ex.getMessage());
        }
        return "redirect:/admin/settings/categories";
    }

    @PostMapping("/categories/{id}/toggle")
    public String toggleCategory(@PathVariable Long id, RedirectAttributes ra) {
        configService.toggleCategory(id);
        ra.addFlashAttribute("success", "Category updated");
        return "redirect:/admin/settings/categories";
    }

    @PostMapping("/categories/{id}/delete")
    public String deleteCategory(@PathVariable Long id, RedirectAttributes ra) {
        configService.deleteCategory(id);
        ra.addFlashAttribute("success", "Category deleted");
        return "redirect:/admin/settings/categories";
    }
}
