<template>
    <div class="list-directory">
        <!-- Header -->
        <div class="directory-header">
            <div class="header-content">
                <Heading :level="2" class="page-title">Your Lists</Heading>
                <div class="header-actions">
                    <Button variant="outline" color="neutral" size="sm" @click="toggleViewMode">
                        <template #icon-left>
                            <BaseIcon :name="viewMode === 'grid' ? 'heroicons:view-list' : 'heroicons:view-grid'" />
                        </template>
                        {{ viewMode === 'grid' ? 'List' : 'Grid' }}
                    </Button>
                    <Button variant="solid" color="primary" @click="showCreateModal = true">
                        <template #icon-left>
                            <BaseIcon name="heroicons:plus-20-solid" />
                        </template>
                        New List
                    </Button>
                </div>
            </div>

            <!-- Filters -->
            <div class="filters-section">
                <TabGroup :selectedIndex="selectedFilter" @change="setSelectedFilter">
                    <TabList class="filter-tabs">
                        <Tab v-for="filter in filters" :key="filter.id" v-slot="{ selected }" as="template">
                            <button :class="['filter-tab', { 'selected': selected }]">
                                <BaseIcon :name="filter.icon" class="filter-icon" />
                                <span class="filter-label">{{ filter.label }}</span>
                                <span v-if="filter.count > 0" class="filter-count">{{ filter.count }}</span>
                            </button>
                        </Tab>
                    </TabList>
                </TabGroup>
            </div>
        </div>

        <!-- Loading State -->
        <div v-if="isLoading" class="loading-state">
            <Spinner size="lg" />
            <span class="loading-text">Loading your lists...</span>
        </div>

        <!-- Error State -->
        <Alert v-else-if="error" type="error" :title="'Failed to load lists'" :message="error" class="mb-6" />

        <!-- Lists Content -->
        <div v-else class="lists-content">
            <!-- Pinned Shopping List -->
            <div v-if="pinnedShoppingList" class="pinned-section">
                <div class="section-header">
                    <BaseIcon name="heroicons:pin-20-solid"
                        class="section-icon text-primary-600 dark:text-primary-400" />
                    <h3 class="section-title">Pinned List</h3>
                </div>
                <ListCard :list="pinnedShoppingList" :view-mode="viewMode" :is-pinned="true" @open="handleOpenList"
                    @edit="handleEditList" @archive="handleArchiveList" @delete="handleDeleteList" />
            </div>

            <!-- Main Lists Section -->
            <div v-if="activeLists.length > 0" class="active-section">
                <div class="section-header">
                    <BaseIcon :name="currentFilter.icon" class="section-icon" />
                    <h3 class="section-title">{{ currentFilter.label }}</h3>
                    <span class="section-count">{{ activeLists.length }}</span>
                </div>

                <div :class="viewModeClasses">
                    <TransitionGroup name="list-item" tag="div" class="lists-container">
                        <ListCard v-for="list in activeLists" :key="list.id" :list="list" :view-mode="viewMode"
                            @open="handleOpenList" @edit="handleEditList" @archive="handleArchiveList"
                            @delete="handleDeleteList" class="list-card-item" />
                    </TransitionGroup>
                </div>
            </div>

            <!-- Smart Suggestions -->
            <div v-if="suggestedLists.length > 0 && selectedFilter !== 3" class="suggestions-section">
                <div class="section-header">
                    <BaseIcon name="heroicons:light-bulb-20-solid" class="section-icon text-warning-500" />
                    <h3 class="section-title">Start a New List</h3>
                </div>

                <div class="suggestions-grid">
                    <Card v-for="suggestion in suggestedLists" :key="suggestion.id" variant="elevated" padding="md"
                        :interactive="true" class="suggestion-card" @click="handleCreateFromSuggestion(suggestion)">
                        <div class="suggestion-content">
                            <div class="suggestion-icon-wrapper">
                                <BaseIcon :name="suggestion.icon" class="suggestion-icon" />
                            </div>
                            <div class="suggestion-text">
                                <h4 class="suggestion-title">{{ suggestion.title }}</h4>
                                <p class="suggestion-description">{{ suggestion.description }}</p>
                            </div>
                            <BaseIcon name="heroicons:chevron-right-20-solid" class="suggestion-arrow" />
                        </div>
                    </Card>
                </div>
            </div>

            <!-- Empty State -->
            <div v-if="activeLists.length === 0 && !pinnedShoppingList" class="empty-state">
                <div class="empty-icon-wrapper">
                    <BaseIcon name="heroicons:clipboard-document-list-20-solid" class="empty-icon" />
                </div>
                <h3 class="empty-title">{{ currentFilter.emptyTitle }}</h3>
                <p class="empty-description">{{ currentFilter.emptyDescription }}</p>
                <Button variant="solid" color="primary" @click="showCreateModal = true">
                    <template #icon-left>
                        <BaseIcon name="heroicons:plus-20-solid" />
                    </template>
                    Create Your First List
                </Button>
            </div>
        </div>

        <!-- Create List Modal -->
        <CreateListModal v-model="showCreateModal" @created="handleListCreated" :template="creationTemplate" />
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { TabGroup, TabList, Tab } from '@headlessui/vue'
import { useNotificationStore } from '@/stores/notifications'
import { useStorage } from '@vueuse/core'
import type { List } from '@/types/list'
import { formatDistanceToNow, parseISO } from 'date-fns'
import { apiClient, API_ENDPOINTS } from '@/services/api'

