<template>
    <div class="icon-picker">
        <!-- Selected Icon Button -->
        <div class="icon-picker-trigger" @click="openModal">
            <div v-if="selectedIcon" class="selected-icon-display">
                <Icon :icon="selectedIcon" class="selected-icon" />
                <span class="selected-icon-name">{{ selectedIcon }}</span>
            </div>
            <div v-else class="placeholder-display">
                <PlusOutlined class="placeholder-icon" />
                <span>{{ placeholder }}</span>
            </div>
            <a-button v-if="selectedIcon" type="text" size="small" class="clear-btn" @click.stop="clearIcon">
                <CloseOutlined />
            </a-button>
        </div>

        <!-- Icon Picker Modal -->
        <a-modal
            v-model:open="modalVisible"
            :title="$t('icon_set.select_icon')"
            width="720px"
            :footer="null"
            class="icon-picker-modal"
            destroyOnClose
        >
            <!-- Search and Add Button Row -->
            <div class="icon-header-row">
                <a-input
                    v-model:value="searchQuery"
                    :placeholder="$t('icon_set.search_icons')"
                    class="icon-search-input"
                    allowClear
                >
                    <template #prefix>
                        <SearchOutlined />
                    </template>
                </a-input>
                <a-button
                    v-if="permsArray.includes('icon_sets_create') || permsArray.includes('admin')"
                    type="primary"
                    @click="openAddIconModal"
                >
                    <template #icon><PlusOutlined /></template>
                    {{ $t('icon_set.add_icon') }}
                </a-button>
            </div>

            <!-- Icon Set Tabs -->
            <a-tabs v-model:activeKey="activeIconSet" class="icon-set-tabs">
                <a-tab-pane v-for="set in iconSets" :key="set.prefix" :tab="set.name" />
            </a-tabs>

            <!-- Loading State -->
            <div v-if="loading" class="icon-grid-loading">
                <a-spin size="large" />
            </div>

            <!-- Icons Grid -->
            <div v-else class="icon-grid-container">
                <div class="icon-grid">
                    <div
                        v-for="icon in filteredIcons"
                        :key="icon"
                        class="icon-item"
                        :class="{ selected: selectedIcon === icon }"
                        @click="selectIcon(icon)"
                    >
                        <Icon :icon="icon" class="icon-display" />
                        <span class="icon-name">{{ getIconName(icon) }}</span>
                    </div>
                </div>

                <!-- No Results -->
                <div v-if="filteredIcons.length === 0 && !loading" class="no-results">
                    <a-empty :description="$t('icon_set.no_icons_found')" />
                </div>
            </div>
        </a-modal>

        <!-- Add Icon Modal -->
        <a-modal
            v-model:open="addIconModalVisible"
            :title="$t('icon_set.add_new_icons')"
            width="600px"
            :maskClosable="false"
            @ok="submitAddIcons"
            @cancel="closeAddIconModal"
            :confirmLoading="addingIcons"
        >
            <div class="add-icon-form">
                <p class="add-icon-help">
                    {{ $t('icon_set.add_icon_help') }}
                </p>

                <!-- Repeater Items -->
                <div class="add-icon-repeater">
                    <div
                        v-for="(item, index) in newIconItems"
                        :key="index"
                        class="add-icon-row"
                    >
                        <a-row :gutter="12" align="middle">
                            <a-col :span="10">
                                <a-select
                                    v-model:value="item.icon_set_prefix"
                                    :placeholder="$t('icon_set.select_icon_set')"
                                    style="width: 100%"
                                    :options="iconSetOptions"
                                />
                            </a-col>
                            <a-col :span="10">
                                <a-input
                                    v-model:value="item.icon_name"
                                    :placeholder="$t('icon_set.icon_name_placeholder')"
                                    @input="onIconNameInput(index)"
                                    @pressEnter="addIconItem"
                                />
                            </a-col>
                            <a-col :span="2">
                                <div v-if="item.icon_set_prefix && item.icon_name" class="icon-preview-small">
                                    <Icon :icon="item.icon_set_prefix + ':' + item.icon_name" />
                                </div>
                            </a-col>
                            <a-col :span="2">
                                <a-button
                                    type="text"
                                    danger
                                    size="small"
                                    @click="removeIconItem(index)"
                                    :disabled="newIconItems.length === 1 && !item.icon_name"
                                >
                                    <template #icon><DeleteOutlined /></template>
                                </a-button>
                            </a-col>
                        </a-row>
                    </div>
                </div>

                <!-- Add More Button -->
                <a-button type="dashed" block @click="addIconItem" class="add-more-btn">
                    <template #icon><PlusOutlined /></template>
                    {{ $t('icon_set.add_another_icon') }}
                </a-button>
            </div>
        </a-modal>
    </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import { Icon, loadIcons } from '@iconify/vue';
