package com.mvrent.carrental.controller;

import com.mvrent.carrental.model.Vendor;
import com.mvrent.carrental.service.SettlementService;
import com.mvrent.carrental.service.VendorService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
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;

@Controller
@RequestMapping("/admin/vendors")
@RequiredArgsConstructor
@PreAuthorize("hasRole('ADMIN') or hasAuthority('MANAGE_VENDORS')")
public class AdminVendorController {

    private final VendorService vendorService;
    private final SettlementService settlementService;

    @GetMapping
    public String list(Model model) {
        model.addAttribute("vendors", vendorService.findAll());
        return "admin/vendors";
    }

    @GetMapping("/new")
    public String newVendor(Model model) {
        if (!model.containsAttribute("vendor")) {
            model.addAttribute("vendor", new Vendor());
        }
        return "admin/vendor-form";
    }

    @PostMapping
    public String save(@Valid @ModelAttribute("vendor") Vendor vendor,
                       BindingResult result,
                       RedirectAttributes ra) {
        if (result.hasErrors()) {
            return "admin/vendor-form";
        }
        Vendor saved = vendorService.save(vendor);
        ra.addFlashAttribute("success", "Vendor saved");
        return "redirect:/admin/vendors/" + saved.getId();
    }

    @GetMapping("/{id}")
    public String detail(@PathVariable Long id, Model model) {
        Vendor vendor = vendorService.findById(id);
        model.addAttribute("vendor", vendor);
        model.addAttribute("cars", vendorService.cars(id));
        model.addAttribute("drivers", vendorService.drivers(id));
        model.addAttribute("revenue", vendorService.revenue(id));
        model.addAttribute("settlements", settlementService.findByVendor(id));
        model.addAttribute("initials", initials(vendor.getName()));
        return "admin/vendor-detail";
    }

    private static String initials(String name) {
        if (name == null || name.isBlank()) return "?";
        String[] p = name.trim().split("\\s+");
        if (p.length >= 2 && !p[0].isEmpty() && !p[1].isEmpty()) {
            return ("" + p[0].charAt(0) + p[1].charAt(0)).toUpperCase();
        }
        return name.substring(0, Math.min(2, name.length())).toUpperCase();
    }

    @GetMapping("/{id}/edit")
    public String edit(@PathVariable Long id, Model model) {
        model.addAttribute("vendor", vendorService.findById(id));
        return "admin/vendor-form";
    }

    @PostMapping("/{id}/delete")
    public String delete(@PathVariable Long id, RedirectAttributes ra) {
        vendorService.delete(id);
        ra.addFlashAttribute("success", "Vendor deleted");
        return "redirect:/admin/vendors";
    }

    @PostMapping("/{id}/portal-user")
    public String createPortalUser(@PathVariable Long id,
                                   @RequestParam String username,
                                   @RequestParam String email,
                                   @RequestParam String password,
                                   RedirectAttributes ra) {
        try {
            vendorService.createPortalUser(id, username, email, password);
            ra.addFlashAttribute("success", "Vendor portal login created for '" + username + "'");
        } catch (IllegalArgumentException ex) {
            ra.addFlashAttribute("error", ex.getMessage());
        }
        return "redirect:/admin/vendors/" + id;
    }
}