// UI Components
import { Heading, Button, Spinner, Alert, Card } from '@/components/ui'
import ListCard from '@/components/ListCard.vue'
import CreateListModal from './CreateListModal.vue'
import BaseIcon from '@/components/BaseIcon.vue'

interface ListFilter {
    id: string
    label: string
    icon: string
    count: number
    emptyTitle: string
    emptyDescription: string
    filter: (lists: List[]) => List[]
}

interface ListSuggestion {
    id: string
    title: string
    description: string
    icon: string
    template: {
        name: string
        description: string
        type: 'shopping' | 'todo' | 'custom'
        items?: { name: string }[]
    }
}

const router = useRouter()
const notificationStore = useNotificationStore()

// Local state for managing lists directly
const allLists = ref<List[]>([])
const isLoading = ref(true)
const error = ref<string | null>(null)
const selectedFilter = ref(0)
const viewMode = useStorage<'grid' | 'list'>('list-directory-view', 'grid')
const showCreateModal = ref(false)
const creationTemplate = ref<ListSuggestion['template'] | null>(null)

// --- API Actions ---
async function fetchLists() {
    isLoading.value = true
    error.value = null
    try {
        const response = await apiClient.get(API_ENDPOINTS.LISTS.BASE)
        allLists.value = response.data
    } catch (err: any) {
        error.value = err.response?.data?.detail || 'Failed to load lists.'
        notificationStore.addNotification({
            type: 'error',
            message: 'Could not fetch your lists. Please try again.'
        })
    } finally {
        isLoading.value = false
    }
}

async function archiveList(list: List) {
    const isArchiving = !list.archived_at
    const originalStatus = list.archived_at
    list.archived_at = isArchiving ? new Date().toISOString() : null

    try {
        if (isArchiving) {
            await apiClient.post(API_ENDPOINTS.LISTS.ARCHIVE(String(list.id)))
        } else {
            await apiClient.post(API_ENDPOINTS.LISTS.UNARCHIVE(String(list.id)))
        }
        notificationStore.addNotification({
            type: 'success',
            message: `"${list.name}" ${isArchiving ? 'archived' : 'unarchived'}.`
        })
    } catch (err) {
        list.archived_at = originalStatus // Rollback on error
        notificationStore.addNotification({
            type: 'error',
            message: `Failed to ${isArchiving ? 'archive' : 'unarchive'} list.`
        })
    }
}

async function deleteList(list: List) {
    if (!confirm(`Are you sure you want to permanently delete "${list.name}"? This action cannot be undone.`)) {
        return
    }

    const originalLists = [...allLists.value]
    allLists.value = allLists.value.filter(l => l.id !== list.id)

    try {
        await apiClient.delete(API_ENDPOINTS.LISTS.BY_ID(String(list.id)))
        notificationStore.addNotification({
            type: 'success',
            message: `"${list.name}" was permanently deleted.`
        })
    } catch (err) {
        allLists.value = originalLists // Rollback on error
        notificationStore.addNotification({
            type: 'error',
            message: 'Failed to delete list.'
        })
    }
}


// Computed properties
const pinnedShoppingList = computed(() =>
    allLists.value.find((list: List) =>
        list.type === 'shopping' &&
        !list.archived_at
    )
)

