<template>
  <div class="admin--news-form">
    <form @submit.prevent="handleSubmit" class="admin--form">
      <!-- 댓글허용 -->
      <div class="admin--form-group">
        <label class="admin--form-label">댓글허용</label>
        <div class="admin--checkbox-group">
          <label class="admin--checkbox-label">
            <input v-model="formData.allow_comment" type="checkbox">
            <span>댓글 허용</span>
          </label>
        </div>
      </div>

      <!-- 공지 -->
      <div class="admin--form-group">
        <label class="admin--form-label">공지</label>
        <div class="admin--checkbox-group">
          <label class="admin--checkbox-label">
            <input v-model="formData.is_notice" type="checkbox">
            <span>공지글로 등록</span>
          </label>
        </div>
      </div>

      <!-- 이름 -->
      <div class="admin--form-group">
        <label class="admin--form-label">이름 <span class="admin--required">*</span></label>
        <input
          v-model="formData.name"
          type="text"
          class="admin--form-input"
          placeholder="이름을 입력하세요"
          required
        >
      </div>

      <!-- 이메일 -->
      <div class="admin--form-group">
        <label class="admin--form-label">이메일 <span class="admin--required">*</span></label>
        <input
          v-model="formData.email"
          type="email"
          class="admin--form-input"
          placeholder="이메일을 입력하세요"
          required
        >
      </div>

      <!-- URL -->
      <div class="admin--form-group">
        <label class="admin--form-label">URL</label>
        <input
          v-model="formData.url"
          type="url"
          class="admin--form-input"
          placeholder="https://example.com"
        >
      </div>

      <!-- 제목 -->
      <div class="admin--form-group">
        <label class="admin--form-label">제목 <span class="admin--required">*</span></label>
        <input
          v-model="formData.title"
          type="text"
          class="admin--form-input"
          placeholder="제목을 입력하세요"
          required
        >
      </div>

      <!-- 내용 -->
      <div class="admin--form-group">
        <label class="admin--form-label">내용 <span class="admin--required">*</span></label>
        <SunEditor v-model="formData.content" />
      </div>

      <!-- 파일첨부 -->
      <div class="admin--form-group">
        <label class="admin--form-label">파일첨부</label>
        <div class="admin--file-list">
          <div v-for="(file, index) in attachedFiles" :key="index" class="admin--file-item">
            <span class="admin--file-name">{{ file.name }}</span>
            <span class="admin--file-size">({{ formatFileSize(file.size) }})</span>
            <button type="button" class="admin--btn-remove-file" @click="removeFile(index)">
              삭제
            </button>
          </div>
        </div>
        <input
          ref="fileInput"
          type="file"
          multiple
          class="admin--form-file-hidden"
          @change="handleFileAdd"
        >
        <button type="button" class="admin--btn admin--btn-secondary" @click="triggerFileInput">
          파일 추가
        </button>
      </div>

      <!-- 버튼 영역 -->
      <div class="admin--form-actions">
        <button
          type="submit"
          class="admin--btn admin--btn-primary"
          :disabled="isSaving"
        >
          {{ isSaving ? '저장 중...' : '확인' }}
        </button>
        <button
          type="button"
          class="admin--btn admin--btn-secondary"
          @click="goToList"
        >
          목록
        </button>
      </div>

      <!-- 성공/에러 메시지 -->
      <div v-if="successMessage" class="admin--alert admin--alert-success">
        {{ successMessage }}
      </div>
      <div v-if="errorMessage" class="admin--alert admin--alert-error">
        {{ errorMessage }}
      </div>
    </form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import SunEditor from '~/components/admin/SunEditor.vue'

definePageMeta({
  layout: 'admin',
  middleware: ['auth']
})

const router = useRouter()
const { post, upload } = useApi()

const isSaving = ref(false)
const successMessage = ref('')
const errorMessage = ref('')
const attachedFiles = ref([])
const fileInput = ref(null)

const formData = ref({
  allow_comment: false,
  is_notice: false,
  name: '고진',
  email: 'admin@admin.kr',
  url: '',
  title: '',
  content: '',
  file_urls: []
})

const triggerFileInput = () => {
  fileInput.value?.click()
}

const handleFileAdd = (event) => {
  const files = Array.from(event.target.files)
  attachedFiles.value.push(...files)
  event.target.value = ''
}

const removeFile = (index) => {
  attachedFiles.value.splice(index, 1)
}

const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
}

const handleSubmit = async () => {
  successMessage.value = ''
  errorMessage.value = ''

  if (!formData.value.title) {
    errorMessage.value = '제목을 입력하세요.'
    return
  }

  if (!formData.value.content) {
    errorMessage.value = '내용을 입력하세요.'
    return
  }

  isSaving.value = true

  try {
    let fileUrls = []

    // 파일 업로드
    if (attachedFiles.value.length > 0) {
      for (const file of attachedFiles.value) {
        const formDataFile = new FormData()
        formDataFile.append('file', file)

        const { data: uploadData, error: uploadError } = await upload('/upload/news-file', formDataFile)

        if (uploadError) {
          errorMessage.value = `파일 업로드에 실패했습니다: ${file.name}`
          isSaving.value = false
          return
        }

        fileUrls.push({
          name: file.name,
          url: uploadData.data.url,
          size: file.size
        })
      }
    }

    // content에서 도메인 제거
    let contentToSave = formData.value.content
    if (contentToSave) {
      // http://도메인 또는 https://도메인 제거
      contentToSave = contentToSave.replace(/https?:\/\/[^\/]+/g, '')
    }

    const submitData = {
      ...formData.value,
      content: contentToSave,
      file_urls: fileUrls
    }

    const { data, error } = await post('/board/news', submitData)

    if (error) {
      errorMessage.value = error.message || '등록에 실패했습니다.'
    } else {
      successMessage.value = '뉴스가 등록되었습니다.'
      setTimeout(() => {
        router.push('/admin/board/news')
      }, 1000)
    }
  } catch (error) {
    errorMessage.value = '서버 오류가 발생했습니다.'
    console.error('Save error:', error)
  } finally {
    isSaving.value = false
  }
}

const goToList = () => {
  router.push('/admin/board/news')
}
</script>
