<template>
  <div v-if="open" class="modal modal-open">
    <div class="modal-box max-w-2xl">
      <h3 class="font-bold text-lg mb-4">
        Ajouter une nouvelle machine
      </h3>
      <form @submit.prevent="handleSubmit">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
          <div class="form-control">
            <label class="label">
              <span class="label-text">Nom de la machine</span>
            </label>
            <input
              v-model="form.name"
              type="text"
              placeholder="Ex: Presse hydraulique #1"
              class="input input-bordered"
              :disabled="disabled"
              required
            >
          </div>

          <div class="form-control">
            <label class="label">
              <span class="label-text">Site</span>
            </label>
            <select
              v-model="form.siteId"
              class="select select-bordered"
              :disabled="disabled"
              required
            >
              <option value="">
                Sélectionner un site
              </option>
              <option v-for="site in sites" :key="site.id" :value="site.id">
                {{ site.name }}
              </option>
            </select>
          </div>
        </div>

        <div class="form-control mb-4">
          <label class="label">
            <span class="label-text">Référence</span>
          </label>
          <input
            v-model="form.reference"
            type="text"
            placeholder="Ex: PRESS-001"
            class="input input-bordered"
            :disabled="disabled"
          >
        </div>

        <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 la machine
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, watch } from 'vue'

const props = defineProps<{
  open: boolean
  sites: Array<{ id: string, name: string }>
  disabled: boolean
  preselectedSiteId?: string
}>()

const emit = defineEmits<{
  close: []
  create: [data: { name: string, siteId: string, reference: string }]
}>()

const form = reactive({
  name: '',
  siteId: '',
  reference: '',
})

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

watch(() => props.open, (isOpen) => {
  if (isOpen && props.preselectedSiteId) {
    form.siteId = props.preselectedSiteId
  }
  if (!isOpen) {
    form.name = ''
    form.siteId = ''
    form.reference = ''
  }
})
</script>
