<script setup lang="ts">
import { onMounted, onBeforeUnmount, ref, computed } from "vue";
import { useRouter } from "vue-router";
import { useAutoflowStore } from "@/stores/autoflowStore";

import type {
  UiProject,
  ApiProject,
  Permission,
} from "@/components/models/project/Project";
import { ProjectService } from "@/components/service/project/projectService";
import { UserManagerService } from "@/components/service/management/userManagerService";
import { storage } from "@/utils/storage.js";

/** ===== 상수 & 기본 권한 ===== */
const DEFAULT_PERMISSIONS: Permission[] = [
  "CREATE",
  "READ",
  "UPDATE",
  "DELETE",
];

/** ===== 라우터 & 스토어 ===== */
const router = useRouter();
const autoflowStore = useAutoflowStore();

/** ===== 상태 ===== */
const dialog = ref(false);
const contextMenu = ref(false);
const menuX = ref(0);
const menuY = ref(0);
const selectedIndex = ref<number | null>(null);

const projects = ref<UiProject[]>([]);
type UserOption = { id: number | string; username: string };
const userOptions = ref<UserOption[]>([]);
const modalMode = ref<"create" | "edit">("create");
const editingProjectId = ref<number | null>(null);

const form = ref({
  prjCd: "",
  prjNm: "",
  prjDesc: "",
  selectedUsers: [] as string[],
});
/** ===== 서버 응답 타입 ===== */
const roles = ref<string[]>([]);
const refreshRoles = () => {
  const auth = storage.getAuth?.() ?? storage.get?.("vpp-Auth") ?? null;
  const r = auth?.userInfo?.roles ?? auth?.roles ?? [];
  roles.value = Array.isArray(r) ? r : [];
};
const isAdmin = computed(() => roles.value.includes("ROLE_ADMIN"));

/** ===== 서버 응답 타입 ===== */
interface ProjectSearchResponseItem {
  id: number;
  prjNm: string;
  prjDesc: string;
  prjStartDt?: string;
  regUserId?: string; // 화면의 "생성자"에 그대로 표시(콤마 구분 username들)
}
interface UserResponseItem {
  id: number | string;
  username: string;
}

/** ===== 유틸 ===== */
const buildApiProjectPayload = (): ApiProject => {
  const today = new Date().toISOString().slice(0, 10);
  const nowIso = new Date().toISOString();
  const namesCsv = form.value.selectedUsers.join(",");

  return {
    id: modalMode.value === "edit" ? editingProjectId.value! : null,
    prjCd: form.value.prjCd,
    prjNm: form.value.prjNm,
    prjDesc: form.value.prjDesc,
    prjStartDt: today,
    prjEndDt: today,
    delYn: "N",
    regDate: nowIso,
    regUserId: namesCsv,
    regUserNm: namesCsv,
    modDate: nowIso,
    modUserId: namesCsv,
    modUserNm: namesCsv,
  };
};

const resetForm = () => {
  form.value.prjCd = `PRJ${Date.now()}`;
  form.value.prjNm = "";
  form.value.prjDesc = "";
  form.value.selectedUsers = [];
};

const loadProjects = async () => {
  try {
    const { data } = await ProjectService.search();
    const rawList = data as ProjectSearchResponseItem[];
    projects.value = rawList.map((p) => ({
      id: p.id,
      title: p.prjNm,
      creator: p.regUserId ?? "",
      date: p.prjStartDt ?? "",
      description: p.prjDesc,
    }));
  } catch (e) {
    console.error("프로젝트 조회 실패:", e);
  }
};

const loadUsers = async () => {
  try {
    const { data } = await UserManagerService.getAll();
    const raw = data as UserResponseItem[];
    userOptions.value = raw.map((u) => ({ id: u.id, username: u.username }));
  } catch (e) {
    console.error("사용자 조회 실패:", e);
  }
};

const openContextMenu = (event: MouseEvent, index: number) => {
  event.preventDefault();
  selectedIndex.value = index;
  menuX.value = event.pageX;
  menuY.value = event.pageY;
  contextMenu.value = true;
};

