<template>
    <div>
<!--        <h1 class="mb-8 font-bold text-3xl">-->
<!--            <Link class="text-indigo-400 hover:text-indigo-600" :href="this.route('tickets')">{{ $t('Tickets') }}</Link>-->
<!--            <span class="text-indigo-400 font-medium">/</span> {{ $t('Create') }}-->
<!--        </h1>-->
        <div class="bg-white rounded-md shadow overflow-hidden max-w-full">
            <form @submit.prevent="store">
                <div class="p-8 -mr-6 -mb-8 flex flex-wrap">


                    <select-input-filter placeholder="Start typing" :onInput="doFilter" :items="customers"
                                         v-if="user_access.ticket.update && auth.user.role.slug !== 'customer'"
                                         v-model="form.user_id" :error="form.errors.user_id"
                                         class="pr-6 pb-8 w-full lg:w-1/3" :label="$t('Customer')">
                    </select-input-filter>


                    <select-input v-if="user_access.ticket.update" v-model="form.priority_id" :error="form.errors.priority_id" class="pr-6 pb-8 w-full lg:w-1/3" :label="$t('Priority')">
                        <option :value="null" />
                        <option v-for="s in priorities" :key="s.id" :value="s.id">{{ s.name }}</option>
                    </select-input>
                    <select-input v-if="!(hidden_fields && hidden_fields.includes('ticket_type'))" v-model="form.type_id" :error="form.errors.type_id" class="pr-6 pb-8 w-full lg:w-1/3" :label="$t('Type')">
                        <option :value="null" />
                        <option v-for="s in types" :key="s.id" :value="s.id">{{ s.name }}</option>
                    </select-input>

                    <select-input v-if="!(hidden_fields && hidden_fields.includes('department'))" @change="getCategories()" v-model="form.department_id" :error="form.errors.department_id" class="pr-6 pb-5 md:col-span-6 lg:w-1/3" :label="$t('Department')">
                        <option :value="null">{{ $t('Select a department') }}</option>
                        <option v-for="department in departments" :key="department.id" :value="department.id">{{ department.name }}</option>
                    </select-input>

                    <select-input ref="category" v-if="!(hidden_fields && hidden_fields.includes('category')) && form.department_id" @change="getSubCategories()" v-model="form.category_id" :error="form.errors.category_id" class=" pb-5 pr-6 md:col-span-6 lg:w-1/3" :label="$t('Category')">
                        <option :value="null">{{ $t('Select a category') }}</option>
                        <option v-for="category in categories" :key="category.id" :value="category.id">{{ category.name }}</option>
                    </select-input>

                    <select-input ref="sub_category"  v-if="form.category_id && sub_categories && sub_categories.length > 0" v-model="form.sub_category_id" :error="form.errors.sub_category_id" class=" pb-5 md:col-span-6 lg:w-1/3" :label="$t('Sub Category')">
                        <option :value="null">{{ $t('Select a sub category') }}</option>
                        <option v-for="category in sub_categories" :key="category.id" :value="category.id">{{ category.name }}</option>
                    </select-input>

                    <select-input-filter placeholder="Start typing" :onInput="doFilterUsersExceptCustomer" :items="usersExceptCustomers"
                                         v-if="auth.user.role.slug !== 'customer' && user_access.ticket.update && !(hidden_fields && hidden_fields.includes('assigned_to'))"
                                         v-model="form.assigned_to" :error="form.errors.assigned_to"
                                         class="pr-6 pb-8 w-full lg:w-1/3" :label="$t('Assigned to')">
                    </select-input-filter>

