<script setup lang="ts">
import { Head, usePage } from '@inertiajs/vue3';
import { ComputedRef } from 'vue';
import { mdiAlertBoxOutline, mdiGlasses, mdiAccountArrowLeft, mdiChevronDown, mdiChevronUp } from '@mdi/js';
import { computed, ref, onMounted } from 'vue';
import LayoutAuthenticated from '@/Layouts/LayoutAuthenticated.vue';
import SectionMain from '@/Components/SectionMain.vue';
import BaseButton from '@/Components/BaseButton.vue';
import BaseIcon from '@/Components/BaseIcon.vue';
import CardBox from '@/Components/CardBox.vue';
import BaseButtons from '@/Components/BaseButtons.vue';
import NotificationBar from '@/Components/NotificationBar.vue';
import Pagination from '@/Components/Admin/Pagination.vue';
import { stardust } from '@eidellev/adonis-stardust/client';

const props = defineProps({
    datasets: {
        type: Object,
        default: () => ({}),
    },
    filters: {
        type: Object,
        default: () => ({}),
    },
    can: {
        type: Object,
        default: () => ({}),
    },
});

const flash: ComputedRef<any> = computed(() => {
    return usePage().props.flash;
});

// Legend visibility state with localStorage persistence
const showLegend = ref(true);

onMounted(() => {
    const savedState = localStorage.getItem('reviewerDatasetLegendVisible');
    if (savedState !== null) {
        showLegend.value = savedState === 'true';
    }
});

const toggleLegend = () => {
    showLegend.value = !showLegend.value;
    localStorage.setItem('reviewerDatasetLegendVisible', String(showLegend.value));
};

const getRowClass = (dataset) => {
    // Return Tailwind classes that will be defined in tailwind.config
    const stateClasses = {
        'approved': 'bg-approved dark:bg-approved-dark',       
        'rejected_reviewer': 'bg-rejected-reviewer dark:bg-rejected-reviewer-dark',
        'rejected_to_reviewer': 'bg-rejected-reviewer dark:bg-rejected-reviewer-dark',
        'reviewed': 'bg-reviewed dark:bg-reviewed-dark',       
    };
    
    return stateClasses[dataset.server_state] || '';
};

// Method to get state badge color
const getStateColor = (state: string) => {
    const stateColors = {
        'inprogress': 'bg-sky-200 text-sky-900 dark:bg-sky-900 dark:text-sky-200',
        'released': 'bg-blue-300 text-blue-900 dark:bg-blue-900 dark:text-blue-200',
        'editor_accepted': 'bg-teal-200 text-teal-900 dark:bg-teal-900 dark:text-teal-200',
        'rejected_reviewer': 'bg-amber-200 text-amber-900 dark:bg-amber-900 dark:text-amber-200',
        'rejected_to_reviewer': 'bg-yellow-200 text-yellow-900 dark:bg-yellow-900 dark:text-yellow-200', 
         'rejected_editor': 'bg-rose-300 text-rose-900 dark:bg-rose-900 dark:text-rose-200',
        'reviewed': 'bg-yellow-300 text-yellow-900 dark:bg-yellow-900 dark:text-yellow-200',
        'published': 'bg-green-300 text-green-900 dark:bg-green-900 dark:text-green-200',
        'approved': 'bg-cyan-200 text-cyan-900 dark:bg-cyan-900 dark:text-cyan-200',
        'reviewer_accepted': 'bg-lime-200 text-lime-900 dark:bg-lime-900 dark:text-lime-200',
    };
    return stateColors[state] || 'bg-sky-200 text-sky-900 dark:bg-sky-900 dark:text-sky-200';
};



const truncateTitle = (text: string, length = 50) => {
    if (!text) return '';
    return text.length > length ? text.substring(0, length) + '...' : text;
};

// Dynamic legend definitions
const datasetStates = [
    { key: 'approved', label: 'Ready for Review' },
    { key: 'rejected_to_reviewer', label: 'Rejected To Reviewer' }   
];
const getLabel = (key: string) => {
  return datasetStates.find(s => s.key === key)?.label || 'Unknown'
}