import { SearchOutlined, PlusOutlined, CloseOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { useI18n } from 'vue-i18n';

const props = defineProps({
    modelValue: {
        type: String,
        default: ''
    },
    placeholder: {
        type: String,
        default: 'Select icon'
    }
});

const emit = defineEmits(['update:modelValue']);

// i18n
const { t } = useI18n();

// Get axios instance and permissions
const axiosAdmin = window.axiosAdmin;
const { permsArray } = window.__composables.common();

// State
const searchQuery = ref('');
const selectedIcon = ref(props.modelValue);
const modalVisible = ref(false);
const loading = ref(false);
const icons = ref([]);
const iconSets = ref([]);
const iconSetsData = ref({});
const apiLoaded = ref(false);

const activeIconSet = ref('');

// Add Icon Modal State
const addIconModalVisible = ref(false);
const addingIcons = ref(false);
const iconSetOptions = ref([]);
const newIconItems = ref([{ icon_set_prefix: '', icon_name: '' }]);

// Default fallback icon sets (used if API fails or returns empty)
const defaultIconSets = [
    { prefix: 'heroicons', name: 'Heroicons' },
    { prefix: 'mdi', name: 'Material Design' },
    { prefix: 'tabler', name: 'Tabler' },
    { prefix: 'lucide', name: 'Lucide' },
    { prefix: 'ph', name: 'Phosphor' },
];

// Fallback icons for each set
const fallbackIcons = {
    heroicons: [
        'heroicons:home', 'heroicons:user', 'heroicons:cog-6-tooth', 'heroicons:bell',
        'heroicons:calendar', 'heroicons:chart-bar', 'heroicons:check', 'heroicons:x-mark',
        'heroicons:plus', 'heroicons:pencil', 'heroicons:trash', 'heroicons:eye',
        'heroicons:heart', 'heroicons:star', 'heroicons:envelope', 'heroicons:phone',
        'heroicons:map-pin', 'heroicons:shopping-cart', 'heroicons:credit-card', 'heroicons:truck',
        'heroicons:gift', 'heroicons:sun', 'heroicons:moon', 'heroicons:document',
        'heroicons:folder', 'heroicons:photo', 'heroicons:lock-closed', 'heroicons:key',
        'heroicons:arrow-right', 'heroicons:chevron-right', 'heroicons:magnifying-glass',
        'heroicons:bars-3', 'heroicons:squares-2x2', 'heroicons:tag', 'heroicons:bookmark',
        'heroicons:wrench', 'heroicons:light-bulb', 'heroicons:question-mark-circle',
        'heroicons:information-circle', 'heroicons:exclamation-circle', 'heroicons:leaf',
        'heroicons:sparkles', 'heroicons:fire', 'heroicons:bolt', 'heroicons:clock',
        'heroicons:shield-check', 'heroicons:rocket-launch', 'heroicons:globe-alt',
    ],
    mdi: [
        'mdi:home', 'mdi:account', 'mdi:cog', 'mdi:bell', 'mdi:calendar', 'mdi:chart-bar',
        'mdi:check', 'mdi:close', 'mdi:plus', 'mdi:pencil', 'mdi:delete', 'mdi:eye',
        'mdi:heart', 'mdi:star', 'mdi:email', 'mdi:phone', 'mdi:map-marker', 'mdi:cart',
        'mdi:credit-card', 'mdi:truck', 'mdi:gift', 'mdi:weather-sunny', 'mdi:weather-night',
        'mdi:file-document', 'mdi:folder', 'mdi:image', 'mdi:lock', 'mdi:key',
        'mdi:arrow-right', 'mdi:chevron-right', 'mdi:magnify', 'mdi:menu', 'mdi:apps',
        'mdi:tag', 'mdi:bookmark', 'mdi:wrench', 'mdi:lightbulb', 'mdi:help-circle',
        'mdi:information', 'mdi:alert', 'mdi:leaf', 'mdi:shimmer', 'mdi:fire',
    ],
    tabler: [
        'tabler:home', 'tabler:user', 'tabler:settings', 'tabler:bell', 'tabler:calendar',
        'tabler:chart-bar', 'tabler:check', 'tabler:x', 'tabler:plus', 'tabler:pencil',
        'tabler:trash', 'tabler:eye', 'tabler:heart', 'tabler:star', 'tabler:mail',
        'tabler:phone', 'tabler:map-pin', 'tabler:shopping-cart', 'tabler:credit-card',
        'tabler:truck', 'tabler:gift', 'tabler:sun', 'tabler:moon', 'tabler:file',
        'tabler:folder', 'tabler:photo', 'tabler:lock', 'tabler:key', 'tabler:arrow-right',
        'tabler:chevron-right', 'tabler:search', 'tabler:menu-2', 'tabler:grid-dots',
        'tabler:tag', 'tabler:bookmark', 'tabler:tool', 'tabler:bulb', 'tabler:help',
        'tabler:info-circle', 'tabler:alert-triangle', 'tabler:leaf', 'tabler:sparkles',
    ],
    lucide: [
        'lucide:home', 'lucide:user', 'lucide:settings', 'lucide:bell', 'lucide:calendar',
        'lucide:bar-chart', 'lucide:check', 'lucide:x', 'lucide:plus', 'lucide:pencil',
        'lucide:trash-2', 'lucide:eye', 'lucide:heart', 'lucide:star', 'lucide:mail',
        'lucide:phone', 'lucide:map-pin', 'lucide:shopping-cart', 'lucide:credit-card',
        'lucide:truck', 'lucide:gift', 'lucide:sun', 'lucide:moon', 'lucide:file',
        'lucide:folder', 'lucide:image', 'lucide:lock', 'lucide:key', 'lucide:arrow-right',
        'lucide:chevron-right', 'lucide:search', 'lucide:menu', 'lucide:grid',
        'lucide:tag', 'lucide:bookmark', 'lucide:wrench', 'lucide:lightbulb', 'lucide:help-circle',
        'lucide:info', 'lucide:alert-triangle', 'lucide:leaf', 'lucide:sparkles',
    ],
    ph: [
        'ph:house', 'ph:user', 'ph:gear', 'ph:bell', 'ph:calendar', 'ph:chart-bar',
        'ph:check', 'ph:x', 'ph:plus', 'ph:pencil-simple', 'ph:trash', 'ph:eye',
        'ph:heart', 'ph:star', 'ph:envelope', 'ph:phone', 'ph:map-pin', 'ph:shopping-cart',
        'ph:credit-card', 'ph:truck', 'ph:gift', 'ph:sun', 'ph:moon', 'ph:file',
        'ph:folder', 'ph:image', 'ph:lock', 'ph:key', 'ph:arrow-right', 'ph:caret-right',
        'ph:magnifying-glass', 'ph:list', 'ph:squares-four', 'ph:tag', 'ph:bookmark-simple',
        'ph:wrench', 'ph:lightbulb', 'ph:question', 'ph:info', 'ph:warning', 'ph:leaf',
    ],
};

// Computed
const filteredIcons = computed(() => {
    let iconList = icons.value;

    if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase();
        iconList = iconList.filter(icon => icon.toLowerCase().includes(query));
    }

    return iconList;
});

