<script setup>
import UpdateDialog from '@/Components/Dialogs/UpdateDialog.vue'
import { useForm } from 'vee-validate'
import { toTypedSchema } from '@vee-validate/zod'
import * as z from 'zod'
import { computed, ref, watch } from 'vue'
import { router } from '@inertiajs/vue3'
import { FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/Components/ui/form'
import { Input } from '@/Components/ui/input'
import { Textarea } from '@/Components/ui/textarea'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/Components/ui/select'
import { Checkbox } from '@/Components/ui/checkbox'
import { Switch } from '@/Components/ui/switch'

const props = defineProps({
  show: { type: Boolean, default: false },
  client_case_uuid: { type: String, required: true },
  document: { type: Object, default: null },
  contracts: { type: Array, default: () => [] },
})

const emit = defineEmits(['close', 'saved'])

const formSchema = toTypedSchema(z.object({
  name: z.string().min(1, 'Ime je obvezno'),
  description: z.string().optional(),
  is_public: z.boolean().default(false),
  contract_uuid: z.string().nullable().optional(),
}))

const form = useForm({
  validationSchema: formSchema,
})


const processing = ref(false)

const update = async () => {
  if (!props.document) return
  
  processing.value = true
  const { values } = form
  
  router.patch(
    route('clientCase.document.update', {
      client_case: props.client_case_uuid,
      document: props.document.uuid,
    }),
    values,
    {
      preserveScroll: true,
      onSuccess: () => {
        emit('saved')
        close()
      },
      onError: (errors) => {
        // Map Inertia errors to VeeValidate field errors
        Object.keys(errors).forEach((field) => {
          const errorMessages = Array.isArray(errors[field])
            ? errors[field]
            : [errors[field]]
          form.setFieldError(field, errorMessages[0])
        })
        processing.value = false
      },
      onFinish: () => {
        processing.value = false
      },
    }
  )
}

const close = () => {
  emit('close')
  processing.value = false
}

const onSubmit = form.handleSubmit((values) => {
  update()
})

const onConfirm = () => {
  onSubmit()
}

const contractOptions = computed(() => {
  return props.contracts || []
})

// Watch for dialog opening and document changes
watch(
  () => [props.show, props.document],
  () => {
    if (!props.show) {
      return
    }
    // When dialog opens, reset form with document values
    if (props.document) {
      form.resetForm({
        values: {
          name: props.document.name || props.document.original_name || '',
          description: props.document.description || '',
          is_public: !!props.document.is_public,
          contract_uuid: (props.document?.documentable_type || '').toLowerCase().includes('contract') ? (props.document.contract_uuid || null) : null,
        },
      })
    }
  },
  { immediate: true }
)
</script>

<template>
  <UpdateDialog
    :show="show"
    title="Uredi dokument"
    :processing="processing"
    @close="close"
    @confirm="onConfirm"
  >
    <form @submit.prevent="onSubmit" class="space-y-4">
      <FormField v-slot="{ componentField }" name="name">
        <FormItem>
          <FormLabel>Ime</FormLabel>
          <FormControl>
            <Input id="docName" v-bind="componentField" />
          </FormControl>
          <FormMessage />
        </FormItem>
      </FormField>

      <FormField v-slot="{ componentField }" name="description">
        <FormItem>
          <FormLabel>Opis</FormLabel>
          <FormControl>
            <Textarea id="docDesc" v-bind="componentField" rows="3" />
          </FormControl>
          <FormMessage />
        </FormItem>
      </FormField>

      <FormField v-slot="{ value, handleChange }" name="is_public">
        <FormItem class="flex flex-row items-start space-x-3 space-y-0">
          <FormControl>
            <Switch
              :model-value="value"
              @update:model-value="handleChange"
            />
          </FormControl>
          <div class="space-y-1 leading-none">
            <FormLabel>Javno</FormLabel>
          </div>
        </FormItem>
      </FormField>

      <FormField v-slot="{ value, handleChange }" name="contract_uuid">
        <FormItem>
          <FormLabel>Pogodba</FormLabel>
          <Select :model-value="value" @update:model-value="handleChange">
            <FormControl>
              <SelectTrigger>
                <SelectValue placeholder="— Brez — (dok. pri primeru)" />
              </SelectTrigger>
            </FormControl>
            <SelectContent>
              <SelectItem :value="null">— Brez — (dok. pri primeru)</SelectItem>
              <SelectItem
                v-for="c in contractOptions"
                :key="c.uuid || c.id"
                :value="c.uuid"
              >
                {{ c.reference || c.uuid }}
              </SelectItem>
            </SelectContent>
          </Select>
          <FormMessage />
        </FormItem>
      </FormField>
    </form>
  </UpdateDialog>
</template>
