<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import {
  DatasetService,
  type ExternalDatasetItem,
} from "@/components/service/management/DatasetService";

const props = defineProps<{
  modelValue: boolean;
  projectId: number;
  refId?: number | null;
  regUserId?: string;
}>();
const emit = defineEmits<{
  (e: "update:modelValue", v: boolean): void;
  (e: "close"): void;
  (e: "saved"): void;
}>();

const visible = ref(props.modelValue);
watch(
  () => props.modelValue,
  (v) => (visible.value = v),
);
watch(visible, (v) => emit("update:modelValue", v));

const loading = ref(false);
const savingKey = ref<string | null>(null);
const errorMsg = ref("");
const rows = ref<ExternalDatasetItem[]>([]);
const searchKeyword = ref("");
const groupName = ref("");

// ✅ 성공 다이얼로그
const successVisible = ref(false);
const successMsg = ref("업로드되었습니다.");

// ✅ 행별 Description 입력값 저장: { [datasetName]: string }
const descMap = ref<Record<string, string>>({});

function unwrap<T = any>(res: any): T {
  return res && res.data ? res.data : res;
}

async function fetchList() {
  if (!props.projectId) return;
  loading.value = true;
  errorMsg.value = "";
  try {
    const res = await DatasetService.listExternal({
      ds_prj_idx: props.projectId,
      search_keyword: searchKeyword.value || undefined,
      grp_name: groupName.value || undefined,
    });
    const body = unwrap<any>(res);
    const arr: ExternalDatasetItem[] = Array.isArray(body?.data)
      ? body.data
      : Array.isArray(body)
        ? body
        : [];

    const kw = (searchKeyword.value || "").trim().toLowerCase();
    rows.value =
      kw.length === 0
        ? arr
        : arr.filter((r) =>
            String(r.ds_dataset_name || "")
              .toLowerCase()
              .includes(kw),
          );
  } catch {
    errorMsg.value = "외부 데이터셋 조회에 실패했습니다.";
  } finally {
    loading.value = false;
  }
}

function close() {
  visible.value = false;
  emit("close");
}

async function pick(item: ExternalDatasetItem) {
  savingKey.value = item.ds_dataset_name;
  errorMsg.value = "";
  try {
    await DatasetService.saveExternal({
      datasetName: item.ds_dataset_name,
      path: "", // UI에선 Base Path 제거, 백엔드가 불필요하면 빈 값 유지
      refId: props.refId ?? 0,
      refType: "DATASET",
      title: item.ds_dataset_name,
      description: (descMap.value[item.ds_dataset_name] || "").trim(), // ✅ 전달
      version: 1,
      regUserId: props.regUserId || "system",
      projectId: props.projectId,
    });

    // ✅ 성공 다이얼로그 오픈 & 입력값 정리
    successMsg.value = "업로드되었습니다.";
    successVisible.value = true;
    descMap.value[item.ds_dataset_name] = "";
  } catch (e: any) {
    errorMsg.value =
      e?.response?.data?.message ||
      "데이터셋 저장(다운로드→S3 업로드) 중 오류가 발생했습니다.";
  } finally {
    savingKey.value = null;
  }
}

function confirmSuccess() {
  successVisible.value = false;
  emit("saved"); // 부모가 목록 갱신
  close();
}

watch(() => props.projectId, fetchList);
onMounted(fetchList);
</script>

<template>
  <v-card rounded="lg" elevation="4">
    <v-card-title
      class="text-white text-h6 font-weight-bold"
      style="background: #1976d2"
    >
      External Datasets
    </v-card-title>

    <v-card-text class="pa-4">
      <div class="d-flex align-center ga-2 mb-3" style="flex-wrap: wrap">
        <v-text-field
          v-model="searchKeyword"
          label="데이터셋 이름 (Dataset Name)"
          density="compact"
          hide-details
          style="min-width: 240px; flex: 1 1 240px"
          @keyup.enter="fetchList"
          clearable
        />
        <v-text-field
          v-model="groupName"
          label="그룹 이름"
          density="compact"
          hide-details
          style="min-width: 240px; flex: 1 1 240px"
          @keyup.enter="fetchList"
          clearable
        />
        <v-btn color="primary" :loading="loading" @click="fetchList"
          >검색</v-btn
        >
      </div>

      <v-alert
        v-if="errorMsg"
        type="error"
        variant="tonal"
        density="compact"
        class="mb-2"
      >
        {{ errorMsg }}
      </v-alert>

      <v-table density="compact" fixed-header height="360">
        <thead>
          <tr>
            <th class="text-left">Dataset Name</th>
            <th class="text-left">Images</th>
            <th class="text-left">Label Type</th>
            <!-- ✅ Base Path 대신 Description -->
            <th class="text-left" style="min-width: 260px">Description</th>
            <th class="text-left">Action</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(r, i) in rows" :key="i">
            <td>{{ r.ds_dataset_name }}</td>
            <td>{{ r.ds_dataset_image_count }}</td>
            <td>{{ r.labelling_tool_kr }}</td>

            <!-- ✅ 행별 Description 입력 -->
            <td>
              <v-text-field
                v-model="descMap[r.ds_dataset_name]"
                placeholder="설명을 입력하세요"
                density="compact"
                hide-details
                clearable
              />
            </td>

            <td>
              <v-btn
                size="small"
                color="primary"
                :loading="savingKey === r.ds_dataset_name"
                :disabled="savingKey !== null"
                @click="pick(r)"
              >
                Select
              </v-btn>
            </td>
          </tr>
          <tr v-if="!loading && rows.length === 0">
            <td colspan="5" class="text-center text-medium-emphasis">
              No data
            </td>
          </tr>
        </tbody>
      </v-table>
    </v-card-text>

    <v-card-actions class="justify-end px-4 py-2">
      <v-btn variant="text" @click="close">Close</v-btn>
    </v-card-actions>
  </v-card>

  <!-- ✅ 성공 다이얼로그 -->
  <v-dialog v-model="successVisible" max-width="420">
    <v-card>
      <v-card-title
        class="text-h6 font-weight-bold text-center"
        style="background: #1976d2"
        >알림</v-card-title
      >
      <v-card-text class="pt-2 mt-4 text-center">{{ successMsg }}</v-card-text>
      <v-card-actions class="justify-end">
        <v-btn color="primary" @click="confirmSuccess">확인</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>
