<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { Head, useForm } from '@inertiajs/vue3';
import { mdiAccountKey, mdiArrowLeftBoldOutline, mdiTrashCan, mdiImageText, mdiPlus } from '@mdi/js';
import LayoutAuthenticated from '@/Layouts/LayoutAuthenticated.vue';
import SectionMain from '@/Components/SectionMain.vue';
import SectionTitleLineWithButton from '@/Components/SectionTitleLineWithButton.vue';
import CardBox from '@/Components/CardBox.vue';
import BaseDivider from '@/Components/BaseDivider.vue';
import BaseButton from '@/Components/BaseButton.vue';
import BaseButtons from '@/Components/BaseButtons.vue';
import { stardust } from '@eidellev/adonis-stardust/client';
import FormField from '@/Components/FormField.vue';
import FormControl from '@/Components/FormControl.vue';
import standardTypes from 'mime/types/standard.js';
import otherTypes from 'mime/types/other.js';
import FormCheckRadioGroup from '@/Components/FormCheckRadioGroup.vue';
import MimetypeInput from '@/Components/MimetypeInput.vue';

defineProps({
    borderless: Boolean,
    transparent: Boolean,
    ctrlKFocus: Boolean,
});

const customTypes: { [key: string]: string[] } = {
  'application/vnd.opengeospatial.geopackage+sqlite3': ['gpkg'],
  'text/plain': ['txt', 'asc', 'c', 'cc', 'h', 'srt'],
};

const isReadOnly: boolean = true;
// const standardMimeTypes = Object.keys(standardTypes);
// const otherMimeTypes = Object.keys(otherTypes);
// const customMimeTypes = Object.keys(customTypes);
const mimeTypesMap = new Map<string, string[]>();

Object.entries(standardTypes).forEach(([mimeType, extensions]) => {
    mimeTypesMap.set(mimeType, extensions);
});

Object.entries(otherTypes).forEach(([mimeType, extensions]) => {
    mimeTypesMap.set(mimeType, extensions);
});

Object.entries(customTypes).forEach(([mimeType, extensions]) => {
    mimeTypesMap.set(mimeType, extensions);
});

const mimeTypes = Array.from(mimeTypesMap.keys());

const file_extensions = reactive<Record<string, string>>({});
interface FormData {
    name: string;
    file_extension: string[];
    alternate_mimetype: string[];
    enabled: boolean;
    [key: string]: string | string[] | boolean;
}
const form = useForm<FormData>({
    name: '',
    file_extension: [],
    alternate_mimetype: [],
    enabled: true,
});

const mimetypeError = ref<string | null>(null);

const addAlternateMimetype = () => {
    form.alternate_mimetype.push("");
};
const removeAliasMimetype = (index: number) => {
    form.alternate_mimetype.splice(index, 1);
};

function resetFileExtensions() {
    Object.keys(file_extensions).forEach(key => {
        delete file_extensions[key];
    });
}

const isValidMimeType = (mimeType: string): boolean => {
    let extensions = mimeTypesMap.get(mimeType) || null;
    return extensions !== null;
};

const clearInput = () => {
    // newExtension.value = '';
    // showDropdown.value = false;
    form.name = '';
    resetFileExtensions();
};

const selectResult = (mimeType: string) => {
    form.name = mimeType;
    resetFileExtensions();
    // showDropdown.value = false;
    // newExtension.value = '';
    // selectedIndex.value = -1;

    if (form.name && isValidMimeType(form.name)) {
        // const extensions = mime.getAllExtensions(form.name) as Set<string>;
        const extensions = mimeTypesMap.get(mimeType);
        extensions?.forEach(extension => {
            file_extensions[extension] = extension;
        });
    } else {
        mimetypeError.value = 'Invalid MIME type.';
    }
};

const submit = async () => {
    if (isValidForm()) {
        await form.post(stardust.route('settings.mimetype.store'), {
            preserveScroll: true,
        });
    }
};

const isValidForm = (): boolean => {
    if (!form.name) {
        form.errors.name = 'Name is required.';
        return false;
    } else {
        form.errors.name = '';
    }
    if (!form.file_extension.length) {
        form.errors.file_extension = 'At least one file extension is required.';

        return false;
    }
    return true;
};
</script>

