"use client";

import React, { useState, useCallback, useEffect } from "react";
import { use } from "react";
import { Button } from "@/components/ui/button";
import { ArrowLeft, Users, Menu as MenuIcon, Save, AlertCircle, Building2, User as UserIcon } from "lucide-react";
import { roleAPI, RoleGroup } from "@/lib/api/role";
import { useAuth } from "@/hooks/useAuth";
import { useRouter } from "next/navigation";
import { DualListBox } from "@/components/common/DualListBox";
import { MenuPermissionsTable } from "@/components/admin/MenuPermissionsTable";
import { useMenu } from "@/contexts/MenuContext";
import { ScrollToTop } from "@/components/common/ScrollToTop";
import { usePageMultiLang } from "@/hooks/usePageMultiLang";

const LANG_KEYS = [
  "detail.loading",
  "detail.error.title",
  "detail.error.load",
  "detail.error.load.generic",
  "detail.error.notfound",
  "detail.button.backToList",
  "detail.status.active",
  "detail.status.inactive",
  "detail.tab.members",
  "detail.tab.permissions",
  "detail.members.title",
  "detail.members.description",
  "detail.members.mode.user",
  "detail.members.mode.dept",
  "detail.members.saving",
  "detail.members.save",
  "detail.members.available",
  "detail.members.selected",
  "detail.members.dept.available",
  "detail.members.dept.selected",
  "detail.members.summary",
  "detail.members.summary.count",
  "detail.members.empty",
  "detail.members.save.success",
  "detail.members.save.fail",
  "detail.members.save.error",
  "detail.permissions.title",
  "detail.permissions.description",
  "detail.permissions.saving",
  "detail.permissions.save",
  "detail.permissions.save.success",
  "detail.permissions.save.fail",
  "detail.permissions.save.error",
  "detail.count.members",
] as const;

const DEFAULT_TEXTS: Record<string, string> = {
  "detail.loading": "권한 그룹 정보를 불러오는 중...",
  "detail.error.title": "오류 발생",
  "detail.error.load": "권한 그룹 정보를 불러오는데 실패했습니다.",
  "detail.error.load.generic": "권한 그룹 정보를 불러오는 중 오류가 발생했습니다.",
  "detail.error.notfound": "권한 그룹을 찾을 수 없습니다.",
  "detail.button.backToList": "목록으로 돌아가기",
  "detail.status.active": "활성",
  "detail.status.inactive": "비활성",
  "detail.tab.members": "멤버 관리",
  "detail.tab.permissions": "메뉴 권한",
  "detail.members.title": "멤버 관리",
  "detail.members.description": "이 권한 그룹에 속한 사용자를 관리합니다",
  "detail.members.mode.user": "사용자별",
  "detail.members.mode.dept": "부서별",
  "detail.members.saving": "저장 중...",
  "detail.members.save": "멤버 저장",
  "detail.members.available": "전체 사용자",
  "detail.members.selected": "그룹 멤버",
  "detail.members.dept.available": "부서 목록 (선택 시 소속 사용자 전체 추가)",
  "detail.members.dept.selected": "추가된 부서",
  "detail.members.summary": "현재 그룹 멤버",
  "detail.members.summary.count": "현재 그룹 멤버 ({count}명)",
  "detail.members.empty": "멤버가 없습니다",
  "detail.members.save.success": "멤버가 성공적으로 저장되었습니다.",
  "detail.members.save.fail": "멤버 저장에 실패했습니다.",
  "detail.members.save.error": "멤버 저장 중 오류가 발생했습니다.",
  "detail.permissions.title": "메뉴 권한 설정",
  "detail.permissions.description": "이 권한 그룹에서 접근 가능한 메뉴와 권한을 설정합니다",
  "detail.permissions.saving": "저장 중...",
  "detail.permissions.save": "권한 저장",
  "detail.permissions.save.success": "메뉴 권한이 성공적으로 저장되었습니다.",
  "detail.permissions.save.fail": "메뉴 권한 저장에 실패했습니다.",
  "detail.permissions.save.error": "메뉴 권한 저장 중 오류가 발생했습니다.",
  "detail.count.members": "{count}명",
};

