package com.home4j.resource;

import com.home4j.dto.BookmarkDTO;
import com.home4j.dto.GroupDTO;
import com.home4j.entity.Bookmark;
import com.home4j.entity.BookmarkGroup;
import com.home4j.service.BookmarkService;
import com.home4j.service.ConfigService;
import io.quarkus.qute.Template;
import io.quarkus.qute.TemplateInstance;
import io.quarkus.security.Authenticated;
import jakarta.annotation.security.RolesAllowed;
import jakarta.inject.Inject;
import jakarta.validation.Valid;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;

import java.net.URI;
import java.util.List;
import java.util.Map;

/**
 * 管理后台控制器 - 需要登录
 */
@Path("/admin")
@RolesAllowed("ADMIN")
public class AdminResource {

    @Inject
    Template admin;

    @Inject
    Template adminGroups;

    @Inject
    Template adminBookmarks;

    @Inject
    Template adminSettings;

    @Inject
    BookmarkService bookmarkService;

    @Inject
    ConfigService configService;

    /**
     * 管理后台首页
     */
    @GET
    @Produces(MediaType.TEXT_HTML)
    public TemplateInstance adminIndex() {
        return admin
                .data("groups", bookmarkService.getAllGroups())
                .data("siteTitle", configService.getSiteTitle());
    }

    // ==================== 分组管理 ====================

    /**
     * 分组管理页面
     */
    @GET
    @Path("/groups")
    @Produces(MediaType.TEXT_HTML)
    public TemplateInstance groupsPage() {
        return adminGroups
                .data("groups", bookmarkService.getAllGroups())
                .data("siteTitle", configService.getSiteTitle());
    }

    /**
     * 创建分组
     */
    @POST
    @Path("/groups")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response createGroup(@FormParam("name") String name, @FormParam("icon") String icon) {
        bookmarkService.createGroup(name, icon);
        return Response.seeOther(URI.create("/admin/groups")).build();
    }

    /**
     * 更新分组
     */
    @POST
    @Path("/groups/{id}")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response updateGroup(@PathParam("id") Long id,
                                @FormParam("name") String name,
                                @FormParam("icon") String icon,
                                @FormParam("visible") Boolean visible) {
        bookmarkService.updateGroup(id, name, icon, visible);
        return Response.seeOther(URI.create("/admin/groups")).build();
    }

    /**
     * 删除分组
     */
    @POST
    @Path("/groups/{id}/delete")
    public Response deleteGroup(@PathParam("id") Long id) {
        bookmarkService.deleteGroup(id);
        return Response.seeOther(URI.create("/admin/groups")).build();
    }

    // ==================== 书签管理 ====================

    /**
     * 书签管理页面
     */
    @GET
    @Path("/bookmarks")
    @Produces(MediaType.TEXT_HTML)
    public TemplateInstance bookmarksPage(@QueryParam("groupId") Long groupId) {
        List<Bookmark> bookmarks;
        if (groupId != null) {
            bookmarks = Bookmark.findByGroupIdOrdered(groupId);
        } else {
            bookmarks = Bookmark.listAll();
        }
        return adminBookmarks
                .data("bookmarks", bookmarks)
                .data("groups", bookmarkService.getAllGroups())
                .data("selectedGroupId", groupId)
                .data("siteTitle", configService.getSiteTitle());
    }

    /**
     * 创建书签
     */
    @POST
    @Path("/bookmarks")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response createBookmark(@FormParam("groupId") Long groupId,
                                   @FormParam("name") String name,
                                   @FormParam("url") String url,
                                   @FormParam("description") String description,
                                   @FormParam("icon") String icon,
                                   @FormParam("openInNewTab") Boolean openInNewTab) {
        bookmarkService.createBookmark(groupId, name, url, description, icon, openInNewTab);
        return Response.seeOther(URI.create("/admin/bookmarks")).build();
    }

    /**
     * 更新书签
     */
    @POST
    @Path("/bookmarks/{id}")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response updateBookmark(@PathParam("id") Long id,
                                   @FormParam("groupId") Long groupId,
                                   @FormParam("name") String name,
                                   @FormParam("url") String url,
                                   @FormParam("description") String description,
                                   @FormParam("icon") String icon,
                                   @FormParam("visible") Boolean visible,
                                   @FormParam("openInNewTab") Boolean openInNewTab) {
        bookmarkService.updateBookmark(id, groupId, name, url, description, icon, visible, openInNewTab);
        return Response.seeOther(URI.create("/admin/bookmarks")).build();
    }

    /**
     * 删除书签
     */
    @POST
    @Path("/bookmarks/{id}/delete")
    public Response deleteBookmark(@PathParam("id") Long id) {
        bookmarkService.deleteBookmark(id);
        return Response.seeOther(URI.create("/admin/bookmarks")).build();
    }

    // ==================== 系统设置 ====================

    /**
     * 系统设置页面
     */
    @GET
    @Path("/settings")
    @Produces(MediaType.TEXT_HTML)
    public TemplateInstance settingsPage() {
        return adminSettings
                .data("config", configService.getAll())
                .data("siteTitle", configService.getSiteTitle());
    }

    /**
     * 保存系统设置
     */
    @POST
    @Path("/settings")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response saveSettings(@FormParam("site_title") String siteTitle,
                                 @FormParam("site_subtitle") String siteSubtitle,
                                 @FormParam("theme") String theme,
                                 @FormParam("footer_text") String footerText,
                                 @FormParam("search_engine") String searchEngine,
                                 @FormParam("show_search") String showSearch) {
        configService.set("site_title", siteTitle);
        configService.set("site_subtitle", siteSubtitle);
        configService.set("theme", theme);
        configService.set("footer_text", footerText);
        configService.set("search_engine", searchEngine);
        configService.set("show_search", showSearch != null ? "true" : "false");
        return Response.seeOther(URI.create("/admin/settings")).build();
    }

    // ==================== API 接口 ====================

    /**
     * 获取所有分组 API
     */
    @GET
    @Path("/api/groups")
    @Produces(MediaType.APPLICATION_JSON)
    public List<BookmarkGroup> getGroupsApi() {
        return bookmarkService.getAllGroups();
    }

    /**
     * 获取所有书签 API
     */
    @GET
    @Path("/api/bookmarks")
    @Produces(MediaType.APPLICATION_JSON)
    public List<Bookmark> getBookmarksApi(@QueryParam("groupId") Long groupId) {
        if (groupId != null) {
            return Bookmark.findByGroupIdOrdered(groupId);
        }
        return Bookmark.listAll();
    }

    /**
     * 更新分组排序 API
     */
    @POST
    @Path("/api/groups/order")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response updateGroupOrder(List<Long> groupIds) {
        bookmarkService.updateGroupOrder(groupIds);
        return Response.ok().entity("{\"success\": true}").build();
    }

    /**
     * 更新书签排序 API
     */
    @POST
    @Path("/api/bookmarks/order")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response updateBookmarkOrder(List<Long> bookmarkIds) {
        bookmarkService.updateBookmarkOrder(bookmarkIds);
        return Response.ok().entity("{\"success\": true}").build();
    }
}
