<script setup>
import { ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { createSubject, updateSubject } from '@/api/subjectService.js'

// Create / edit dialog. `subject` prop null → create mode, object → edit.
// Owns the form, validation, save flow, and inline error display. Delete
// was spun out to SubjectDeleteDialog (delete flow is now row-triggered).
const props = defineProps({
  open: { type: Boolean, default: false },
  subject: { type: Object, default: null },
  colorOptions: { type: Array, required: true },
})
const emit = defineEmits(['close', 'saved'])

const { t } = useI18n()

const isCreateMode = ref(false)
const editingSubject = ref(null)
const editForm = ref({
  subject_name: '',
  enabled_flag: 'Y',
  primary_flag: 'N',
  calendar_color: '',
  sort_sequence: 0,
})
const isSaving = ref(false)
const isError = ref(false)
const errorMessage = ref('')

const blankForm = () => ({
  subject_name: '',
  enabled_flag: 'Y',
  primary_flag: 'N',
  calendar_color: '',
  sort_sequence: 0,
})

function resetForm() {
  editForm.value = blankForm()
}

function loadFromSubject(s) {
  isCreateMode.value = false
  editingSubject.value = s
  editForm.value = {
    subject_name: s.subject_name || '',
    enabled_flag: s.enabled_flag || 'Y',
    primary_flag: s.primary_flag || 'N',
    calendar_color: s.calendar_color || '',
    sort_sequence: s.sort_sequence ?? 0,
  }
}

function initCreate() {
  isCreateMode.value = true
  editingSubject.value = null
  resetForm()
}

function closeDialog() {
  isError.value = false
  errorMessage.value = ''
  resetForm()
  emit('close')
}

async function save() {
  if (!editForm.value.subject_name) {
    isError.value = true
    errorMessage.value = t('subject.validation.subjectNameRequired')
    return
  }

  isSaving.value = true
  isError.value = false
  errorMessage.value = ''

  try {
    const payload = {
      subject_name: editForm.value.subject_name,
      enabled_flag: editForm.value.enabled_flag,
      primary_flag: editForm.value.primary_flag,
      calendar_color: editForm.value.calendar_color,
      sort_sequence: editForm.value.sort_sequence,
    }

    let result
    if (isCreateMode.value) {
      result = await createSubject(payload)
    } else {
      if (!editingSubject.value?.subject_id) {
        throw new Error(t('common.messages.error.general'))
      }
      result = await updateSubject(editingSubject.value.subject_id, payload)
    }

    // closeDialog emits 'close' first; parent's close handler runs but
    // is idempotent. Then emit 'saved' so the parent can merge/unshift.
    closeDialog()
    emit('saved', result)
  } catch (error) {
    console.error('Subject save failed:', error)
    isError.value = true
    errorMessage.value = error?.message || t('common.messages.error.general')
  } finally {
    isSaving.value = false
  }
}

watch(
  () => [props.open, props.subject],
  ([isOpen, subject]) => {
    if (!isOpen) return
    isError.value = false
    errorMessage.value = ''
    if (subject) loadFromSubject(subject)
    else initCreate()
  },
  { immediate: true },
)
</script>

<template>
  <v-dialog :model-value="open" max-width="500px" @update:model-value="(v) => !v && closeDialog()">
    <v-card>
      <v-card-title>
        {{ isCreateMode ? t('subject.dialog.add') : t('subject.dialog.edit') }}
      </v-card-title>
      <v-card-text>
        <v-alert
          v-if="isError"
          type="error"
          variant="tonal"
          class="mb-4"
          closable
          @click:close="isError = false"
        >
          {{ errorMessage }}
        </v-alert>

        <v-form @submit.prevent="save">
          <v-container>
            <v-row>
              <v-col cols="12">
                <v-text-field
                  v-model="editForm.subject_name"
                  :label="t('subject.form.subject_name')"
                  required
                  variant="outlined"
                />
              </v-col>
              <v-col cols="6">
                <v-text-field
                  v-model.number="editForm.sort_sequence"
                  :label="t('subject.form.sort_sequence')"
                  type="number"
                  variant="outlined"
                />
              </v-col>
              <v-col cols="6">
                <v-select
                  v-model="editForm.calendar_color"
                  :label="t('subject.form.calendar_color')"
                  :items="colorOptions"
                  variant="outlined"
                  clearable
                >
                  <template v-slot:item="{ props, item }">
                    <v-list-item v-bind="props" :title="item.title">
                      <template v-slot:prepend>
                        <div
                          class="color-dot"
                          :style="{ backgroundColor: item.raw?.color || '#e0e0e0' }"
                        ></div>
                      </template>
                    </v-list-item>
                  </template>
                  <template v-slot:selection="{ item }">
                    <div class="d-flex align-center">
                      <div
                        class="color-dot"
                        :style="{ backgroundColor: item.raw?.color || '#e0e0e0' }"
                      ></div>
                      <span>{{ item.raw?.title || item.title }}</span>
                    </div>
                  </template>
                </v-select>
              </v-col>
              <v-col cols="6">
                <v-switch
                  v-model="editForm.enabled_flag"
                  :label="t('subject.form.enabled_flag')"
                  color="primary"
                  true-value="Y"
                  false-value="N"
                  inset
                />
              </v-col>
              <v-col cols="6">
                <v-switch
                  v-model="editForm.primary_flag"
                  :label="t('subject.form.primary_flag')"
                  color="primary"
                  true-value="Y"
                  false-value="N"
                  inset
                />
              </v-col>
            </v-row>
          </v-container>
        </v-form>
      </v-card-text>
      <v-card-actions>
        <v-spacer />
        <v-btn
          color="grey-darken-1"
          variant="text"
          :disabled="isSaving"
          @click="closeDialog"
        >
          {{ t('common.buttons.cancel') }}
        </v-btn>
        <v-btn
          :color="isCreateMode ? 'success' : 'primary'"
          variant="text"
          :loading="isSaving"
          :disabled="isSaving"
          @click="save"
        >
          {{ isCreateMode ? t('common.buttons.create') : t('common.buttons.save') }}
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<style scoped>
.color-dot {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  margin-right: 8px;
  border: 1px solid #ddd;
  display: inline-block;
  flex-shrink: 0;
}
</style>