package com.example.dateplanner.controllers.web;

import com.example.dateplanner.models.entities.GalleryPost;
import com.example.dateplanner.models.entities.SiteSettings;
import com.example.dateplanner.repositories.GalleryPostRepository;
import com.example.dateplanner.repositories.SiteSettingsRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.reactive.result.view.Rendering;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Controller
@RequiredArgsConstructor
public class HomeController extends BaseWebController {

    private final SiteSettingsRepository siteSettingsRepository;
    private final GalleryPostRepository galleryPostRepository;

    private static final String DEFAULT_HERO_IMAGE =
            "https://avatars.mds.yandex.net/get-altay/1880524/2a0000016ef11d02f18395e01a44f0ddbdb7/XXL_height";

    @GetMapping("/")
    public Mono<Rendering> home() {
        Map<String, Object> model = new HashMap<>();
        model.put("title", "Home");
        model.put("index", "home");

        Mono<SiteSettings> settingsMono = siteSettingsRepository.findFirstByOrderByUpdatedAtDesc()
                .switchIfEmpty(Mono.defer(() -> {
                    SiteSettings s = new SiteSettings();
                    s.setHeroImageUrl(DEFAULT_HERO_IMAGE);
                    s.setBackgroundImageUrl(DEFAULT_HERO_IMAGE);
                    return siteSettingsRepository.save(s);
                }));

        Mono<GalleryPost> latestPostMono = galleryPostRepository.findFirstByIsPublishedTrueOrderByPublishedAtDesc()
                .onErrorResume(e -> {
                    log.warn("Failed to fetch latest gallery post: {}", e.getMessage());
                    return Mono.empty();
                });

        return settingsMono
                .flatMap(settings -> {
                    model.put("heroImageUrl", settings.getHeroImageUrl() != null ? settings.getHeroImageUrl() : DEFAULT_HERO_IMAGE);
                    model.put("backgroundImageUrl", settings.getBackgroundImageUrl() != null ? settings.getBackgroundImageUrl() : DEFAULT_HERO_IMAGE);
                    return latestPostMono
                            .doOnNext(post -> model.put("latestGalleryPost", post))
                            .thenReturn(model)
                            .switchIfEmpty(Mono.just(model));
                })
                .flatMap(this::addAuthToModel)
                .map(m -> Rendering.view("template").model(m).build());
    }

    @GetMapping("/clubs/{id}")
    public Mono<Rendering> clubPage(@PathVariable UUID id) {
        Map<String, Object> model = new HashMap<>();
        model.put("title", "Клуб");
        model.put("index", "club");
        model.put("clubId", id.toString());
        return addAuthToModel(model).map(m ->
                Rendering.view("template").model(m).build()
        );
    }

    @GetMapping("/admin")
    public Mono<Rendering> adminPanel() {
        Map<String, Object> model = new HashMap<>();
        model.put("title", "Панель управления");
        model.put("index", "admin-panel");
        return addAuthToModel(model).map(m ->
                Rendering.view("template").model(m).build()
        );
    }
}