<template>
    <LayoutAuthenticated>

        <Head title="Add mimetype" />
        <SectionMain>
            <SectionTitleLineWithButton :icon="mdiAccountKey" title="Add Mimetype" main>
                <BaseButton :route-name="stardust.route('settings.mimetype.index')" :icon="mdiArrowLeftBoldOutline"
                    label="Back" color="white" rounded-full small />
            </SectionTitleLineWithButton>
            <CardBox form>
                <MimetypeInput @on-select-result="selectResult" @on-clear-input="clearInput" :transparent="transparent"
                    :borderless="borderless" :mimeTypes="mimeTypes" :isValidMimeType="isValidMimeType" />
                <div v-if="mimetypeError" class="text-red-400 text-sm mt-1">
                    {{ mimetypeError }}
                </div>

                <BaseDivider v-if="form.name" />

                <FormField v-if="form.name" label="Mimetype Name" :class="{ 'text-red-400': form.errors.name }">
                    <FormControl v-model="form.name" name="display_name" :error="form.errors.name"
                        :is-read-only=isReadOnly>
                        <div class="text-red-400 text-sm" v-if="form.errors.name">
                            {{ form.errors.name }}
                        </div>
                    </FormControl>
                </FormField>
                <!-- <FormField v-if="form.name" help="Activate mimetype immediately?" wrap-body
                    class="mt-8 w-full mx-2 flex-1 flex-col">
                    <label for="rights" class="checkbox mr-6 mb-3 last:mr-0">
                        <input type="checkbox" id="rights" required v-model="form.enabled" />
                        <span class="check" />
                        <a class="pl-2" target="_blank">Enable mimetype immediately </a>
                    </label>
                </FormField> -->
                <FormField v-if="Object.keys(file_extensions).length > 0" label="File Extensions" wrap-body>
                    <!-- <div class="flex items-center mt-2">
                        <FormControl v-model="newExtension" placeholder="Enter file extension" class="mr-2" />
                        <BaseButton color="info" @click="addFileExtension" label="Add" />
                    </div> -->
                    <FormCheckRadioGroup v-model="form.file_extension" :options="file_extensions" name="file_extensions"
                        is-column allow-manual-adding manual-adding-placeholder="Enter additional file extension manually" />

                </FormField>
                <div class="text-red-400 text-sm" v-if="form.errors.file_extension">
                    {{ form.errors.file_extension }}
                </div>

                <BaseDivider v-if="Object.keys(file_extensions).length > 0" />

                <CardBox v-if="form.name" class="mb-6 shadow" has-table :icon="mdiImageText" title="Alternate Mimetypes"
                    :header-icon="mdiPlus" @header-icon-click="addAlternateMimetype">
                    <div v-if="form.alternate_mimetype.length === 0" class="text-center py-4">
                        <p class="text-gray-600">No alternate mimetypes added yet.</p>
                        <p class="text-gray-400">
                            Click the plus icon above to add a new alternate mimetype.
                            <br>
                            An alternate mimetype is needed to ensure compatibility across different systems and
                            software.
                            For example, the GeoPackage standard mimetype is
                            'application/vnd.opengeospatial.geopackage+sqlite3', but most software stores it as
                            'application/x-sqlite3'. Therefore, 'application/x-sqlite3' must be added as an alternate
                            mimetype.
                        </p>
                    </div>
                    <table class="table-fixed border-green-900" v-if="form.alternate_mimetype.length > 0">
                        <thead>
                            <tr>
                                <th class="w-10/12">Alias Mimetype</th>
                                <th class="w-2/12"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="(alias, index) in form.alternate_mimetype" :key="index">
                                <td>
                                    <FormControl required v-model="form.alternate_mimetype[index]"
                                        placeholder="[alternate mimetype]">
                                        <div class="text-red-400 text-sm"
                                            v-if="Array.isArray(form.errors[`alternate_mimetype.${index}`])">
                                            {{ form.errors[`alternate_mimetype.${index}`]?.join(', ') }}
                                        </div>
                                    </FormControl>
                                </td>
                                <td class="before:hidden lg:w-1 whitespace-nowrap">
                                    <BaseButton color="danger" :icon="mdiTrashCan" small
                                        @click.prevent="removeAliasMimetype(index)" />
                                </td>
                            </tr>
                        </tbody>
                    </table>
                    <div class="text-red-400 text-sm"
                        v-if="form.errors.alternate_mimetype && Array.isArray(form.errors.alternate_mimetype)">
                        {{ form.errors.alternate_mimetype.join(', ') }}
                    </div>
                </CardBox>

                <template #footer>
                    <BaseButtons>
                        <BaseButton type="submit" color="info" label="Create" :class="{ 'opacity-25': form.processing }"
                            :disabled="form.processing" @click.prevent="submit()" />
                    </BaseButtons>
                </template>
            </CardBox>
        </SectionMain>
    </LayoutAuthenticated>
</template>