<!--                    <div v-for="custom_field in custom_fields" class="pr-6 w-full lg:w-1/3" :key="custom_field.id">-->
<!--                        <text-input v-model="form[custom_field.name]" :error="form.errors[custom_field.name]" :placeholder="custom_field.placeholder" class="pr-6 pb-8 w-full" :label="$t(custom_field.label)" />-->
<!--                    </div>-->
                    <div class="pr-6 pb-8 w-full lg:w-1/3" v-for="ticket_field in custom_fields" :key="ticket_field.id" :class="{'lg:w-full': ticket_field.type === 'textarea'}">
                        <div class="flex flex-col w-full">
                            <!-- Label (consistent with regular form inputs) -->
                            <label v-if="ticket_field.type !== 'checkbox'" :for="'ticket_field_'+ticket_field.id" class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                                {{ ticket_field.label }}
                                <span v-if="ticket_field.required" class="text-red-500 ml-1">*</span>
                                <span v-else class="text-slate-500 text-xs ml-1">(optional)</span>
                            </label>
                            <div v-else class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">
                                {{ ticket_field.label }}
                                <span v-if="ticket_field.required" class="text-red-500 ml-1">*</span>
                                <span v-else class="text-slate-500 text-xs ml-1">(optional)</span>
                            </div>
                            
                            <!-- Text, Email, Number Inputs (matching TextInput component) -->
                            <input 
                                v-if="['text', 'email', 'number'].includes(ticket_field.type)" 
                                v-model="form.custom_field[ticket_field.name]" 
                                :type="ticket_field.type" 
                                :id="'ticket_field_'+ticket_field.id" 
                                :placeholder="ticket_field.placeholder" 
                                :required="ticket_field.required" 
                                class="w-full px-4 py-3 bg-white dark:bg-slate-700 border border-slate-300 dark:border-slate-600 rounded-lg text-sm text-slate-900 dark:text-white placeholder-slate-500 dark:placeholder-slate-400 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:focus:ring-blue-400 dark:focus:border-blue-400 transition-all duration-200"
                                :class="{'border-red-500 dark:border-red-400 focus:ring-red-500 focus:border-red-500': form.errors['custom_field.' + ticket_field.name]}"
                            />
                            
                            <!-- Textarea (matching TextInput component) -->
                            <textarea 
                                v-if="ticket_field.type === 'textarea'" 
                                :id="'ticket_field_'+ticket_field.id" 
                                rows="3" 
                                v-model="form.custom_field[ticket_field.name]" 
                                class="w-full px-4 py-3 bg-white dark:bg-slate-700 border border-slate-300 dark:border-slate-600 rounded-lg text-sm text-slate-900 dark:text-white placeholder-slate-500 dark:placeholder-slate-400 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:focus:ring-blue-400 dark:focus:border-blue-400 transition-all duration-200 resize-none"
                                :placeholder="ticket_field.placeholder"
                                :required="ticket_field.required"
                                :class="{'border-red-500 dark:border-red-400 focus:ring-red-500 focus:border-red-500': form.errors['custom_field.' + ticket_field.name]}"
                            ></textarea>
                            
                            <!-- Select Dropdown (matching SelectInput component) -->
                            <div v-if="ticket_field.type === 'select'" class="relative">
                                <select 
                                    :id="'ticket_field_'+ticket_field.id"
                                    v-model="form.custom_field[ticket_field.name]"
                                    :required="ticket_field.required"
                                    class="w-full px-4 py-3 pr-10 bg-white dark:bg-slate-700 border border-slate-300 dark:border-slate-600 rounded-lg text-sm text-slate-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:focus:ring-blue-400 dark:focus:border-blue-400 transition-all duration-200 appearance-none cursor-pointer"
                                    :class="{'border-red-500 dark:border-red-400 focus:ring-red-500 focus:border-red-500': form.errors['custom_field.' + ticket_field.name]}"
                                >
                                    <option :value="null">{{ ticket_field.placeholder || 'Select an option' }}</option>
                                    <option
                                        v-for="(option, oi) in ticket_field.options"
                                        :key="oi"
                                        :value="option.value"
                                    >
                                        {{ option.name }}
                                    </option>
                                </select>
                                <!-- Custom Dropdown Arrow -->
                                <div class="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                                    <svg class="w-4 h-4 text-slate-400 dark:text-slate-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
                                    </svg>
                                </div>
                            </div>
                            
                            <!-- Checkbox (Multiple Options) -->
                            <div v-if="ticket_field.type === 'checkbox'" class="space-y-2">
                                <div
                                    v-for="(option, oi) in ticket_field.options"
                                    :key="oi"
                                    class="flex items-center"
                                >
                                    <input
                                        :id="'ticket_checkbox_'+ticket_field.id+'_'+oi"
                                        type="checkbox"
                                        :value="option.value"
                                        v-model="form.custom_field[ticket_field.name]"
                                        class="w-4 h-4 text-blue-600 bg-white dark:bg-slate-700 border-slate-300 dark:border-slate-600 rounded focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400"
                                        :class="{'border-red-500 dark:border-red-400': form.errors['custom_field.' + ticket_field.name]}"
                                    >
                                    <label
                                        :for="'ticket_checkbox_'+ticket_field.id+'_'+oi"
                                        class="ml-2 text-sm text-slate-700 dark:text-slate-300"
                                    >
                                        {{ option.name }}
                                    </label>
                                </div>
                            </div>
                            
                            <!-- Radio Buttons -->
                            <div v-if="ticket_field.type === 'radio'" class="space-y-2">
                                <div
                                    v-for="(option, oi) in ticket_field.options"
                                    :key="oi"
                                    class="flex items-center"
                                >
                                    <input
                                        :id="'ticket_radio_'+ticket_field.id+'_'+oi"
                                        type="radio"
                                        :value="option.value"
                                        v-model="form.custom_field[ticket_field.name]"
                                        :name="'ticket_radio_'+ticket_field.id"
                                        :required="ticket_field.required"
                                        class="w-4 h-4 text-blue-600 bg-white dark:bg-slate-700 border-slate-300 dark:border-slate-600 focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400"
                                        :class="{'border-red-500 dark:border-red-400': form.errors['custom_field.' + ticket_field.name]}"
                                    >
                                    <label
                                        :for="'ticket_radio_'+ticket_field.id+'_'+oi"
                                        class="ml-2 text-sm text-slate-700 dark:text-slate-300"
                                    >
                                        {{ option.name }}
                                    </label>
                                </div>
                            </div>
                            
                            <!-- Date Input (matching TextInput component) -->
                            <input 
                                v-if="ticket_field.type === 'date'" 
                                v-model="form.custom_field[ticket_field.name]" 
                                type="date" 
                                :id="'ticket_field_'+ticket_field.id" 
                                :placeholder="ticket_field.placeholder" 
                                :required="ticket_field.required" 
                                class="w-full px-4 py-3 bg-white dark:bg-slate-700 border border-slate-300 dark:border-slate-600 rounded-lg text-sm text-slate-900 dark:text-white placeholder-slate-500 dark:placeholder-slate-400 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:focus:ring-blue-400 dark:focus:border-blue-400 transition-all duration-200"
                                :class="{'border-red-500 dark:border-red-400 focus:ring-red-500 focus:border-red-500': form.errors['custom_field.' + ticket_field.name]}"
                            />
                            
                            <!-- DateTime Input (matching TextInput component) -->
                            <input 
                                v-if="ticket_field.type === 'datetime'" 
                                v-model="form.custom_field[ticket_field.name]" 
                                type="datetime-local" 
                                :id="'ticket_field_'+ticket_field.id" 
                                :placeholder="ticket_field.placeholder" 
                                :required="ticket_field.required" 
                                class="w-full px-4 py-3 bg-white dark:bg-slate-700 border border-slate-300 dark:border-slate-600 rounded-lg text-sm text-slate-900 dark:text-white placeholder-slate-500 dark:placeholder-slate-400 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:focus:ring-blue-400 dark:focus:border-blue-400 transition-all duration-200"
                                :class="{'border-red-500 dark:border-red-400 focus:ring-red-500 focus:border-red-500': form.errors['custom_field.' + ticket_field.name]}"
                            />
                            
                            <!-- File Input (matching TextInput component) -->
                            <input 
                                v-if="ticket_field.type === 'file'" 
                                type="file" 
                                :id="'ticket_field_'+ticket_field.id" 
                                @change="handleCustomFileChange(ticket_field.name, $event)"
                                :required="ticket_field.required" 
                                class="w-full px-4 py-3 bg-white dark:bg-slate-700 border border-slate-300 dark:border-slate-600 rounded-lg text-sm text-slate-900 dark:text-white file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100 dark:file:bg-slate-600 dark:file:text-slate-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:focus:ring-blue-400 dark:focus:border-blue-400 transition-all duration-200"
                                :class="{'border-red-500 dark:border-red-400 focus:ring-red-500 focus:border-red-500': form.errors['custom_field.' + ticket_field.name]}"
                            />
                            
                            <!-- Error Messages (matching TextInput component) -->
                            <div v-if="form.errors['custom_field.' + ticket_field.name]" class="mt-2 flex items-center gap-2 text-sm text-red-600 dark:text-red-400">
                                <svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                </svg>
                                <span>{{ form.errors['custom_field.' + ticket_field.name] }}</span>
                            </div>
                            
                            <!-- Hint Text (matching TextInput helperText) -->
                            <div v-if="ticket_field.hint && !form.errors['custom_field.' + ticket_field.name]" class="mt-2 text-sm text-slate-500 dark:text-slate-400">
                                {{ ticket_field.hint }}
                            </div>
                        </div>
                    </div>
                    <text-input v-model="form.subject" :error="form.errors.subject" class="pr-6 pb-8 w-full lg:w-full" :label="$t('Subject')" />
                    <div class="pr-6 pb-8 w-full">
                        <label class="form-label" >Request Details:</label>
                        <RichEditor v-model="form.details" class="mt-1" />
                        <div v-if="form.errors.details" class="text-red-600 text-sm mt-1">{{ form.errors.details }}</div>
                    </div>
                    <input ref="file" type="file" accept=".xlsx,.xls,image/*,.doc, .docx,.ppt, .pptx,.txt,.pdf, .zip" class="hidden" multiple="multiple" @change="fileInputChange" />
                    <div class="pr-6 pb-8 w-full lg:w-full flex-col">
                        <button type="button" class="btn flex justify-center items-center" @click="fileBrowse">
                            <icon name="file" class="flex-shrink-0 h-8 fill-gray-400 pr-1" /> <h4>{{ $t('Attach files') }}</h4>
                        </button>
                        <div v-if="form.files.length" class="flex items-center justify-between pr-6 pt-8 w-full lg:w-1/2" v-for="(file, fi) in form.files" :key="fi">
                            <div class="flex-1 pr-1">
                                {{ file.name }} <span class="text-gray-500 text-xs">({{ getFileSize(file.size) }})</span>
                            </div>
                            <button type="button" class="btn flex justify-center items-center" @click="fileRemove(file, fi)">
                                {{ $t('Remove') }}</button>
                        </div>
                    </div>
                </div>
                <div class="px-8 py-4 bg-gray-50 border-t border-gray-100 flex justify-end items-center">
                    <loading-button :loading="form.processing" class="btn-indigo" type="submit">{{ $t('Create') }}
                        {{ $t('Ticket') }}</loading-button>
                </div>
            </form>
        </div>
    </div>