const closeDialog = () => {
  dialog.value = false;
  contextMenu.value = false;
  selectedIndex.value = null;
};

const selectProject = (index: number) => {
  const selected = projects.value[index];
  autoflowStore.setProjectId(selected.id);
  autoflowStore.setProjectName(selected.title);
  router.push("/home");
};

/** ===== 프로젝트 저장 & 권한 부여 ===== */
const grantDefaultPermissions = async (
  projectId: number,
  usernames: string[],
) => {
  if (!usernames?.length) return;

  const nameSet = new Set(usernames);
  const numericIds = userOptions.value
    .filter((u) => nameSet.has(u.username))
    .map((u) => Number(u.id))
    .filter((n) => Number.isFinite(n));

  await Promise.all(
    numericIds.map((uid) =>
      ProjectService.projectAuthority(projectId, {
        projectId,
        userId: uid, // number로 보장
        permissions: DEFAULT_PERMISSIONS,
      }),
    ),
  );
};

const saveProject = async () => {
  if (!isAdmin.value) {
    alert("권한이 없습니다. (ROLE_ADMIN 전용)");
    return;
  }

  const payload = buildApiProjectPayload();

  try {
    let projectId: number;

    if (modalMode.value === "create") {
      const createRes = await ProjectService.add(payload);
      projectId = createRes.data.id;
    } else {
      await ProjectService.update(editingProjectId.value!, payload);
      projectId = editingProjectId.value!;
    }

    await grantDefaultPermissions(projectId, form.value.selectedUsers);
    await loadProjects();
    closeDialog();
  } catch (error: any) {
    console.error(`${modalMode.value} 실패:`, error?.response?.data || error);
    alert(error?.response?.data?.message || "저장 실패");
  }
};

const deleteProject = async () => {
  try {
    if (selectedIndex.value === null) return;
    const target = projects.value[selectedIndex.value];

    await ProjectService.delete(target.id);
    await loadProjects();
  } catch (e: any) {
    console.error("삭제 실패:", e?.response?.status, e?.response?.data || e);
    alert("삭제 실패: " + (e?.response?.data?.message || e.message || ""));
  } finally {
    contextMenu.value = false;
  }
};

// 프로젝트 권한있을 때
// const deleteProject = async (): Promise<void> => {
//   try {
//     if (selectedIndex.value === null) return;
//     const target = projects.value[selectedIndex.value];
//     const projectId = target.id;

//     // 1) 프로젝트에 연결된 username들 뽑기
//     const usernames = (target.creator || "")
//       .split(",")
//       .map((s) => s.trim())
//       .filter(Boolean);

//     // 2) username -> userId 매핑
//     if (usernames.length) {
//       const ids = userOptions.value
//         .filter((u) => usernames.includes(u.username))
//         .map((u) => u.id);

//       // 3) 각 사용자 권한/매핑 제거
//       await Promise.all(
//         ids.map((uid) => ProjectService.deleteProjectAuthority(projectId, uid)),
//       );
//     }

//     // 4) 마지막에 프로젝트 삭제
//     await ProjectService.delete(projectId);

//     await loadProjects();
//   } catch (e: any) {
//     console.error("삭제 실패:", e?.response?.status, e?.response?.data || e);
//     alert("삭제 실패: " + (e?.response?.data?.message || e.message || ""));
//   } finally {
//     contextMenu.value = false;
//   }
// };

const onAddProject = () => {
  if (!isAdmin.value) {
    alert("권한이 없습니다. (ROLE_ADMIN 전용)");
    return;
  }
  modalMode.value = "create";
  editingProjectId.value = null;
  resetForm();
  dialog.value = true;
};

const modifyProject = () => {
  contextMenu.value = false;
  if (selectedIndex.value === null) return;

  const selected = projects.value[selectedIndex.value];
  modalMode.value = "edit";
  editingProjectId.value = selected.id;

  form.value.prjCd = selected.title;
  form.value.prjNm = selected.title;
  form.value.prjDesc = selected.description;
  form.value.selectedUsers =
    selected.creator
      ?.split(",")
      .map((s) => s.trim())
      .filter(Boolean) ?? [];

  dialog.value = true;
};