// Methods
const fetchIconSetsFromApi = async () => {
    try {
        const response = await axiosAdmin.get('icons/all');
        // axiosAdmin interceptor returns response.data directly
        const data = response.data || [];

        if (data.length > 0) {
            iconSets.value = data.map(set => ({
                prefix: set.prefix,
                name: set.name,
            }));

            // Store icons data by prefix
            data.forEach(set => {
                iconSetsData.value[set.prefix] = set.icons || [];
            });

            apiLoaded.value = true;

            // Set first icon set as active
            if (iconSets.value.length > 0 && !activeIconSet.value) {
                activeIconSet.value = iconSets.value[0].prefix;
            }
        } else {
            // Use fallback if no data from API
            useFallbackIcons();
        }
    } catch (error) {
        console.error('Error fetching icon sets from API:', error);
        // Use fallback on error
        useFallbackIcons();
    }
};

const useFallbackIcons = () => {
    iconSets.value = defaultIconSets;
    iconSetsData.value = fallbackIcons;
    apiLoaded.value = false;

    if (!activeIconSet.value && iconSets.value.length > 0) {
        activeIconSet.value = iconSets.value[0].prefix;
    }
};

const openModal = async () => {
    modalVisible.value = true;

    // Load icon sets if not already loaded
    if (iconSets.value.length === 0) {
        await fetchIconSetsFromApi();
    }

    // If an icon is selected, activate the tab for its prefix
    if (selectedIcon.value) {
        const prefix = getIconPrefix(selectedIcon.value);
        if (prefix) {
            // Check if this prefix exists in our icon sets
            const setExists = iconSets.value.some(set => set.prefix === prefix);
            if (setExists) {
                activeIconSet.value = prefix;
            }
        }
    }

    // Load icons for active set
    if (activeIconSet.value) {
        loadIconSet(activeIconSet.value);
    }
};

