<template>
  <div v-if="open" class="modal modal-open">
    <div class="modal-box">
      <h3 class="font-bold text-lg mb-4">
        Ajouter un nouveau site
      </h3>
      <form class="space-y-4" @submit.prevent="handleSubmit">
        <div class="form-control">
          <label class="label">
            <span class="label-text">Nom du site</span>
          </label>
          <input
            v-model="form.name"
            type="text"
            placeholder="Ex: Usine de production"
            class="input input-bordered"
            :disabled="disabled"
            required
          >
        </div>

        <SiteContactFormFields :form="form" :disabled="disabled" />

        <div class="modal-action">
          <button
            type="button"
            class="btn btn-outline"
            @click="$emit('close')"
          >
            Annuler
          </button>
          <button type="submit" class="btn btn-primary" :disabled="disabled">
            Créer le site
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, watch } from 'vue'
import SiteContactFormFields from '~/components/sites/SiteContactFormFields.vue'

const props = defineProps<{
  open: boolean
  disabled: boolean
}>()

const emit = defineEmits<{
  close: []
  create: [data: { name: string, contactName: string, contactPhone: string, contactAddress: string, contactPostalCode: string, contactCity: string }]
}>()

const form = reactive({
  name: '',
  contactName: '',
  contactPhone: '',
  contactAddress: '',
  contactPostalCode: '',
  contactCity: '',
})

function handleSubmit() {
  emit('create', { ...form })
}

watch(() => props.open, (isOpen) => {
  if (!isOpen) {
    form.name = ''
    form.contactName = ''
    form.contactPhone = ''
    form.contactAddress = ''
    form.contactPostalCode = ''
    form.contactCity = ''
  }
})
</script>
