<script setup lang="ts">
import { ref, watch } from 'vue';
import FileUpload from 'primevue/fileupload';
import DatePicker from 'primevue/datepicker';
import BaseFormDialog from '@/core/components/BaseFormDialog.vue';

const props = defineProps<{
  visible: boolean;
  loading?: boolean;
}>();

const emit = defineEmits<{
  'update:visible': [value: boolean];
  upload: [payload: { file: File; effectiveDate: string }];
}>();

const selectedFile = ref<File | null>(null);
const effectiveDate = ref<Date | null>(null);

watch(
  () => props.visible,
  (v) => {
    if (v) {
      selectedFile.value = null;
      effectiveDate.value = null;
    }
  },
);

function onFileSelect(event: any) {
  const files = event.files ?? event;
  if (Array.isArray(files) && files.length > 0) {
    selectedFile.value = files[0];
  }
}

function formatDate(d: Date): string {
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${y}-${m}-${day}`;
}

function onSubmit() {
  if (!selectedFile.value || !effectiveDate.value) return;
  emit('upload', {
    file: selectedFile.value,
    effectiveDate: formatDate(effectiveDate.value),
  });
}
</script>

<template>
  <BaseFormDialog
    :visible="visible"
    title="TEAL 업로드"
    width="580px"
    :loading="loading"
    submitLabel="업로드"
    @update:visible="emit('update:visible', $event)"
    @submit="onSubmit"
  >
    <div class="form-grid">
      <div class="col-12">
        <div class="form-field">
          <label class="form-field__label form-field__label--required">TEAL 파일</label>
          <FileUpload
            mode="basic"
            accept=".xls,.xlsx,.csv"
            :maxFileSize="10000000"
            chooseLabel="파일 선택"
            :auto="false"
            @select="onFileSelect"
          />
          <small v-if="selectedFile" class="form-field__hint">
            {{ selectedFile.name }}
          </small>
        </div>
      </div>
      <div class="col-12">
        <div class="form-field">
          <label class="form-field__label form-field__label--required">적용일</label>
          <DatePicker
            v-model="effectiveDate"
            dateFormat="yy-mm-dd"
            placeholder="적용일 선택"
            fluid
          />
        </div>
      </div>
    </div>
  </BaseFormDialog>
</template>
