<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue';
import Column from 'primevue/column';
import Select from 'primevue/select';
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 TealUploadDialog from '../components/TealUploadDialog.vue';
import TealVersionSelect from '../components/TealVersionSelect.vue';
import { useTealStore } from '../teal.store';
import type { TealVersion } from '../teal.store';
import { projectService } from '@/modules/project/project.service';
import type { Project } from '@/modules/project/project.types';

const toast = useToast();
const tealStore = useTealStore();

const projects = ref<Project[]>([]);
const selectedProject = ref<Project | null>(null);
const selectedVersion = ref<TealVersion | null>(null);
const uploadDialogVisible = ref(false);
const uploadLoading = ref(false);
const disciplineFilter = ref<string | null>(null);

const disciplineOptions = [
  'Piping', 'Electrical', 'Instrument', 'Civil', 'Structural',
  'Mechanical', 'Process', 'HSE', 'QA/QC', 'Other',
].map((d) => ({ label: d, value: d }));

const filteredEntries = computed(() => {
  if (!disciplineFilter.value) return tealStore.entries;
  return tealStore.entries.filter(
    (e: any) => e.discipline === disciplineFilter.value,
  );
});

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

async function loadVersions() {
  if (!selectedProject.value) return;
  try {
    await tealStore.fetchVersions(selectedProject.value.id);
    selectedVersion.value = null;
  } catch {
    toast.add({ severity: 'error', summary: '오류', detail: 'TEAL 버전 목록 로드 실패', life: 5000 });
  }
}

async function loadEntries() {
  if (!selectedProject.value) return;
  try {
    await tealStore.fetchActive(selectedProject.value.id);
  } catch {
    toast.add({ severity: 'error', summary: '오류', detail: 'TEAL 항목 로드 실패', life: 5000 });
  }
}

async function onUpload(payload: { file: File; effectiveDate: string }) {
  if (!selectedProject.value) return;
  uploadLoading.value = true;
  try {
    await tealStore.upload(selectedProject.value.id, payload.file, payload.effectiveDate);
    toast.add({ severity: 'success', summary: '성공', detail: 'TEAL 파일이 업로드되었습니다.', life: 3000 });
    uploadDialogVisible.value = false;
    await loadEntries();
  } catch {
    toast.add({ severity: 'error', summary: '오류', detail: 'TEAL 업로드 실패', life: 5000 });
  } finally {
    uploadLoading.value = false;
  }
}

watch(selectedProject, () => {
  loadVersions();
  loadEntries();
});

watch(selectedVersion, () => {
  if (selectedProject.value) {
    loadEntries();
  }
});

onMounted(loadProjects);
</script>

<template>
  <div class="teal-list-view">
    <BasePageHeader title="TEAL 관리">
      <template #actions>
        <Button
          label="TEAL 업로드"
          icon="pi pi-upload"
          :disabled="!selectedProject"
          @click="uploadDialogVisible = true"
        />
      </template>
    </BasePageHeader>

    <!-- Top bar: selectors -->
    <div class="teal-list-view__toolbar">
      <div class="teal-list-view__selector">
        <label class="teal-list-view__label">프로젝트</label>
        <Select
          v-model="selectedProject"
          :options="projects"
          optionLabel="name"
          placeholder="프로젝트 선택"
          fluid
          style="min-width: 240px"
        />
      </div>
      <div class="teal-list-view__selector">
        <label class="teal-list-view__label">버전</label>
        <TealVersionSelect
          v-model="selectedVersion"
          :versions="tealStore.versions"
          :loading="tealStore.loading"
          style="min-width: 200px"
        />
      </div>
      <div class="teal-list-view__selector">
        <label class="teal-list-view__label">Discipline</label>
        <Select
          v-model="disciplineFilter"
          :options="disciplineOptions"
          optionLabel="label"
          optionValue="value"
          placeholder="전체"
          showClear
          fluid
          style="min-width: 160px"
        />
      </div>
    </div>

    <!-- DataTable -->
    <BaseCrudTable
      :value="filteredEntries"
      :loading="tealStore.loading"
      :globalFilterFields="['activityCode', 'activityName', 'discipline']"
      emptyMessage="프로젝트를 선택해 주세요."
    >
      <Column field="activityCode" header="Activity Code" sortable style="min-width: 160px" />
      <Column field="activityName" header="Activity Name" sortable style="min-width: 240px" />
      <Column field="canonicalWbsCode" header="WBS Code" sortable style="min-width: 160px">
        <template #body="{ data }">
          {{ (data as any).canonicalWbsCode ?? (data as any).wbsCode ?? '-' }}
        </template>
      </Column>
      <Column field="discipline" header="Discipline" sortable style="min-width: 120px" />
      <Column header="상태" style="min-width: 90px">
        <template #body="{ data }">
          <Tag
            :value="(data as any).isActive === false ? '비활성' : '활성'"
            :severity="(data as any).isActive === false ? 'secondary' : 'success'"
          />
        </template>
      </Column>
    </BaseCrudTable>

    <TealUploadDialog
      :visible="uploadDialogVisible"
      :loading="uploadLoading"
      @update:visible="uploadDialogVisible = $event"
      @upload="onUpload"
    />
  </div>
</template>

<style lang="scss" scoped>
@use '@/assets/styles/variables' as *;

.teal-list-view {
  &__toolbar {
    display: flex;
    align-items: flex-end;
    gap: $space-md;
    flex-wrap: wrap;
    margin-bottom: $space-lg;
  }

  &__selector {
    display: flex;
    flex-direction: column;
    gap: $space-xs;
  }

  &__label {
    font-size: $font-size-sm;
    font-weight: 600;
    color: $color-text-muted;
  }

  @media (max-width: $bp-mobile) {
    &__toolbar {
      flex-direction: column;
      align-items: stretch;
    }
  }
}
</style>