const availableActions = [
    { icon: mdiGlasses, label: 'View / Review', color: 'text-blue-500' },
    { icon: mdiAccountArrowLeft, label: 'Reject to Editor', color: 'text-yellow-600' },
];

</script>

<template>
    <LayoutAuthenticated>
        <Head title="Reviewer Datasets" />
        <SectionMain>
            <NotificationBar v-if="flash.message" color="success" :icon="mdiAlertBoxOutline">
                {{ flash.message }}
            </NotificationBar>
            <NotificationBar v-if="flash.warning" color="warning" :icon="mdiAlertBoxOutline">
                {{ flash.warning }}
            </NotificationBar>
            <NotificationBar v-if="flash.error" color="danger" :icon="mdiAlertBoxOutline">
                {{ flash.error }}
            </NotificationBar>

            <!-- Legend -->
            <CardBox class="mb-4">
                <!-- Legend Header with Toggle -->
                <!-- <div 
                    class="flex items-center justify-between cursor-pointer select-none p-4 border-b border-gray-200 dark:border-slate-700 hover:bg-gray-50 dark:hover:bg-slate-800/50 transition-colors"
                    @click="toggleLegend"
                >
                    <div class="flex items-center gap-2">
                        <svg class="w-5 h-5 text-gray-600 dark:text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                        <h3 class="text-sm font-semibold text-gray-700 dark:text-gray-300">
                            Legend - States & Actions
                        </h3>
                    </div>
                    <div class="flex items-center gap-2">
                        <span class="text-xs text-gray-500 dark:text-gray-400">
                            {{ showLegend ? 'Click to hide' : 'Click to show' }}
                        </span>
                        <BaseIcon 
                            :path="showLegend ? mdiChevronUp : mdiChevronDown" 
                            :size="20" 
                            class="text-gray-500 dark:text-gray-400 transition-transform"
                        />
                    </div>
                </div> -->

                <!-- Collapsible Legend Content -->
                <transition
                    enter-active-class="transition-all duration-300 ease-out"
                    enter-from-class="max-h-0 opacity-0"
                    enter-to-class="max-h-96 opacity-100"
                    leave-active-class="transition-all duration-300 ease-in"
                    leave-from-class="max-h-96 opacity-100"
                    leave-to-class="max-h-0 opacity-0"
                >
                    <div v-show="showLegend" class="overflow-hidden">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 p-4">
                            <!-- State Colors Legend -->
                            <div>
                                <h3 class="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3 flex items-center gap-2">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" />
                                    </svg>
                                    Dataset States
                                </h3>
                                <div class="grid grid-cols-2 gap-2 text-xs">
                                    <div v-for="state in datasetStates" :key="state.key" class="flex items-center gap-2">
                                        <span class="inline-flex items-center px-2 py-0.5 rounded-full" :class="getStateColor(state.key)">
                                            {{ state.label }}
                                        </span>
                                    </div>
                                </div>
                            </div>

                            <!-- Actions Legend -->
                            <div>
                                <h3 class="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3 flex items-center gap-2">
                                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
                                    </svg>
                                    Available Actions
                                </h3>
                                <div class="grid grid-cols-1 gap-1.5 text-xs">
                                    <div v-for="action in availableActions" :key="action.label" class="flex items-center gap-2">
                                        <BaseIcon :path="action.icon" :size="16" :class="action.color" />
                                        <span class="text-gray-700 dark:text-gray-300">{{ action.label }}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </transition>
            </CardBox>

            <!-- table -->
            <CardBox class="mb-6" has-table>
                <div v-if="props.datasets.data.length > 0">
                    <table>
                        <thead>
                            <tr>
                                <th>Title</th>
                                <th>ID</th>
                                <th>State</th>
                                <th>Editor</th>
                                <th>Remaining Time</th>
                                <th v-if="can.edit || can.delete">Actions</th>
                            </tr>
                        </thead>

                        <tbody>
                            <tr v-for="dataset in props.datasets.data" :key="dataset.id"
                                :class="['hover:bg-gray-50 dark:hover:bg-slate-800 transition-colors', getRowClass(dataset)]">
                                <td data-label="Title">
                                    <div class="max-w-xs">
                                        <span 
                                            class="text-gray-700 dark:text-gray-300 text-sm font-medium"
                                            :title="dataset.main_title"
                                        >
                                            {{ truncateTitle(dataset.main_title) }}
                                        </span>
                                    </div>
                                </td>
                                <td data-label="ID">
                                    <span class="text-sm text-gray-700 dark:text-gray-300 font-mono">
                                        {{ dataset.id }}
                                    </span>
                                </td>
                                <td data-label="State">
                                    <div class="flex items-center gap-2">
                                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium capitalize"
                                            :class="getStateColor(dataset.server_state)">
                                            {{ getLabel(dataset.server_state) }}
                                        </span>
                                        <div v-if="dataset.server_state === 'rejected_to_reviewer' && dataset.reject_editor_note"
                                            class="relative group">
                                            <button
                                                class="w-5 h-5 rounded-full bg-gray-200 dark:bg-slate-700 text-gray-600 dark:text-gray-300 text-xs flex items-center justify-center focus:outline-none hover:bg-gray-300 dark:hover:bg-slate-600 transition-colors">
                                                i
                                            </button>
                                            <div
                                                class="absolute left-0 top-full mt-1 w-64 bg-white dark:bg-slate-800 shadow-lg rounded-md p-3 text-xs text-left z-50 transform scale-0 origin-top-left transition-transform duration-100 group-hover:scale-100 border border-gray-200 dark:border-slate-700">
                                                <p class="text-gray-700 dark:text-gray-300 max-h-40 overflow-y-auto overflow-x-hidden whitespace-normal break-words">
                                                    {{ dataset.reject_editor_note }}
                                                </p>
                                                <div class="absolute -top-1 left-1 w-2 h-2 bg-white dark:bg-slate-800 border-l border-t border-gray-200 dark:border-slate-700 transform rotate-45">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </td>

                                <td data-label="Editor">
                                    <span class="text-sm text-gray-700 dark:text-gray-300">
                                        {{ dataset.editor?.login || '—' }}
                                    </span>
                                </td>

                                <td data-label="Remaining Time">
                                    <span class="text-sm text-gray-600 dark:text-gray-400" :title="dataset.remaining_time">
                                        {{ dataset.remaining_time }} days
                                    </span>
                                </td>
                                <td v-if="can.reject" class="before:hidden lg:w-1 whitespace-nowrap">
                                    <BaseButtons type="justify-start lg:justify-end" no-wrap>
                                        <BaseButton 
                                            v-if="can.reject && (dataset.server_state == 'approved' || dataset.server_state == 'rejected_to_reviewer')"
                                            :route-name="stardust.route('reviewer.dataset.review', [dataset.id])"
                                            color="info" :icon="mdiGlasses" small 
                                            title="View / Review" />
                                        
                                        <BaseButton
                                            v-if="can.reject && (dataset.server_state == 'approved' || dataset.server_state == 'rejected_to_reviewer')"
                                            :route-name="stardust.route('reviewer.dataset.reject', [dataset.id])"
                                            color="warning" :icon="mdiAccountArrowLeft" small 
                                            title="Reject to Editor" />
                                    </BaseButtons>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div v-else>
                    <div class="text-center py-12">
                        <div class="flex flex-col items-center justify-center text-gray-500 dark:text-gray-400">
                            <p class="text-lg font-medium mb-2">No datasets found</p>
                            <p class="text-sm">Datasets will appear here when they are ready for review</p>
                        </div>
                    </div>
                </div>

                <div class="py-4">
                    <Pagination v-bind:data="datasets.meta" />
                </div>
            </CardBox>
        </SectionMain>
    </LayoutAuthenticated>
</template>

<style scoped lang="css">
/* Background colors are now defined in tailwind.config.js */
/* .bg-approved {
    @apply bg-approved dark:bg-approved-dark;
}

.bg-rejected-reviewer {
    @apply bg-rejected-reviewer dark:bg-rejected-reviewer-dark;
}

.bg-reviewed {
    @apply bg-reviewed dark:bg-reviewed-dark;
}

.bg-released {
    @apply bg-released dark:bg-released-dark;
}

.bg-published {
    @apply bg-published dark:bg-published-dark;
} */
</style>