const getIconName = (icon) => {
    const parts = icon.split(':');
    return parts.length > 1 ? parts[1] : icon;
};

const getIconPrefix = (icon) => {
    if (!icon) return '';
    const parts = icon.split(':');
    return parts.length > 1 ? parts[0] : '';
};

const loadIconSet = async (prefix) => {
    loading.value = true;

    try {
        // Get icons from stored data or fallback
        const iconList = iconSetsData.value[prefix] || fallbackIcons[prefix] || [];
        icons.value = iconList;

        if (icons.value.length > 0) {
            await loadIcons(icons.value);
        }
    } catch (error) {
        console.error('Error loading icons:', error);
        icons.value = [];
    } finally {
        loading.value = false;
    }
};

const selectIcon = (icon) => {
    selectedIcon.value = icon;
    emit('update:modelValue', icon);
    modalVisible.value = false;
};

const clearIcon = () => {
    selectedIcon.value = '';
    emit('update:modelValue', '');
};

// Add Icon Modal Methods
const openAddIconModal = () => {
    // Set default icon set from current active tab
    newIconItems.value = [{ icon_set_prefix: activeIconSet.value, icon_name: '' }];

    // Build options from loaded icon sets
    iconSetOptions.value = iconSets.value.map(set => ({
        value: set.prefix,
        label: set.name,
    }));

    addIconModalVisible.value = true;
};

const closeAddIconModal = () => {
    addIconModalVisible.value = false;
    newIconItems.value = [{ icon_set_prefix: '', icon_name: '' }];
};

const addIconItem = () => {
    // Use the same icon set as the first item or active tab
    const defaultPrefix = newIconItems.value[0]?.icon_set_prefix || activeIconSet.value;
    newIconItems.value.push({ icon_set_prefix: defaultPrefix, icon_name: '' });
};