const filters = computed((): ListFilter[] => [
    {
        id: 'recent',
        label: 'Recent',
        icon: 'heroicons:clock-20-solid',
        count: recentLists.value.length,
        emptyTitle: 'No recent activity',
        emptyDescription: 'Lists you\'ve used recently will appear here.',
        filter: (lists: List[]) => recentLists.value
    },
    {
        id: 'active',
        label: 'Active',
        icon: 'heroicons:fire-20-solid',
        count: activeLists.value.length,
        emptyTitle: 'No active lists',
        emptyDescription: 'Create a list to start organizing your tasks.',
        filter: (lists: List[]) => lists.filter((list: List) => !list.archived_at && hasRecentActivity(list))
    },
    {
        id: 'all',
        label: 'All Lists',
        icon: 'heroicons:list-bullet-20-solid',
        count: allLists.value.filter((list: List) => !list.archived_at).length,
        emptyTitle: 'No lists yet',
        emptyDescription: 'Create your first list to get started.',
        filter: (lists: List[]) => lists.filter((list: List) => !list.archived_at && list.id !== pinnedShoppingList.value?.id)
    },
    {
        id: 'archived',
        label: 'Archived',
        icon: 'heroicons:archive-box-20-solid',
        count: archivedLists.value.length,
        emptyTitle: 'No archived lists',
        emptyDescription: 'Archived lists will appear here.',
        filter: (lists: List[]) => archivedLists.value
    }
])

const currentFilter = computed(() => filters.value[selectedFilter.value] || filters.value[0])

const recentLists = computed(() =>
    allLists.value
        .filter((list: List) => !list.archived_at && list.id !== pinnedShoppingList.value?.id)
        .filter((list: List) => hasRecentActivity(list))
        .sort((a: List, b: List) => new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime())
        .slice(0, 10)
)

const activeLists = computed(() => {
    const filtered = currentFilter.value.filter(allLists.value)
    return filtered.filter((list: List) => list.id !== pinnedShoppingList.value?.id)
})

const archivedLists = computed(() =>
    allLists.value.filter((list: List) => list.archived_at)
)

const viewModeClasses = computed(() => ({
    'lists-grid': viewMode.value === 'grid',
    'lists-list': viewMode.value === 'list'
}))

// List suggestions based on user patterns
const suggestedLists = computed((): ListSuggestion[] => {
    if (allLists.value.length >= 5) return [] // Don't show suggestions if user already has many lists

    const suggestions: ListSuggestion[] = [
        {
            id: 'weekly-shopping',
            title: 'Weekly Groceries',
            description: 'Organize your grocery shopping with smart categorization.',
            icon: 'heroicons:shopping-cart-20-solid',
            template: {
                name: 'Weekly Groceries',
                description: 'Smart grocery list with categorization',
                type: 'shopping',
                items: [{ name: 'Milk' }, { name: 'Bread' }, { name: 'Eggs' }, { name: 'Fruits & Vegetables' }]
            }
        },
        {
            id: 'weekend-tasks',
            title: 'Weekend Tasks',
            description: 'Keep track of things to do on the weekend.',
            icon: 'heroicons:calendar-days-20-solid',
            template: {
                name: 'Weekend Tasks',
                description: 'Tasks and activities for the weekend',
                type: 'todo'
            }
        },
        {
            id: 'meal-planning',
            title: 'Meal Planning',
            description: 'Plan your meals and ingredients for the week.',
            icon: 'heroicons:cake-20-solid',
            template: {
                name: 'Weekly Meal Plan',
                description: 'Plan meals and required ingredients',
                type: 'custom',
                items: [{ name: 'Monday Dinner' }, { name: 'Tuesday Lunch' }, { name: 'Wednesday Dinner' }]
            }
        }
    ]

    return suggestions.filter(suggestion => {
        // Don't suggest if similar list already exists
        return !allLists.value.some((list: List) =>
            list.name.toLowerCase().includes(suggestion.template.name.toLowerCase().split(' ')[0])
        )
    })
})

// Helper functions
const hasRecentActivity = (list: List): boolean => {
    const threeDaysAgo = new Date()
    threeDaysAgo.setDate(threeDaysAgo.getDate() - 3)

    const listDate = new Date(list.updated_at)
    return listDate > threeDaysAgo
}

// Actions
const toggleViewMode = () => {
    viewMode.value = viewMode.value === 'grid' ? 'list' : 'grid'
}

const setSelectedFilter = (index: number) => {
    selectedFilter.value = index
}

const handleOpenList = (list: List) => {
    router.push(`/lists/${list.id}`)
}

const handleEditList = (list: List) => {
    // This could open the CreateListModal in "edit mode"
    notificationStore.addNotification({
        type: 'info',
        message: 'Edit functionality coming soon!'
    })
}

const handleArchiveList = async (list: List) => {
    await archiveList(list)
}

const handleDeleteList = async (list: List) => {
    await deleteList(list)
}

