<template>
  <div class="admin--sales-form">
    <form @submit.prevent="handleSubmit" class="admin--form">
      <!-- 전시장 -->
      <div class="admin--form-group">
        <label class="admin--form-label">전시장 <span class="admin--required">*</span></label>
        <select v-model="formData.showroom_id" class="admin--form-select" required>
          <option value="">전시장을 선택하세요</option>
          <option v-for="showroom in showrooms" :key="showroom.id" :value="showroom.id">
            {{ showroom.name }}
          </option>
        </select>
      </div>

      <!-- 영업팀 -->
      <div class="admin--form-group">
        <label class="admin--form-label">영업팀 <span class="admin--required">*</span></label>
        <select v-model="formData.team_id" class="admin--form-select" required>
          <option value="">영업팀을 선택하세요</option>
          <option v-for="team in teams" :key="team.id" :value="team.id">
            {{ team.name }}
          </option>
        </select>
      </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>
        <select v-model.number="formData.position" class="admin--form-select" required>
          <option value="">직책을 선택하세요</option>
          <option :value="10">팀장</option>
          <option :value="15">마스터</option>
          <option :value="20">차장</option>
          <option :value="30">과장</option>
          <option :value="40">대리</option>
          <option :value="60">사원</option>
        </select>
      </div>

      <!-- 대표번호 -->
      <div class="admin--form-group">
        <label class="admin--form-label">대표번호 <span class="admin--required">*</span></label>
        <input
          v-model="formData.main_phone"
          type="tel"
          class="admin--form-input"
          placeholder="02-1234-5678"
          required
        >
      </div>

      <!-- 직통번호 -->
      <div class="admin--form-group">
        <label class="admin--form-label">직통번호</label>
        <input
          v-model="formData.direct_phone"
          type="tel"
          class="admin--form-input"
          placeholder="02-1234-5679"
        >
      </div>

      <!-- 핸드폰 -->
      <div class="admin--form-group">
        <label class="admin--form-label">핸드폰</label>
        <input
          v-model="formData.mobile"
          type="tel"
          class="admin--form-input"
          placeholder="010-1234-5678"
        >
      </div>

      <!-- 이메일 -->
      <div class="admin--form-group">
        <label class="admin--form-label">이메일</label>
        <input
          v-model="formData.email"
          type="email"
          class="admin--form-input"
          placeholder="email@example.com"
        >
      </div>

      <!-- 사진 -->
      <div class="admin--form-group">
        <label class="admin--form-label">사진</label>
        <input
          type="file"
          accept="image/*"
          class="admin--form-file"
          @change="handlePhotoUpload"
        >
        <div v-if="photoPreview" class="admin--image-preview">
          <img :src="photoPreview" alt="미리보기">
          <button type="button" class="admin--btn-remove-image" @click="removePhoto">
            삭제
          </button>
        </div>
      </div>

      <!-- SACT -->
      <div class="admin--form-group">
        <label class="admin--form-label">SACT</label>
        <div class="admin--radio-group">
          <label class="admin--radio-label">
            <input v-model="formData.is_sact" type="radio" :value="true" name="is_sact">
            <span>예</span>
          </label>
          <label class="admin--radio-label">
            <input v-model="formData.is_sact" type="radio" :value="false" name="is_sact">
            <span>아니오</span>
          </label>
        </div>
      </div>

      <!-- TOP30 -->
      <div class="admin--form-group">
        <label class="admin--form-label">TOP30</label>
        <div class="admin--radio-group">
          <label class="admin--radio-label">
            <input v-model="formData.is_top30" type="radio" :value="true" name="is_top30">
            <span>예</span>
          </label>
          <label class="admin--radio-label">
            <input v-model="formData.is_top30" type="radio" :value="false" name="is_top30">
            <span>아니오</span>
          </label>
        </div>
      </div>

      <!-- 노출순서 -->
      <div class="admin--form-group">
        <label class="admin--form-label">노출순서</label>
        <input
          v-model.number="formData.display_order"
          type="number"
          class="admin--form-input"
          placeholder="숫자만 입력"
          min="0"
        >
        <p class="admin--form-help">숫자가 작을수록 먼저 노출됩니다.</p>
      </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, onMounted } from 'vue'
import { useRouter } from 'vue-router'

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

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

const isSaving = ref(false)
const successMessage = ref('')
const errorMessage = ref('')
const photoPreview = ref(null)
const photoFile = ref(null)

const showrooms = ref([])

// 영업팀 수동 리스트 (0번째는 마스터팀)
const teams = ref([
  { id: 0, name: '마스터팀' },
  { id: 1, name: '1팀' },
  { id: 2, name: '2팀' },
  { id: 3, name: '3팀' },
  { id: 4, name: '4팀' },
  { id: 5, name: '5팀' },
  { id: 6, name: '6팀' },
  { id: 7, name: '7팀' },
  { id: 8, name: '8팀' },
  { id: 9, name: '9팀' },
  { id: 10, name: '10팀' }
])

const formData = ref({
  showroom_id: '',
  team_id: '',
  name: '',
  position: '',
  main_phone: '',
  direct_phone: '',
  mobile: '',
  email: '',
  photo_url: '',
  is_sact: false,
  is_top30: false,
  display_order: 0
})

// 필터 데이터 로드
const loadFilters = async () => {
  // 전시장 리스트 (지점 목록)
  const { data: branchData, error: branchError } = await get('/branch/list', { per_page: 1000 })
  console.log('[SalesCreate] 전시장(지점) API 응답:', { data: branchData, error: branchError })
  if (branchData?.success && branchData?.data) {
    showrooms.value = branchData.data.items || []
    console.log('[SalesCreate] 전시장(지점) 로드 성공')
  }
}

// 사진 업로드
const handlePhotoUpload = (event) => {
  const file = event.target.files[0]
  if (!file) return

  if (!file.type.startsWith('image/')) {
    alert('이미지 파일만 업로드 가능합니다.')
    return
  }

  photoFile.value = file

  const reader = new FileReader()
  reader.onload = (e) => {
    photoPreview.value = e.target.result
  }
  reader.readAsDataURL(file)
}

// 사진 삭제
const removePhoto = () => {
  photoPreview.value = null
  photoFile.value = null
  formData.value.photo_url = ''
}

// 폼 제출
const handleSubmit = async () => {
  successMessage.value = ''
  errorMessage.value = ''

  if (!formData.value.showroom_id || !formData.value.team_id) {
    errorMessage.value = '전시장, 영업팀을 선택하세요.'
    return
  }

  if (!formData.value.name) {
    errorMessage.value = '이름을 입력하세요.'
    return
  }

  isSaving.value = true

  try {
    let photoUrl = formData.value.photo_url

    // 사진 업로드
    if (photoFile.value) {
      const formDataImage = new FormData()
      formDataImage.append('file', photoFile.value)

      const { data: uploadData, error: uploadError } = await upload('/upload/staff-image', formDataImage)

      if (uploadError) {
        errorMessage.value = '사진 업로드에 실패했습니다.'
        isSaving.value = false
        return
      }

      photoUrl = uploadData.data?.url || uploadData.url
    }

    const submitData = {
      ...formData.value,
      photo_url: photoUrl
    }

    const { data, error } = await post('/staff/sales', submitData)

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

const goToList = () => {
  router.push('/admin/staff/sales')
}

onMounted(() => {
  loadFilters()
})
</script>
