<script setup>
    import { computed, onMounted, reactive, ref, watch } from 'vue';
    import { useRoute } from 'vue-router';
    import { useI18n } from 'vue-i18n';
    import { useWorkspaceStore } from '@/features/workspaces/stores/workspaceStore.js';
    import { useContentItemsStore } from '@/features/content/stores/contentItemsStore.js';
    import { useChannelsStore } from '@/features/channels/stores/channelsStore.js';
    import {
        mdiClose,
        mdiFacebook,
        mdiInstagram,
        mdiLinkedin,
        mdiMusicNote,
        mdiPlus,
        mdiReddit,
        mdiWeb,
        mdiYoutube,
    } from '@mdi/js';

    const route = useRoute();
    const { t } = useI18n();
    const workspaceStore = useWorkspaceStore();
    const contentItemsStore = useContentItemsStore();
    const channelsStore = useChannelsStore();

    const isCreateFormVisible = ref(false);
    const formError = ref(null);
    const activeNetwork = ref('Instagram');
    const form = reactive({
        name: '',
        network: 'Instagram',
    });

    const networkOptions = [
        { value: 'Instagram', icon: mdiInstagram },
        { value: 'TikTok', icon: mdiMusicNote },
        { value: 'Facebook', icon: mdiFacebook },
        { value: 'LinkedIn', icon: mdiLinkedin },
        { value: 'YouTube', icon: mdiYoutube },
        { value: 'X', icon: mdiClose },
        { value: 'Reddit', icon: mdiReddit },
        { value: 'Website', icon: mdiWeb },
    ];

    const configuredChannels = computed(() =>
        channelsStore.channels
            .filter(channel => channel.network)
            .map(channel => {
                const metrics = buildMetrics(channel.name);
                const workspace = workspaceStore.workspaces.find(candidate => candidate.id === channel.workspaceId);

                return {
                    ...channel,
                    ...metrics,
                    workspaceName: workspace?.name ?? t('nav.noWorkspace'),
                };
            })
    );

    const channelsForActiveNetwork = computed(() =>
        configuredChannels.value.filter(channel => channel.network === activeNetwork.value)
    );

    function buildMetrics(channelName) {
        const matches = contentItemsStore.items.filter(item =>
            parseTargets(item.publicationTargets).some(target => target.toLowerCase() === channelName.toLowerCase())
        );

        return {
            scheduled: matches.length,
            nextDueDate: matches
                .filter(item => item.dueDate)
                .sort((left, right) => new Date(left.dueDate).getTime() - new Date(right.dueDate).getTime())[0]?.dueDate ?? null,
            readyCount: matches.filter(item => ['Approved', 'Scheduled', 'Published'].includes(item.status)).length,
            blockedCount: matches.filter(item => item.status === 'In approval').length,
        };
    }

    function resetForm() {
        form.name = '';
        form.network = activeNetwork.value;
        formError.value = null;
    }

    function openCreateForm(network = activeNetwork.value) {
        activeNetwork.value = network;
        resetForm();
        form.network = network;
        isCreateFormVisible.value = true;
    }

    async function submitForm() {
        formError.value = null;

        try {
            await channelsStore.createChannel({
                name: form.name,
                network: form.network,
            });
            isCreateFormVisible.value = false;
            resetForm();
        } catch (error) {
            formError.value = error.message ?? t('channels.errors.createFailed');
        }
    }

    function parseTargets(value) {
        return (value ?? '')
            .split(/[,\n]+/)
            .map(target => target.trim())
            .filter(Boolean);
    }

    watch(
        () => route.query.create,
        createValue => {
            if (createValue === 'true') {
                openCreateForm(activeNetwork.value);
            }
        },
        { immediate: true }
    );

    onMounted(() => {
        channelsStore.fetchChannels();
    });
</script>