</template>

<script>
import { Link } from '@inertiajs/vue3'
import Icon from '@/Shared/Icon.vue'
import Layout from '@/Shared/Layout.vue'
import TextInput from '@/Shared/TextInput.vue'
import SelectInput from '@/Shared/SelectInput.vue'
import SelectInputFilter from '@/Shared/SelectInputFilter.vue'
import TextareaInput from '@/Shared/TextareaInput.vue'
import LoadingButton from '@/Shared/LoadingButton.vue'

import RichEditor from '@/Shared/RichEditor.vue';

import axios from 'axios'

export default {
    components: {
        LoadingButton,
        SelectInput,
        SelectInputFilter,
        TextInput,
        TextareaInput,
        Link,
        Icon,
        RichEditor,
    },
    layout: Layout,
    props: {
        customers: Array,
        usersExceptCustomers: Array,
        priorities: Array,
        statuses: Array,
        types: Array,
        departments: Array,
        all_categories: Array,
        auth: Object,
        hidden_fields: Object,
        custom_fields: Object,
    },
    remember: false,
    data() {
        return {
            user_access: this.$page.props.auth?.user?.access || {},
            categories: [],
            sub_categories: [],
            form: this.$inertia.form({
                user_id: null,
                priority_id: null,
                status_id: null,
                department_id: null,
                category_id: null,
                sub_category_id: null,
                assigned_to: null,
                type_id: null,
                subject: null,
                details: '',
                files: [],
                custom_field: {}
            }),
        }
    },
    created() {
        this.setDefaultValue(this.statuses, 'status_id', 'Pending')
        this.setDefaultValue(this.priorities, 'priority_id', 'Generally')
        
        // Initialize custom fields - checkbox fields should be arrays
        if (this.custom_fields && Array.isArray(this.custom_fields)) {
            this.custom_fields.forEach((field) => {
                if (field && field.name) {
                    if (field.type === 'checkbox') {
                        if (!Array.isArray(this.form.custom_field[field.name])) {
                            this.form.custom_field[field.name] = []
                        }
                    } else if (this.form.custom_field[field.name] === undefined) {
                        this.form.custom_field[field.name] = ''
                    }
                }
            })
        }
    },
    methods: {
        getCategories(){
            this.categories = this.all_categories.filter(cat=>cat.department_id === this.form.department_id)
            this.form.category_id = null;
            this.$refs.category.selected = null;
        },
        getSubCategories(){
            this.sub_categories = this.all_categories.filter(cat=>cat.parent_id === this.form.category_id)
            this.form.sub_category_id = null;
            this.$refs.sub_category.selected = null;
        },
        doFilter(e){
            axios.get(this.route('filter.customers', {search: e.target.value})).then((res)=>{
                this.customers.splice(0, this.customers.length, ...res.data);
            })
        },
        doFilterUsersExceptCustomer(e){
            axios.get(this.route('filter.users_except_customer', {search: e.target.value})).then((res)=>{
                this.usersExceptCustomers.splice(0, this.usersExceptCustomers.length, ...res.data);
            })
        },
        setDefaultValue(arr, key, value){
            const find = arr.find(i=>i.name.match(new RegExp(value + ".*")))
            if(find){
                this.form[key] = find['id']
            }
        },
        fileInputChange(e) {
            let selectedFiles = e.target.files;
            for (let i = 0; i < selectedFiles.length; i++) {
                this.form.files.push(selectedFiles[i]);
            }
        },
        fileRemove(image, index) {
            this.form.files.splice(index, 1);
        },
        getFileSize(size) {
            const i = Math.floor(Math.log(size) / Math.log(1024))
            return (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + ['B', 'kB', 'MB', 'GB', 'TB'][i]
        },
        fileBrowse() {
            this.$refs.file.click()
        },
        handleCustomFileChange(fieldName, event) {
            const files = event.target.files;
            if (files && files.length > 0) {
                // For file fields, store the file object
                // Note: You may need to handle file uploads separately or include them in form.files
                // For now, we'll store the file reference
                if (!this.form.custom_field[fieldName]) {
                    this.form.custom_field[fieldName] = []
                }
                // Add files to the custom field
                Array.from(files).forEach(file => {
                    this.form.custom_field[fieldName].push(file)
                })
            }
        },
        store() {
            if(this.auth && this.auth.user) {
                this.form.user_id = this.auth.user.id;
            }
            
            // Prepare custom fields for submission
            // Ensure checkbox fields are arrays, and filter out empty values
            const customFieldData = {}
            Object.keys(this.form.custom_field).forEach(key => {
                const field = this.custom_fields.find(f => f.name === key)
                if (field) {
                    const value = this.form.custom_field[key]
                    
                    // Skip empty values (except for checkboxes which can be empty arrays)
                    if (value === null || value === '' || value === undefined) {
                        // Only skip if field is not required, or if it's a checkbox with empty array
                        if (!field.required || (field.type === 'checkbox' && Array.isArray(value) && value.length === 0)) {
                            return
                        }
                    }
                    
                    if (field.type === 'checkbox') {
                        // Ensure checkbox fields are arrays
                        customFieldData[key] = Array.isArray(value) ? value : (value ? [value] : [])
                    } else {
                        customFieldData[key] = value
                    }
                }
            })
            this.form.custom_field = customFieldData
            
            this.form.post(this.route('tickets.store'))
        },
    },
}
</script>
