<script setup>
import { ref, computed, onMounted } from 'vue';
import { useAuthStore } from '@/stores/Auth';
import { useRouter } from 'vue-router';

const router = useRouter();
const authStore = useAuthStore();

const info = ref({ regions: [] });
const region = ref('');
const selectedDistrictId = ref('');
const name = ref('');
const latitude = ref('');
const longitude = ref('');
const file = ref(null);

// Загружаем данные об областях и районах
onMounted(async () => {
  const { regions, error } = await authStore.fetchRegionsForSelect();
  if (error) {
    console.error(error);
    return;
  }
  // В regions уже лежит массив областей
  info.value.regions = regions;
});

const regions = computed(() => info.value.regions || []);
const filteredDistricts = computed(() => {
  const selected = regions.value.find(r => r.name === region.value);
  return selected?.districts || [];
});

const handleFileUpload = (event) => {
  const uploadedFile = event.target.files[0];
  if (uploadedFile) {
    file.value = uploadedFile;
    console.log('Файл выбран:', uploadedFile.name);
  }
};

const savePoint = async () => {
  const formData = new FormData();
  formData.append('name', name.value);
  formData.append('latitude', latitude.value);
  formData.append('longitude', longitude.value);
  formData.append('district_id', selectedDistrictId.value);
  formData.append('file', file.value);

  console.log('Данные, отправляемые на бэк:');
  for (const [key, val] of formData.entries()) {
    console.log(`${key}:`, key === 'file' ? val.name : val);
  }

  try {
    const {response, error} = await authStore.createPoint(formData);
    if (response) {
      alert('Точка успешно создана');
      router.push({name: 'point-list'});
    } else {
      console.error('Ошибка при создании точки:', error);
    }
  } catch (e) {
    console.error('Ошибка запроса:', e);
  }
};
</script>

<template>
  <div class="container py-4">
    <div class="row justify-content-center">
      <div class="col-md-8">
        <div class="card shadow-sm">
          <div class="card-body">
            <div class="mb-3 d-flex justify-content-between">
              <button class="btn btn-primary" @click="savePoint">Сохранить</button>
            </div>

            <div class="mb-3 d-flex align-items-center">
              <label class="w-160 flex-shrink-0">Область:</label>
              <select v-model="region" class="form-select">
                <option value="">Выберите область</option>
                <option v-for="r in regions" :key="r.id" :value="r.name">
                  {{ r.name }}
                </option>
              </select>
            </div>

            <div class="mb-3 d-flex align-items-center">
              <label class="w-160 flex-shrink-0">Район:</label>
              <select v-model="selectedDistrictId" class="form-select">
                <option value="">Выберите район</option>
                <option v-for="d in filteredDistricts" :key="d.id" :value="d.id">
                  {{ d.name }}
                </option>
              </select>
            </div>

            <div class="mb-3 d-flex align-items-center">
              <label class="w-160 flex-shrink-0">Название:</label>
              <input v-model="name" type="text" class="form-control"/>
            </div>

            <div class="mb-3 d-flex align-items-center">
              <label class="w-160 flex-shrink-0">Широта:</label>
              <input v-model="latitude" type="text" class="form-control"/>
            </div>

            <div class="mb-3 d-flex align-items-center">
              <label class="w-160 flex-shrink-0">Долгота:</label>
              <input v-model="longitude" type="text" class="form-control"/>
            </div>

            <div class="mb-3 d-flex align-items-center">
              <label class="w-160 flex-shrink-0">Загрузить GeoJSON:</label>
              <input
                  type="file"
                  accept=".json,application/geo+json"
                  class="form-control"
                  @change="handleFileUpload"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.w-160 {
  width: 160px;
}
</style>