/** ===== 라이프사이클 ===== */
const onStorage = (e: StorageEvent) => {
  if (!e.key || /auth|vpp-Auth/i.test(e.key)) refreshRoles();
};

onMounted(async () => {
  refreshRoles();
  await Promise.all([loadProjects(), loadUsers()]);
  window.addEventListener("storage", onStorage);
});

onBeforeUnmount(() => {
  window.removeEventListener("storage", onStorage);
});
</script>

<template>
  <v-container class="mt-12" style="max-width: 1600px">
    <v-row class="mb-6" align="center" justify="space-between">
      <v-col cols="auto">
        <h2 class="font-weight-bold text-h5">Project Selection</h2>
      </v-col>

      <v-col cols="auto">
        <!-- ADMIN만 노출 -->
        <v-btn
          v-show="isAdmin"
          color="secondary"
          variant="flat"
          class="text-white font-weight-bold"
          @click="onAddProject"
        >
          <v-icon left icon="mdi-plus" size="20" />
          Create Project
        </v-btn>
      </v-col>
    </v-row>

    <v-row dense>
      <v-col
        v-for="(project, index) in projects"
        :key="index"
        cols="12"
        sm="6"
        md="6"
        lg="6"
        class="d-flex"
      >
        <v-card
          class="pa-4 flex-grow-1 d-flex flex-column"
          color="primary"
          variant="elevated"
          elevation="6"
          rounded="lg"
          @click="selectProject(index)"
          @contextmenu.prevent="(e) => openContextMenu(e, index)"
        >
          <v-card-title class="d-flex align-center">
            <v-icon color="#6EC1E4" icon="mdi-file" start size="18" />
            <h4>{{ project.title }}</h4>
          </v-card-title>

          <v-card-subtitle
            class="text-white text-caption d-flex justify-space-between"
          >
            <span>Select Users: {{ project.creator }}</span>
            <span>등록일: {{ project.date }}</span>
          </v-card-subtitle>

          <v-card-text
            class="text-white mt-3 text-body-2 flex-grow-1"
            style="white-space: normal"
          >
            {{ project.description }}
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>

    <v-menu
      v-model="contextMenu"
      absolute
      :style="{ top: menuY + 'px', left: menuX + 'px' }"
      max-width="180"
      width="130"
    >
      <v-list>
        <v-list-item @click="modifyProject">
          <v-list-item-icon
            ><v-icon>mdi-square-edit-outline</v-icon></v-list-item-icon
          >
          <v-list-item-title>Modify</v-list-item-title>
        </v-list-item>
        <v-list-item @click="deleteProject">
          <v-list-item-icon><v-icon>mdi-delete</v-icon></v-list-item-icon>
          <v-list-item-title>Delete</v-list-item-title>
        </v-list-item>
      </v-list>
    </v-menu>

    <v-dialog v-model="dialog" max-width="500">
      <v-card>
        <v-card-title class="headline">
          {{ modalMode === "create" ? "Create Project" : "Modify Project" }}
        </v-card-title>

        <v-card-text>
          <v-form>
            <v-text-field label="Project Name" v-model="form.prjNm" required />
            <v-textarea
              label="Description"
              v-model="form.prjDesc"
              rows="3"
              required
            />
            <v-select
              label="Select Users"
              v-model="form.selectedUsers"
              :items="userOptions"
              item-title="username"
              item-value="username"
              multiple
              chips
              closable-chips
            />
          </v-form>
        </v-card-text>

        <v-card-actions>
          <v-spacer />
          <v-btn text @click="closeDialog">Cancel</v-btn>
          <v-btn color="primary" @click="saveProject">
            {{ modalMode === "create" ? "Create" : "Save" }}
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-container>
</template>

<style scoped></style>
