<script setup>
import DialogModal from '@/Components/DialogModal.vue'
import PrimaryButton from '@/Components/PrimaryButton.vue'
import SecondaryButton from '@/Components/SecondaryButton.vue'
import ActionMessage from '@/Components/ActionMessage.vue'
import InputLabel from '@/Components/InputLabel.vue'
import TextInput from '@/Components/TextInput.vue'
import { useForm } from '@inertiajs/vue3'
import { ref, watch } from 'vue'

const props = defineProps({
  show: { type: Boolean, default: false },
  postUrl: { type: String, required: true },
})
const emit = defineEmits(['close', 'uploaded'])

const MAX_SIZE = 25 * 1024 * 1024 // 25MB
const ALLOWED_EXTS = ['doc','docx','pdf','txt','csv','xls','xlsx','jpeg','jpg','png']

const form = useForm({
  name: '',
  description: '',
  file: null,
  is_public: false,
})
const localError = ref('')

watch(() => props.show, (v) => {
  if (!v) return
  localError.value = ''
})

const onFileChange = (e) => {
  localError.value = ''
  const f = e.target.files?.[0]
  if (!f) { form.file = null; return }
  const ext = (f.name.split('.').pop() || '').toLowerCase()
  if (!ALLOWED_EXTS.includes(ext)) {
    localError.value = 'Unsupported file type. Allowed: ' + ALLOWED_EXTS.join(', ')
    e.target.value = ''
    form.file = null
    return
  }
  if (f.size > MAX_SIZE) {
    localError.value = 'File is too large. Maximum size is 25MB.'
    e.target.value = ''
    form.file = null
    return
  }
  form.file = f
  if (!form.name) {
    form.name = f.name.replace(/\.[^.]+$/, '')
  }
}

const submit = () => {
  localError.value = ''
  if (!form.file) {
    localError.value = 'Please choose a file.'
    return
  }
  const ext = (form.file.name.split('.').pop() || '').toLowerCase()
  if (!ALLOWED_EXTS.includes(ext)) {
    localError.value = 'Unsupported file type. Allowed: ' + ALLOWED_EXTS.join(', ')
    return
  }
  if (form.file.size > MAX_SIZE) {
    localError.value = 'File is too large. Maximum size is 25MB.'
    return
  }
  form.post(props.postUrl, {
    forceFormData: true,
    onSuccess: () => {
      emit('uploaded')
      close()
      form.reset()
    },
  })
}

const close = () => emit('close')
</script>

<template>
  <DialogModal :show="props.show" @close="close" maxWidth="lg">
    <template #title>Dodaj dokument</template>
    <template #content>
      <div class="space-y-4">
        <div>
          <InputLabel for="doc_name" value="Name" />
          <TextInput id="doc_name" class="mt-1 block w-full" v-model="form.name" />
        </div>
        <div>
          <InputLabel for="doc_desc" value="Description" />
          <textarea id="doc_desc" class="mt-1 block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm" rows="3" v-model="form.description"></textarea>
        </div>
        <div>
          <InputLabel for="doc_file" value="File (max 25MB)" />
          <input id="doc_file" type="file" class="mt-1 block w-full" @change="onFileChange" accept=".doc,.docx,.pdf,.txt,.csv,.xls,.xlsx,.jpeg,.jpg,.png" />
          <div v-if="localError" class="text-sm text-red-600 mt-1">{{ localError }}</div>
        </div>
        <label class="inline-flex items-center gap-2 text-sm">
          <input type="checkbox" v-model="form.is_public" class="rounded" />
          Public
        </label>
      </div>
    </template>
    <template #footer>
      <div class="flex items-center gap-3">
        <ActionMessage :on="form.recentlySuccessful">Uploaded.</ActionMessage>
        <SecondaryButton type="button" @click="close">Cancel</SecondaryButton>
        <PrimaryButton :disabled="form.processing" @click="submit">Upload</PrimaryButton>
      </div>
    </template>
  </DialogModal>
</template>