package com.weighttracker.controller;

import com.weighttracker.model.WeightRecord;
import com.weighttracker.repository.UserRepository;
import com.weighttracker.service.WeightService;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Controller
public class DashboardController {

    private final WeightService weightService;
    private final UserRepository userRepo;

    public DashboardController(WeightService weightService, UserRepository userRepo) {
        this.weightService = weightService;
        this.userRepo = userRepo;
    }

    @GetMapping("/")
    public String home(@AuthenticationPrincipal UserDetails ud,
                       @RequestParam(required = false) String start,
                       @RequestParam(required = false) String end,
                       Model model) {

        var user = userRepo.findByUsername(ud.getUsername()).orElseThrow();
        model.addAttribute("ultimos", weightService.last10(user));

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDateTime startDate = (start != null) ? LocalDate.parse(start, formatter).atStartOfDay()
                                                  : LocalDateTime.now().minusDays(30);
        LocalDateTime endDate = (end != null) ? LocalDate.parse(end, formatter).atTime(LocalTime.MAX)
                                              : LocalDateTime.now();

        List<WeightRecord> registros = weightService.recordsBetween(user, startDate, endDate);
        model.addAttribute("labels", registros.stream().map(r -> r.getDate().toLocalDate().toString()).toList());
        model.addAttribute("pesos", registros.stream().map(WeightRecord::getWeight).toList());
        model.addAttribute("grasa", registros.stream().map(WeightRecord::getBodyFat).toList());
        model.addAttribute("musculo", registros.stream().map(WeightRecord::getMuscleMass).toList());
        model.addAttribute("agua", registros.stream().map(WeightRecord::getWaterPercent).toList());
        model.addAttribute("bmi", registros.stream().map(WeightRecord::getBmi).toList());
        model.addAttribute("edadMetabolica", registros.stream().map(WeightRecord::getMetabolicAge).toList());
        model.addAttribute("grasaVisceral", registros.stream().map(WeightRecord::getVisceralFat).toList());

        return "dashboard";
    }
}
