<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 ProjectFormDialog from '../components/ProjectFormDialog.vue';
import { projectService } from '../project.service';
import { PROJECT_STATUS } from '@/core/constants/app.constants';
import type { Project } from '../project.types';

const toast = useToast();

const projects = ref<Project[]>([]);
const loading = ref(false);
const dialogVisible = ref(false);
const dialogLoading = ref(false);
const selectedProject = ref<Partial<Project> | null>(null);

async function loadProjects() {
  loading.value = true;
  try {
    const { data } = await projectService.getAll();
    projects.value = (data as any).items ?? data;
  } catch {
    toast.add({ severity: 'error', summary: '오류', detail: '프로젝트 목록 로드 실패', life: 5000 });
  } finally {
    loading.value = false;
  }
}

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

function openEdit(project: Project) {
  selectedProject.value = { ...project };
  dialogVisible.value = true;
}

async function onSave(data: Partial<Project>) {
  dialogLoading.value = true;
  try {
    if (data.id) {
      await projectService.update(data.id, data);
      toast.add({ severity: 'success', summary: '성공', detail: '프로젝트가 수정되었습니다.', life: 3000 });
    } else {
      await projectService.create(data);
      toast.add({ severity: 'success', summary: '성공', detail: '프로젝트가 등록되었습니다.', life: 3000 });
    }
    dialogVisible.value = false;
    await loadProjects();
  } catch {
    toast.add({ severity: 'error', summary: '오류', detail: '저장 실패', life: 5000 });
  } finally {
    dialogLoading.value = false;
  }
}

function statusSeverity(status: string) {
  return (PROJECT_STATUS as Record<string, any>)[status]?.severity ?? 'secondary';
}
function statusLabel(status: string) {
  return (PROJECT_STATUS as Record<string, any>)[status]?.label ?? status;
}

function typeTag(type: string) {
  const map: Record<string, string> = { EPC: 'info', PMC: 'warn', FEED: 'success', OTHER: 'secondary' };
  return map[type] ?? 'secondary';
}

onMounted(loadProjects);
</script>

<template>
  <div class="project-list-view">
    <BasePageHeader title="프로젝트 목록" subtitle="프로젝트 조회 및 관리">
      <template #actions>
        <Button label="등록" icon="pi pi-plus" @click="openCreate" />
      </template>
    </BasePageHeader>

    <BaseCrudTable
      :value="projects"
      :loading="loading"
      :globalFilterFields="['projectCode', 'name', 'projectType', 'status']"
      @row-select="openEdit"
    >
      <Column field="projectCode" header="프로젝트코드" sortable style="min-width: 140px" />
      <Column field="name" header="이름" sortable style="min-width: 180px" />
      <Column field="projectType" header="유형" sortable style="min-width: 90px">
        <template #body="{ data }">
          <Tag :value="data.projectType" :severity="typeTag(data.projectType)" />
        </template>
      </Column>
      <Column field="status" header="상태" sortable style="min-width: 90px">
        <template #body="{ data }">
          <Tag :value="statusLabel(data.status)" :severity="statusSeverity(data.status)" />
        </template>
      </Column>
      <Column field="pmUserId" header="PM" sortable style="min-width: 100px" />
      <Column header="기간" style="min-width: 180px">
        <template #body="{ data }">
          {{ data.startDate ?? '-' }} ~ {{ data.endDate ?? '-' }}
        </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>

    <ProjectFormDialog
      :visible="dialogVisible"
      :project="selectedProject"
      :loading="dialogLoading"
      @update:visible="dialogVisible = $event"
      @save="onSave"
    />
  </div>
</template>