<template>
    <section class="page-shell">
        <div class="header">
            <h1>{{ t('channels.title') }}</h1>
            <p>{{ t('channels.description') }}</p>
        </div>

        <div class="network-tabs">
            <v-btn variant="text" :ripple="false"
                v-for="network in networkOptions"
                :key="network.value"
                type="button"
                class="network-tab"
                :class="{ active: activeNetwork === network.value }"
                @click="activeNetwork = network.value"
            >
                <v-icon :icon="network.icon" />
                <span>{{ network.value }}</span>
            </v-btn>
        </div>

        <div
            v-if="isCreateFormVisible"
            class="create-panel"
        >
            <div class="panel-header">
                <strong>{{ t('channels.createTitle') }}</strong>
                <span>{{ form.network }}</span>
            </div>

            <div
                v-if="formError"
                class="page-message error"
            >
                {{ formError }}
            </div>

            <div class="form-grid">
                <v-text-field
                    v-model="form.name"
                    :label="t('channels.fields.name')"
                    variant="outlined"
                    hide-details
                />
            </div>

            <div class="panel-actions">
                <v-btn variant="text" :ripple="false"
                    class="secondary"
                    type="button"
                    @click="isCreateFormVisible = false"
                >
                    {{ t('common.cancel') }}
                </v-btn>
                <v-btn variant="text" :ripple="false"
                    class="primary"
                    type="button"
                    :disabled="channelsStore.isCreating"
                    @click="submitForm"
                >
                    {{ channelsStore.isCreating ? t('common.saving') : t('channels.createTitle') }}
                </v-btn>
            </div>
        </div>

        <div
            v-if="channelsStore.isLoading"
            class="page-message"
        >
            {{ t('loading') }}
        </div>

        <div
            v-else-if="channelsStore.error"
            class="page-message error"
        >
            {{ channelsStore.error }}
        </div>

        <div
            v-else-if="channelsForActiveNetwork.length"
            class="channel-grid"
        >
            <article
                v-for="channel in channelsForActiveNetwork"
                :key="channel.id"
                class="channel-card"
            >
                <div class="channel-header">
                    <strong>{{ channel.name }}</strong>
                    <span>{{ channel.workspaceName }}</span>
                </div>

                <div class="channel-metrics">
                    <div>
                        <small>{{ t('channels.metrics.scheduled') }}</small>
                        <strong>{{ channel.scheduled }}</strong>
                    </div>
                    <div>
                        <small>{{ t('channels.metrics.ready') }}</small>
                        <strong>{{ channel.readyCount }}</strong>
                    </div>
                    <div>
                        <small>{{ t('channels.metrics.blocked') }}</small>
                        <strong>{{ channel.blockedCount }}</strong>
                    </div>
                </div>

                <div class="channel-footer">
                    <span>{{ t('channels.nextDue') }}</span>
                    <em>{{ channel.nextDueDate ? new Date(channel.nextDueDate).toLocaleDateString() : t('channels.noScheduled') }}</em>
                </div>
            </article>
        </div>

        <v-btn variant="text" :ripple="false"
            v-else
            type="button"
            class="empty-state"
            @click="openCreateForm(activeNetwork)"
        >
            <v-icon :icon="mdiPlus" />
            <span>{{ t('channels.emptyAction', { network: activeNetwork }) }}</span>
        </v-btn>
    </section>
</template>

<style scoped>
@reference "@/assets/main.css";
    .page-shell {
        @apply mx-auto flex w-full max-w-7xl flex-col gap-6 px-5 py-8 md:px-8;
    }

    .header h1 {
        @apply text-4xl font-black;
        color: var(--app-color-on-surface);
    }

    .header p,
    .network-tab span,
    .channel-header span,
    .channel-footer span,
    .channel-footer em,
    .channel-metrics small,
    .page-message,
    .empty-state span {
        @apply text-sm leading-6 not-italic;
        color: var(--app-text-muted);
    }

    .network-tabs {
        @apply flex flex-wrap gap-3;
    }

    .network-tab {
        @apply inline-flex items-center gap-2 rounded-full border px-4 py-3 transition;
        border-color: var(--app-border-subtle);
        background: rgba(255, 255, 255, 0.95);
        color: var(--app-text-muted);
    }

    .network-tab.active,
    .network-tab:hover {
        border-color: rgba(255, 138, 61, 0.28);
        background: rgba(255, 138, 61, 0.1);
        color: var(--app-color-on-surface);
    }

    .channel-grid {
        @apply grid gap-4 md:grid-cols-2 xl:grid-cols-3;
    }

    .channel-card,
    .create-panel,
    .empty-state {
        @apply flex flex-col gap-5 rounded-[1.5rem] border p-5;
        background: rgba(255, 255, 255, 0.92);
        border-color: var(--app-border-subtle);
    }

    .empty-state {
        @apply items-center justify-center text-center;
    }

    .create-button,
    .primary,
    .secondary {
        @apply inline-flex items-center justify-center rounded-full px-5 py-3 text-sm font-bold transition;
    }

    .primary {
        background: var(--app-color-on-surface);
        color: var(--app-color-on-primary);
    }

    .secondary {
        background: var(--app-control-hover);
        color: var(--app-color-on-surface);
    }

    .panel-header {
        @apply flex items-center justify-between gap-4;
    }

    .panel-header strong,
    .field,
    .channel-header strong,
    .channel-metrics strong {
        color: var(--app-color-on-surface);
    }

    .panel-header span {
        @apply text-sm font-semibold;
        color: var(--app-text-muted);
    }

    .form-grid {
        @apply grid gap-4;
    }

    .field {
        @apply flex flex-col gap-2 text-sm font-semibold;
    }

    .field input {
        @apply rounded-2xl border px-4 py-3 text-sm;
        border-color: var(--app-border-subtle);
        background: rgba(255, 255, 255, 0.95);
    }

    .panel-actions {
        @apply flex justify-end gap-3;
    }

    .channel-header,
    .channel-footer {
        @apply flex items-center justify-between gap-4;
    }

    .channel-header strong {
        @apply text-xl font-black;
    }

    .channel-metrics {
        @apply grid grid-cols-3 gap-3 rounded-[1rem] border p-4;
        background: var(--app-color-on-primary);
        border-color: var(--app-border-subtle);
    }

    .channel-metrics div {
        @apply flex flex-col gap-1;
    }

    .channel-metrics strong {
        @apply text-2xl font-black;
    }

    .page-message {
        @apply rounded-[1.25rem] border p-4 font-medium;
        background: rgba(255, 255, 255, 0.84);
        border-color: var(--app-border-subtle);
    }

    .page-message.error {
        color: var(--app-danger-muted);
    }
</style>
