<script setup lang="ts">
import { ref, onMounted } from 'vue';
import Column from 'primevue/column';
import Button from 'primevue/button';
import Tag from 'primevue/tag';
import { useToast } from 'primevue/usetoast';
import BasePageHeader from '@/core/components/BasePageHeader.vue';
import BaseCrudTable from '@/core/components/BaseCrudTable.vue';
import UserFormDialog from '../components/UserFormDialog.vue';
import { userService } from '../user.service';
import type { User } from '../user.types';

const toast = useToast();

const users = ref<User[]>([]);
const loading = ref(false);
const dialogVisible = ref(false);
const dialogLoading = ref(false);
const selectedUser = ref<Partial<User> | null>(null);

async function loadUsers() {
  loading.value = true;
  try {
    const { data } = await userService.getAll();
    users.value = (data as any).items ?? data;
  } catch {
    toast.add({ severity: 'error', summary: '오류', detail: '사용자 목록 로드 실패', life: 5000 });
  } finally {
    loading.value = false;
  }
}

function openCreate() {
  selectedUser.value = null;
  dialogVisible.value = true;
}

function openEdit(user: User) {
  selectedUser.value = { ...user };
  dialogVisible.value = true;
}

async function onSave(data: Partial<User>) {
  dialogLoading.value = true;
  try {
    if (data.id) {
      await userService.update(data.id, data);
      toast.add({ severity: 'success', summary: '성공', detail: '사용자 정보가 수정되었습니다.', life: 3000 });
    } else {
      toast.add({ severity: 'info', summary: '안내', detail: '사용자 등록은 Excel 업로드를 이용해주세요.', life: 5000 });
    }
    dialogVisible.value = false;
    await loadUsers();
  } catch {
    toast.add({ severity: 'error', summary: '오류', detail: '저장 실패', life: 5000 });
  } finally {
    dialogLoading.value = false;
  }
}

function roleSeverity(role: string): string {
  const map: Record<string, string> = { SA: 'danger', PM: 'warn', PCM: 'info', DL: 'success', PTK: 'secondary', USER: 'contrast' };
  return map[role] ?? 'secondary';
}

onMounted(loadUsers);
</script>

<template>
  <div class="user-list-view">
    <BasePageHeader title="사용자 관리" subtitle="시스템 사용자 목록 및 역할 관리">
      <template #actions>
        <Button label="등록" icon="pi pi-plus" @click="openCreate" />
      </template>
    </BasePageHeader>

    <BaseCrudTable
      :value="users"
      :loading="loading"
      :globalFilterFields="['fullName', 'email', 'employeeId', 'department', 'discipline']"
      @row-select="openEdit"
    >
      <Column field="fullName" header="이름" sortable style="min-width: 120px" />
      <Column field="email" header="이메일" sortable style="min-width: 180px" />
      <Column field="employeeId" header="사번" sortable style="min-width: 100px" />
      <Column field="department" header="부서" sortable style="min-width: 120px" />
      <Column field="discipline" header="Discipline" sortable style="min-width: 120px" />
      <Column field="roles" header="역할" style="min-width: 140px">
        <template #body="{ data }">
          <div style="display: flex; gap: 4px; flex-wrap: wrap;">
            <Tag v-for="role in data.roles" :key="role" :value="role" :severity="roleSeverity(role)" />
          </div>
        </template>
      </Column>
      <Column field="isActive" header="상태" style="min-width: 80px">
        <template #body="{ data }">
          <Tag :value="data.isActive ? '활성' : '비활성'" :severity="data.isActive ? 'success' : 'secondary'" />
        </template>
      </Column>
      <Column header="" style="width: 80px">
        <template #body="{ data }">
          <Button icon="pi pi-pencil" text rounded severity="info" @click="openEdit(data)" />
        </template>
      </Column>
    </BaseCrudTable>

    <UserFormDialog
      :visible="dialogVisible"
      :user="selectedUser"
      :loading="dialogLoading"
      @update:visible="dialogVisible = $event"
      @save="onSave"
    />
  </div>
</template>