const handleCreateFromSuggestion = (suggestion: ListSuggestion) => {
    creationTemplate.value = suggestion.template
    showCreateModal.value = true
}

const handleListCreated = (newList: List) => {
    notificationStore.addNotification({
        type: 'success',
        message: `"${newList.name}" created successfully!`
    })

    // Add the new list to our local state and navigate
    allLists.value.unshift(newList)
    router.push(`/lists/${newList.id}`)
}

// Lifecycle
onMounted(fetchLists)

</script>

<style scoped>
.list-directory {
    @apply space-y-6;
}

.directory-header {
    @apply space-y-4;
}

.header-content {
    @apply flex items-center justify-between;
}

.page-title {
    @apply text-2xl font-bold text-neutral-900 dark:text-neutral-100;
}

.header-actions {
    @apply flex items-center gap-2;
}

.filters-section {
    @apply border-b border-neutral-200 dark:border-neutral-700;
}

.filter-tabs {
    @apply flex items-center gap-2 overflow-x-auto pb-2;
}

.filter-tab {
    @apply flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm font-medium transition-all duration-micro;
    @apply text-text-secondary hover:text-text-primary;
    @apply hover:bg-surface-hover;
    @apply whitespace-nowrap cursor-pointer;
}

.filter-tab.selected {
    @apply bg-primary-100 text-primary-700 dark:bg-primary-900/50 dark:text-primary-300;
    @apply hover:bg-primary-100/80;
}

.filter-icon {
    @apply w-5 h-5;
}

.filter-label {
    @apply font-semibold;
}

.filter-count {
    @apply bg-neutral-200 dark:bg-neutral-700 text-neutral-600 dark:text-neutral-300 px-2 py-0.5 rounded-full text-xs font-semibold;
}

.filter-tab.selected .filter-count {
    @apply bg-primary-200 text-primary-800 dark:bg-primary-500/50 dark:text-primary-200;
}

.loading-state {
    @apply flex flex-col items-center justify-center py-12 space-y-4;
}

.loading-text {
    @apply text-neutral-600 dark:text-neutral-400;
}

.lists-content {
    @apply space-y-8;
}

.pinned-section,
.active-section,
.suggestions-section {
    @apply space-y-4;
}

.section-header {
    @apply flex items-center gap-2;
    @apply mb-3;
}

.section-icon {
    @apply w-5 h-5 text-text-secondary;
}

.section-title {
    @apply text-lg font-semibold text-text-primary;
}

.section-count {
    @apply ml-auto bg-neutral-100 dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300 px-3 py-1 rounded-full text-sm font-medium;
}

.lists-grid {
    @apply grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4;
}

.lists-list {
    @apply space-y-3;
}

.lists-container {
    @apply contents;
}

.suggestions-grid {
    @apply grid grid-cols-1 md:grid-cols-2 gap-4;
}

.suggestion-card {
    @apply transition-all duration-micro;
}

.suggestion-content {
    @apply flex items-center gap-4;
}

.suggestion-icon-wrapper {
    @apply w-10 h-10 bg-primary-100 dark:bg-primary-900/50 rounded-lg flex items-center justify-center flex-shrink-0;
}

.suggestion-icon {
    @apply w-5 h-5 text-primary-600 dark:text-primary-400;
}

.suggestion-text {
    @apply flex-1 min-w-0;
}

.suggestion-title {
    @apply font-semibold text-text-primary;
}

.suggestion-description {
    @apply text-sm text-text-secondary mt-0.5;
}

.suggestion-arrow {
    @apply w-5 h-5 text-text-tertiary transition-transform duration-micro;
    @apply group-hover:translate-x-1;
}

.empty-state {
    @apply flex flex-col items-center justify-center py-16 px-6 space-y-4 text-center;
    @apply bg-surface-soft rounded-lg;
}

.empty-icon-wrapper {
    @apply w-16 h-16 bg-primary-100 dark:bg-primary-900/50 rounded-full flex items-center justify-center;
}

.empty-icon {
    @apply w-8 h-8 text-primary-600 dark:text-primary-400;
}

.empty-title {
    @apply text-xl font-semibold text-text-primary;
}

.empty-description {
    @apply text-text-secondary max-w-md;
}

/* List item animations */
.list-item-enter-active,
.list-item-leave-active {
    @apply transition-all duration-medium ease-medium;
}

.list-item-enter-from {
    @apply opacity-0 scale-95 translate-y-2;
}

.list-item-leave-to {
    @apply opacity-0 scale-95 translate-y-2;
}

.list-item-move {
    @apply transition-transform duration-medium ease-medium;
}
</style>