const removeIconItem = (index) => {
    if (newIconItems.value.length > 1) {
        newIconItems.value.splice(index, 1);
    } else {
        // If only one row, just clear it
        newIconItems.value[0].icon_name = '';
    }
};

// Auto-add new row when typing in the last row
const onIconNameInput = (index) => {
    const isLastRow = index === newIconItems.value.length - 1;
    const currentValue = newIconItems.value[index].icon_name;

    if (isLastRow && currentValue && currentValue.trim()) {
        addIconItem();
    }
};

const submitAddIcons = async () => {
    // Filter out empty items
    const validItems = newIconItems.value.filter(
        item => item.icon_set_prefix && item.icon_name?.trim()
    );

    if (validItems.length === 0) {
        message.warning(t('icon_set.please_add_at_least_one_icon'));
        return;
    }

    addingIcons.value = true;

    try {
        const response = await axiosAdmin.post('icons/bulk-add', {
            items: validItems.map(item => ({
                icon_set_prefix: item.icon_set_prefix,
                icon_name: item.icon_name.trim(),
            })),
        });

        const result = response;
        if (result.success) {
            message.success(result.message);

            // Refresh the icon sets data
            await fetchIconSetsFromApi();

            // Reload current icon set to show new icons
            if (activeIconSet.value) {
                await loadIconSet(activeIconSet.value);
            }

            closeAddIconModal();
        } else {
            message.error(result.message || t('icon_set.failed_to_add_icons'));
        }
    } catch (error) {
        console.error('Error adding icons:', error);
        message.error(t('icon_set.failed_to_add_icons'));
    } finally {
        addingIcons.value = false;
    }
};

// Watch for icon set changes
watch(activeIconSet, (newSet) => {
    if (modalVisible.value && newSet) {
        searchQuery.value = '';
        loadIconSet(newSet);
    }
});

// Watch for model value changes from parent
watch(() => props.modelValue, (newValue) => {
    selectedIcon.value = newValue;
});

// Initial load of selected icon if present
onMounted(async () => {
    if (props.modelValue) {
        try {
            await loadIcons([props.modelValue]);
        } catch (error) {
            console.error('Error loading selected icon:', error);
        }
    }
});
</script>

<style scoped>
.icon-picker {
    width: 100%;
}

