<script setup>
import DialogModal from '@/Components/DialogModal.vue'
import InputLabel from '@/Components/InputLabel.vue'
import TextInput from '@/Components/TextInput.vue'
import PrimaryButton from '@/Components/PrimaryButton.vue'
import SectionTitle from '@/Components/SectionTitle.vue'
import { useForm } from '@inertiajs/vue3'

const props = defineProps({
  show: { type: Boolean, default: false },
  client_case: { type: Object, required: true },
  // Contract can initially be null while dialog is hidden; make it optional to avoid prop warning
  contract: { type: Object, default: null },
})

const emit = defineEmits(['close', 'created'])
const close = () => emit('close')

const form = useForm({
  reference: '',
  name: '',
  description: '',
  type: '',
})

const submit = () => {
  if (!props.contract) {
    // No contract selected; do nothing safely
    return
  }
  form.post(route('clientCase.contract.object.store', { client_case: props.client_case.uuid, uuid: props.contract.uuid }), {
    preserveScroll: true,
    onSuccess: () => { emit('created'); form.reset(); close() },
  })
}
</script>

<template>
  <DialogModal :show="show" @close="close">
    <template #title>Dodaj premet</template>
    <template #content>
      <form @submit.prevent="submit">
        <SectionTitle class="mt-2 border-b mb-4">
          <template #title>Premet</template>
        </SectionTitle>
        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <div>
            <InputLabel for="objRef" value="Referenca" />
            <TextInput id="objRef" v-model="form.reference" type="text" class="mt-1 block w-full" />
          </div>
          <div>
            <InputLabel for="objType" value="Tip" />
            <TextInput id="objType" v-model="form.type" type="text" class="mt-1 block w-full" />
          </div>
        </div>
        <div class="mt-4">
          <InputLabel for="objName" value="Naziv" />
          <TextInput id="objName" v-model="form.name" type="text" class="mt-1 block w-full" required />
        </div>
        <div class="mt-4">
          <InputLabel for="objDesc" value="Opis" />
          <textarea id="objDesc" v-model="form.description" class="mt-1 block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm" rows="3" />
        </div>
        <div class="flex justify-end mt-6">
          <PrimaryButton :class="{ 'opacity-25': form.processing }" :disabled="form.processing">Shrani</PrimaryButton>
        </div>
      </form>
    </template>
  </DialogModal>
</template>