/**
 * 권한 그룹 상세 페이지
 * URL: /admin/userMng/rolesList/[id]
 *
 * 기능:
 * - 권한 그룹 멤버 관리 (Dual List Box)
 * - 메뉴 권한 설정 (CRUD 체크박스)
 */
export default function RoleDetailPage({ params }: { params: Promise<{ id: string }> }) {
  // Next.js 15: params는 Promise이므로 React.use()로 unwrap
  const { id: roleId } = use(params);
  const { user: currentUser } = useAuth();
  const router = useRouter();
  const { refreshMenus } = useMenu();
  const { t } = usePageMultiLang({ keys: LANG_KEYS, defaults: DEFAULT_TEXTS, menuCode: "roles.management" });

  const isSuperAdmin = currentUser?.companyCode === "*" && currentUser?.userType === "SUPER_ADMIN";

  // 상태 관리
  const [roleGroup, setRoleGroup] = useState<RoleGroup | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 탭 상태
  const [activeTab, setActiveTab] = useState<"members" | "permissions">("members");

  // 멤버 관리 상태
  const [memberMode, setMemberMode] = useState<"user" | "dept">("user");
  const [availableUsers, setAvailableUsers] = useState<Array<{ id: string; name: string; dept?: string }>>([]);
  const [selectedUsers, setSelectedUsers] = useState<Array<{ id: string; name: string; dept?: string }>>([]);
  const [availableDepts, setAvailableDepts] = useState<Array<{ id: string; label: string; description?: string; userIds: string[] }>>([]);
  const [selectedDepts, setSelectedDepts] = useState<Array<{ id: string; label: string; description?: string; userIds: string[] }>>([]);
  const [allUsersMap, setAllUsersMap] = useState<Map<string, { id: string; label: string; description?: string }>>(new Map());
  const [isSavingMembers, setIsSavingMembers] = useState(false);

  // 메뉴 권한 상태
  const [menuPermissions, setMenuPermissions] = useState<any[]>([]);
  const [isSavingPermissions, setIsSavingPermissions] = useState(false);

  // 데이터 로드
  const loadRoleGroup = useCallback(async () => {
    setIsLoading(true);
    setError(null);

    try {
      const response = await roleAPI.getById(parseInt(roleId, 10));

      if (response.success && response.data) {
        setRoleGroup(response.data);
      } else {
        setError(response.message || t("detail.error.load"));
      }
    } catch (err) {
      console.error("권한 그룹 정보 로드 오류:", err);
      setError(t("detail.error.load.generic"));
    } finally {
      setIsLoading(false);
    }
  }, [roleId]);

  // 멤버 목록 로드
  const loadMembers = useCallback(async () => {
    if (!roleGroup) return;

    try {
      // 1. 권한 그룹 멤버 조회
      const membersResponse = await roleAPI.getMembers(roleGroup.objid);
      if (membersResponse.success && membersResponse.data) {
        setSelectedUsers(
          membersResponse.data.map((member: any) => ({
            id: member.userId,
            label: member.userName || member.userId,
            description: member.deptName,
          })),
        );
      }

      // 2. 전체 사용자 목록 조회 (같은 회사)
      const userAPI = await import("@/lib/api/user");
      const usersResponse = await userAPI.userAPI.getList({
        companyCode: roleGroup.companyCode,
        size: 1000,
      });

      if (usersResponse.success && usersResponse.data) {
        const userItems = usersResponse.data.map((user: any) => ({
          id: user.userId,
          label: user.userName || user.userId,
          description: user.deptName,
        }));
        setAvailableUsers(userItems);

        // 전체 사용자 맵 저장 (부서별 추가 시 사용)
        const uMap = new Map<string, { id: string; label: string; description?: string }>();
        userItems.forEach((u: any) => uMap.set(u.id, u));
        setAllUsersMap(uMap);

        // 3. 부서 목록 로드 + 부서별 사용자 수 계산
        const { getDepartments } = await import("@/lib/api/department");
        const deptsResponse = await getDepartments(roleGroup.companyCode);
        const depts = deptsResponse?.success ? deptsResponse.data : deptsResponse;
        if (Array.isArray(depts)) {
          // 부서별 사용자 그룹핑
          const deptUserMap = new Map<string, string[]>();
          usersResponse.data.forEach((user: any) => {
            const deptCode = user.deptCode || user.dept_code;
            if (deptCode) {
              if (!deptUserMap.has(deptCode)) deptUserMap.set(deptCode, []);
              deptUserMap.get(deptCode)!.push(user.userId);
            }
          });

          setAvailableDepts(
            depts.map((dept: any) => {
              const deptCode = dept.deptCode || dept.dept_code;
              const userIds = deptUserMap.get(deptCode) || [];
              return {
                id: `dept_${deptCode}`,
                label: dept.deptName || dept.dept_name || deptCode,
                description: t("detail.count.members", { count: userIds.length }),
                userIds,
              };
            }).filter((d: any) => d.userIds.length > 0),
          );
        }
      }
    } catch (err) {
      console.error("멤버 목록 로드 오류:", err);
    }
  }, [roleGroup]);

  // 메뉴 권한 로드
  const loadMenuPermissions = useCallback(async () => {
    if (!roleGroup) return;

    console.log("🔍 [loadMenuPermissions] 메뉴 권한 로드 시작", {
      roleGroupId: roleGroup.objid,
      roleGroupName: roleGroup.authName,
      companyCode: roleGroup.companyCode,
    });

    try {
      const response = await roleAPI.getMenuPermissions(roleGroup.objid);

      console.log("✅ [loadMenuPermissions] API 응답", {
        success: response.success,
        dataCount: response.data?.length,
        data: response.data,
      });

      if (response.success && response.data) {
        setMenuPermissions(response.data);
        console.log("✅ [loadMenuPermissions] 상태 업데이트 완료", {
          count: response.data.length,
        });
      } else {
        console.warn("⚠️ [loadMenuPermissions] 응답 실패", {
          message: response.message,
        });
      }
    } catch (err) {
      console.error("❌ [loadMenuPermissions] 메뉴 권한 로드 오류:", err);
    }
  }, [roleGroup]);

  useEffect(() => {
    loadRoleGroup();
  }, [loadRoleGroup]);

  useEffect(() => {
    if (roleGroup && activeTab === "members") {
      loadMembers();
    } else if (roleGroup && activeTab === "permissions") {
      loadMenuPermissions();
    }
  }, [roleGroup, activeTab, loadMembers, loadMenuPermissions]);

  // 부서 선택 변경 시 우측에 부서 표시 + 해당 사용자를 멤버에 추가
  const handleDeptSelectionChange = useCallback(
    (newSelectedDepts: Array<{ id: string; label: string; description?: string; [key: string]: any }>) => {
      // 새로 추가된 부서 찾기
      const prevIds = new Set(selectedDepts.map((d) => d.id));
      const addedDepts = newSelectedDepts.filter((d) => !prevIds.has(d.id));

      // 우측 부서 목록 업데이트
      setSelectedDepts(newSelectedDepts as typeof selectedDepts);

      // 새로 추가된 부서의 사용자만 멤버에 추가
      if (addedDepts.length > 0) {
        const userIdsToAdd = new Set<string>();
        addedDepts.forEach((deptItem) => {
          const fullDept = availableDepts.find((d) => d.id === deptItem.id);
          fullDept?.userIds.forEach((uid) => userIdsToAdd.add(uid));
        });

        const existingIds = new Set(selectedUsers.map((u) => u.id));
        const newUsers: Array<{ id: string; label: string; description?: string }> = [];
        userIdsToAdd.forEach((uid) => {
          if (!existingIds.has(uid)) {
            const userInfo = allUsersMap.get(uid);
            if (userInfo) newUsers.push(userInfo);
          }
        });

        if (newUsers.length > 0) {
          setSelectedUsers((prev) => [...prev, ...newUsers]);
        }
      }
    },
    [availableDepts, selectedDepts, selectedUsers, allUsersMap],
  );

  // 멤버 저장 핸들러
  const handleSaveMembers = useCallback(async () => {
    if (!roleGroup) return;

    setIsSavingMembers(true);
    try {
      // 현재 선택된 사용자 ID 목록
      const selectedUserIds = selectedUsers.map((user) => user.id);

      // 멤버 업데이트 API 호출
      const response = await roleAPI.updateMembers(roleGroup.objid, selectedUserIds);

      if (response.success) {
        alert(t("detail.members.save.success"));
        loadMembers(); // 새로고침

        // 사이드바 메뉴 새로고침 (현재 사용자가 영향받을 수 있음)
        await refreshMenus();
      } else {
        alert(response.message || t("detail.members.save.fail"));
      }
    } catch (err) {
      console.error("멤버 저장 오류:", err);
      alert(t("detail.members.save.error"));
    } finally {
      setIsSavingMembers(false);
    }
  }, [roleGroup, selectedUsers, loadMembers, refreshMenus]);

  // 메뉴 권한 저장 핸들러
  const handleSavePermissions = useCallback(async () => {
    if (!roleGroup) return;

    setIsSavingPermissions(true);
    try {
      const response = await roleAPI.setMenuPermissions(roleGroup.objid, menuPermissions);

      if (response.success) {
        alert(t("detail.permissions.save.success"));
        loadMenuPermissions(); // 새로고침

        // 사이드바 메뉴 새로고침 (권한 변경 즉시 반영)
        await refreshMenus();
      } else {
        alert(response.message || t("detail.permissions.save.fail"));
      }
    } catch (err) {
      console.error("메뉴 권한 저장 오류:", err);
      alert(t("detail.permissions.save.error"));
    } finally {
      setIsSavingPermissions(false);
    }
  }, [roleGroup, menuPermissions, loadMenuPermissions, refreshMenus]);

  if (isLoading) {
    return (
      <div className="bg-card flex h-64 flex-col items-center justify-center rounded-lg border p-12 shadow-sm">
        <div className="flex flex-col items-center gap-4">
          <div className="border-primary h-8 w-8 animate-spin rounded-full border-4 border-t-transparent"></div>
          <p className="text-muted-foreground text-sm">{t("detail.loading")}</p>
        </div>
      </div>
    );
  }

  if (error || !roleGroup) {
    return (
      <div className="bg-card flex h-64 flex-col items-center justify-center rounded-lg border p-6 shadow-sm">
        <AlertCircle className="text-destructive mb-4 h-12 w-12" />
        <h3 className="mb-2 text-lg font-semibold">{t("detail.error.title")}</h3>
        <p className="text-muted-foreground mb-4 text-center text-sm">{error || t("detail.error.notfound")}</p>
        <Button variant="outline" onClick={() => router.push("/admin/userMng/rolesList")}>
          {t("detail.button.backToList")}
        </Button>
      </div>
    );
  }

  return (
    <div className="bg-background h-full overflow-y-auto">
      <div className="space-y-6 p-6">
        {/* 페이지 헤더 */}
        <div className="space-y-2 border-b pb-4">
          <div className="flex items-center gap-4">
            <Button variant="ghost" size="icon" onClick={() => router.push("/admin/userMng/rolesList")} className="h-10 w-10">
              <ArrowLeft className="h-5 w-5" />
            </Button>
            <div className="flex-1">
              <h1 className="text-3xl font-bold tracking-tight">{roleGroup.authName}</h1>
              <p className="text-muted-foreground text-sm">{roleGroup.authCode}</p>
            </div>
            <span
              className={`rounded-full px-3 py-1 text-sm font-medium ${
                roleGroup.status === "active" ? "bg-emerald-100 text-emerald-800" : "bg-muted text-foreground"
              }`}
            >
              {roleGroup.status === "active" ? t("detail.status.active") : t("detail.status.inactive")}
            </span>
          </div>
        </div>

        {/* 탭 네비게이션 */}
        <div className="flex gap-4 border-b">
          <button
            onClick={() => setActiveTab("members")}
            className={`flex items-center gap-2 border-b-2 px-4 py-3 text-sm font-medium transition-colors ${
              activeTab === "members"
                ? "border-primary text-primary"
                : "text-muted-foreground hover:text-foreground border-transparent"
            }`}
          >
            <Users className="h-4 w-4" />
            {t("detail.tab.members")} ({selectedUsers.length})
          </button>
          <button
            onClick={() => setActiveTab("permissions")}
            className={`flex items-center gap-2 border-b-2 px-4 py-3 text-sm font-medium transition-colors ${
              activeTab === "permissions"
                ? "border-primary text-primary"
                : "text-muted-foreground hover:text-foreground border-transparent"
            }`}
          >
            <MenuIcon className="h-4 w-4" />
            {t("detail.tab.permissions")} ({menuPermissions.length})
          </button>
        </div>

        {/* 탭 컨텐츠 */}
        <div className="space-y-6">
          {activeTab === "members" && (
            <>
              <div className="flex items-center justify-between">
                <div>
                  <h2 className="text-xl font-semibold">{t("detail.members.title")}</h2>
                  <p className="text-muted-foreground text-sm">{t("detail.members.description")}</p>
                </div>
                <div className="flex items-center gap-3">
                  {/* 사용자별/부서별 모드 전환 */}
                  <div className="flex rounded-lg border p-0.5">
                    <button
                      onClick={() => setMemberMode("user")}
                      className={`flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-colors ${
                        memberMode === "user" ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:text-foreground"
                      }`}
                    >
                      <UserIcon className="h-3.5 w-3.5" />
                      {t("detail.members.mode.user")}
                    </button>
                    <button
                      onClick={() => setMemberMode("dept")}
                      className={`flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-colors ${
                        memberMode === "dept" ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:text-foreground"
                      }`}
                    >
                      <Building2 className="h-3.5 w-3.5" />
                      {t("detail.members.mode.dept")}
                    </button>
                  </div>
                  <Button onClick={handleSaveMembers} disabled={isSavingMembers} className="gap-2">
                    <Save className="h-4 w-4" />
                    {isSavingMembers ? t("detail.members.saving") : t("detail.members.save")}
                  </Button>
                </div>
              </div>

              {memberMode === "user" ? (
                <DualListBox
                  availableItems={availableUsers}
                  selectedItems={selectedUsers}
                  onSelectionChange={setSelectedUsers}
                  availableLabel={t("detail.members.available")}
                  selectedLabel={t("detail.members.selected")}
                  enableSearch
                />
              ) : (
                <>
                  <DualListBox
                    availableItems={availableDepts}
                    selectedItems={selectedDepts}
                    onSelectionChange={handleDeptSelectionChange}
                    availableLabel={t("detail.members.dept.available")}
                    selectedLabel={t("detail.members.dept.selected")}
                    enableSearch
                    renderItem={(item) => (
                      <div className="flex flex-col">
                        <span className="text-sm font-medium">{item.label}</span>
                        <span className="text-muted-foreground text-xs">{item.description}</span>
                      </div>
                    )}
                  />

                  {/* 현재 멤버 요약 */}
                  <div className="rounded-lg border bg-muted/30 p-4">
                    <p className="mb-2 text-sm font-semibold">{t("detail.members.summary.count", { count: selectedUsers.length })}</p>
                    {selectedUsers.length === 0 ? (
                      <p className="text-muted-foreground text-sm">{t("detail.members.empty")}</p>
                    ) : (
                      <div className="flex flex-wrap gap-1.5">
                        {selectedUsers.map((user) => (
                          <span key={user.id} className="inline-flex items-center gap-1 rounded-full bg-background border px-2.5 py-0.5 text-xs">
                            {user.label}
                            <button
                              onClick={() => setSelectedUsers((prev) => prev.filter((u) => u.id !== user.id))}
                              className="ml-0.5 text-muted-foreground hover:text-destructive"
                            >
                              x
                            </button>
                          </span>
                        ))}
                      </div>
                    )}
                  </div>
                </>
              )}
            </>
          )}

          {activeTab === "permissions" && (
            <>
              <div className="flex items-center justify-between">
                <div>
                  <h2 className="text-xl font-semibold">{t("detail.permissions.title")}</h2>
                  <p className="text-muted-foreground text-sm">{t("detail.permissions.description")}</p>
                </div>
                <Button onClick={handleSavePermissions} disabled={isSavingPermissions} className="gap-2">
                  <Save className="h-4 w-4" />
                  {isSavingPermissions ? t("detail.permissions.saving") : t("detail.permissions.save")}
                </Button>
              </div>

              <MenuPermissionsTable
                permissions={menuPermissions}
                onPermissionsChange={setMenuPermissions}
                roleGroup={roleGroup}
              />
            </>
          )}
        </div>
      </div>

      {/* Scroll to Top 버튼 (모바일/태블릿 전용) */}
      <ScrollToTop />
    </div>
  );
}