.icon-picker-trigger {
    display: flex;
    align-items: center;
    justify-content: space-between;
    min-height: 32px;
    padding: 4px 11px;
    border: 1px solid var(--ant-color-border, #d9d9d9);
    border-radius: var(--ant-border-radius, 6px);
    cursor: pointer;
    transition: all 0.2s;
    background: var(--ant-color-bg-container, #fff);
    color: var(--ant-color-text, rgba(0, 0, 0, 0.88));
}

.icon-picker-trigger:hover {
    border-color: var(--ant-color-primary, #1890ff);
}

.selected-icon-display {
    display: flex;
    align-items: center;
    gap: 10px;
    flex: 1;
}

.selected-icon {
    font-size: 20px;
    color: var(--ant-color-primary, #1890ff);
}

.selected-icon-name {
    font-size: 13px;
    color: var(--ant-color-text-secondary, #595959);
}

.placeholder-display {
    display: flex;
    align-items: center;
    gap: 8px;
    color: var(--ant-color-text-quaternary, #bfbfbf);
}

.placeholder-icon {
    font-size: 16px;
}

.clear-btn {
    color: var(--ant-color-text-quaternary, #bfbfbf);
}

.clear-btn:hover {
    color: var(--ant-color-error, #ff4d4f);
}

.icon-header-row {
    display: flex;
    gap: 12px;
    margin-bottom: 16px;
}

.icon-header-row .icon-search-input {
    flex: 1;
    margin-bottom: 0;
}

.icon-set-tabs {
    margin-bottom: 16px;
}

.icon-set-tabs :deep(.ant-tabs-nav) {
    margin-bottom: 0;
}

.icon-grid-loading {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 300px;
}

.icon-grid-container {
    max-height: 400px;
    overflow-y: auto;
    overflow-x: hidden;
}

.icon-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(90px, 1fr));
    gap: 8px;
    width: 100%;
}

.icon-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 12px 8px;
    border-radius: var(--ant-border-radius, 8px);
    cursor: pointer;
    transition: all 0.2s;
    border: 2px solid transparent;
}

.icon-item:hover {
    background-color: var(--ant-color-fill-tertiary, #f5f5f5);
    border-color: var(--ant-color-border, #d9d9d9);
}

.icon-item.selected {
    background-color: var(--ant-color-primary-bg, #e6f7ff);
    border-color: var(--ant-color-primary, #1890ff);
}

.icon-display {
    font-size: 28px;
    color: var(--ant-color-text-secondary, #595959);
    margin-bottom: 4px;
}

.icon-item:hover .icon-display,
.icon-item.selected .icon-display {
    color: var(--ant-color-primary, #1890ff);
}

.icon-name {
    font-size: 11px;
    color: var(--ant-color-text-tertiary, #8c8c8c);
    text-align: center;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.no-results {
    padding: 40px 0;
}

/* Dark mode support */
:global(.dark_theme) .icon-picker-trigger {
    background: #141414;
    border-color: #434343;
    color: rgba(255, 255, 255, 0.85);
}

:global(.dark_theme) .icon-picker-trigger:hover {
    border-color: #177ddc;
}

:global(.dark_theme) .selected-icon {
    color: #177ddc;
}

:global(.dark_theme) .selected-icon-name {
    color: rgba(255, 255, 255, 0.65);
}

:global(.dark_theme) .placeholder-display {
    color: rgba(255, 255, 255, 0.45);
}

:global(.dark_theme) .clear-btn {
    color: rgba(255, 255, 255, 0.45);
}

:global(.dark_theme) .icon-item:hover {
    background-color: #303030;
    border-color: #434343;
}

:global(.dark_theme) .icon-item.selected {
    background-color: #111d2c;
    border-color: #177ddc;
}

:global(.dark_theme) .icon-display {
    color: rgba(255, 255, 255, 0.65);
}

:global(.dark_theme) .icon-item:hover .icon-display,
:global(.dark_theme) .icon-item.selected .icon-display {
    color: #177ddc;
}

:global(.dark_theme) .icon-name {
    color: rgba(255, 255, 255, 0.45);
}

/* Add Icon Modal Styles */
.add-icon-form {
    padding: 0;
}

.add-icon-help {
    color: var(--ant-color-text-secondary, #595959);
    font-size: 13px;
    margin-bottom: 16px;
    padding: 12px;
    background: var(--ant-color-fill-quaternary, #fafafa);
    border-radius: 6px;
}

.add-icon-repeater {
    margin-bottom: 16px;
}

.add-icon-row {
    padding: 12px;
    background: var(--ant-color-fill-quaternary, #fafafa);
    border-radius: 6px;
    margin-bottom: 8px;
}

.add-icon-row:last-child {
    margin-bottom: 0;
}

.icon-preview-small {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    background: var(--ant-color-bg-container, #fff);
    border: 1px solid var(--ant-color-border, #d9d9d9);
    border-radius: 4px;
}

.icon-preview-small svg {
    font-size: 20px;
    color: var(--ant-color-primary, #1890ff);
}

.add-more-btn {
    margin-top: 8px;
}

/* Dark mode for Add Icon Modal */
:global(.dark_theme) .add-icon-help {
    background: #1f1f1f;
    color: rgba(255, 255, 255, 0.65);
}

:global(.dark_theme) .add-icon-row {
    background: #1f1f1f;
}

:global(.dark_theme) .icon-preview-small {
    background: #141414;
    border-color: #434343;
}

:global(.dark_theme) .icon-preview-small svg {
    color: #177ddc;
}
</style>
