<template>
  <Card class="w-full md:w-1/2">
    <template #title>Add New Bullet</template>
    <template #content>
      <div class="w-full">
        <label>Manufacturer</label>
        <Dropdown :options="manufacturers" option-label="name" option-value="id" v-model="bullet.manufacturer_id"
                  class="w-full" />
      </div>
      <div class="m-5" v-if="bullet.manufacturer_id === '-- Add --'">
        <div class="w-full m-1">
          <label>Manufacturer Name</label>
          <div class="w-full">
            <InputText v-model="add.name" class="w-full" />
          </div>
        </div>
        <div class="w-full m-1">
          <label>Manufacturer Url</label>
          <div class="w-full">
            <InputText v-model="add.url" class="w-full" />
          </div>
        </div>
      </div>
      <div class="w-full mt-3">
        <label>Bullet Name</label>
        <InputText v-model="bullet.name" class="w-full" />
      </div>
      <div class="w-full mt-3">
        <label>Bullet Diameter</label>
        <InputNumber v-model="bullet.diameter" prefix="." :min="0" :max="999" class="w-full" />
      </div>
      <div class="w-full mt-3">
        <label>Grain Weight</label>
        <InputNumber v-model="bullet.weight" suffix=" gr" :min="0" :max="1000" class="w-full" />
      </div>
      <div class="w-full mt-3">
        <label>Picture</label>
        <FileUpload v-model="file" mode="basic" @select="fileSelected" customUpload />
      </div>
    </template>
    <template #footer>
      <div class="mt-3">
        <Button :loading="loading" @click="create" label="Add" :icon="icons.add" />
      </div>
    </template>
  </Card>
</template>
<script lang="ts" setup>
import { defineAsyncComponent, ref } from 'vue'
import axios, { AxiosError } from 'axios'
import { Manufacturer } from '../../types/manufacturer'
import { Response } from '../../types/Response'
import { FileUploadSelectEvent } from 'primevue/fileupload'
import { Bullet } from '../../types/bullet'
import { ToastMessageOptions } from 'primevue/toast'
import { useToast } from 'primevue/usetoast'
import { useRouter } from 'vue-router'
import { icons } from '../../lib/icons.ts'

const toast = useToast()
const router = useRouter()

const Dropdown = defineAsyncComponent(() => import('primevue/dropdown'))
const InputText = defineAsyncComponent(() => import('primevue/inputtext'))
const InputNumber = defineAsyncComponent(() => import('primevue/inputnumber'))
const FileUpload = defineAsyncComponent(() => import('primevue/fileupload'))
const Button = defineAsyncComponent(() => import('primevue/button'))
const Card = defineAsyncComponent(() => import('primevue/card'))

const add = ref({
  name: '',
  url: '',
})

const bullet = ref({
  name: '',
  diameter: 0,
  manufacturer_id: '',
  weight: 0,
  meta: {},
})

const file = ref('')
const manufacturers = ref<Manufacturer[]>([])
const loading = ref(false)

const loadManufacturers = async () => {
  await axios.get(`${import.meta.env.VITE_API}/manufacturer`).then((r: Response<Manufacturer[]>) => {
    manufacturers.value.push({
      name: '-- Add --',
      id: '-- Add --',
    } as Manufacturer)

    if (!r.data.payload) {
      return
    }

    r.data.payload.forEach((m: Manufacturer) => {
      manufacturers.value.push(m)
    })
  })
}

const fileSelected = (event: FileUploadSelectEvent) => {
  file.value = event.files[0]
}

const createManufacturer = async () => {
  return axios.post(`${import.meta.env.VITE_API}/manufacturer`, {
    name: add.value.name,
    url: add.value.url,
  }, {
    headers: {
      Authorization: `Bearer ${jwt}`,
    },
  }).then((r: Response<Manufacturer>) => {
    manufacturers.value.push(r.data.payload)
    bullet.value.manufacturer_id = r.data.payload.id
  })
}

const create = async () => {
  loading.value = true
  if (bullet.value.manufacturer_id === '-- Add --') {
    try {
      await createManufacturer()
    } catch (e) {
      toast.add({
        severity: 'error',
        summary: 'Error',
        detail: e,
        life: 3000,
      } as ToastMessageOptions)

      return
    }
  }

  let formData = new FormData()
  formData.append('photo', file.value)
  formData.append('manufacturer_id', bullet.value.manufacturer_id)
  formData.append('weight', bullet.value.weight.toString())
  formData.append('name', bullet.value.name)
  formData.append('diameter', bullet.value.diameter.toString())

  axios.post(`${import.meta.env.VITE_API}/bullet`,
      formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      },
  ).then((r: Response<string>) => {
    router.push(`/bullets/edit/${r.data.payload}`)
  }).catch((e: AxiosError<{ message: string }>) => {
    loading.value = false
    toast.add({
      severity: 'error',
      summary: 'Error',
      detail: e.response?.data.message,
      life: 3000,
    } as ToastMessageOptions)
  })
}

loadManufacturers()
</script>