// index.ts
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { useToolbarStore } from '@/stores/toolbar-store'
import { useSpaceStore } from '@/stores/spaceStore'
import CategoryCreateUpdate from "@/components/settings/CategoryCreateUpdate.vue";
import DashboardView from "@/components/dashboard/DashboardView.vue";
import RecurrentyCreateUpdate from "@/components/settings/RecurrentyCreateUpdate.vue";
import TransactionList from "@/components/transactions/TransactionList.vue";
import LoginPage from "@/components/auth/LoginPage.vue";
import TransactionCreateUpdate from "@/components/transactions/TransactionCreateUpdate.vue";
import TargetList from "@/components/targets/TargetList.vue";

// 📝 Расширяем тип меты роутов (типобезопасный toolbar, requiresAuth, guestOnly)
declare module 'vue-router' {
    interface RouteMeta {
        requiresAuth?: boolean
        guestOnly?: boolean
        toolbar?: import('@/stores/toolbar-store').ToolbarConfig,
        navStack: string,
        title: string
    }
}

// ⚙️ Ленивая загрузка компонентов (code-splitting)
const SettingsList = () => import('@/components/settings/SettingsList.vue')
const CategoriesList = () => import('@/components/settings/CategoriesList.vue')
const AnalyticsView = () => import('@/views/AnalyticsView.vue')
const RecurrentsList = () => import('@/components/settings/RecurrentsList.vue')
const SpaceSettings = () => import('@/components/settings/SpaceSettings.vue')
const NotificationSettings = () => import('@/components/settings/NotificationSettings.vue')

// Имена роутов для автокомплита и навигации
export const RouteName = {
    Login: 'login',
    Dashboard: 'dashboard',
    Analytics: 'analytics',
    TransactionList: 'transaction-list',
    TransactionCreate: 'transaction-create',
    TransactionUpdate: 'transaction-update',
    TargetList: 'target-list',
    TargetCreate: 'target-create',
    TargetUpdate: 'target-update',
    SettingsList: 'settings-list',
    CategoriesList: 'categories-list',
    CategoryCreate: 'category-create',
    CategoryUpdate: 'category-update',
    RecurrentsList: 'recurrents-list',
    RecurrentCreate: 'recurrent-create',
    RecurrentUpdate: 'recurrent-update',
    SpaceSettings: 'space-settings',
    NotificationSettings: 'notification-settings',
} as const

export type RouteName = typeof RouteName[keyof typeof RouteName]

const routes: RouteRecordRaw[] = [
    { path: '/login', name: RouteName.Login, component: LoginPage, meta: { requiresAuth: false, navStack: 'auth', title: 'Login' } },
    {
        path: '/',
        name: RouteName.Dashboard,
        component: DashboardView,
        meta: { requiresAuth: true, navStack: 'dashboard', title: "Home" }
    },
    {
        path: '/analytics',
        name: RouteName.Analytics,
        component: AnalyticsView,
        meta: { requiresAuth: true, navStack: 'analytics', title: "Analytics" }
    },
    {
        path: '/transactions',
        name: RouteName.TransactionList,
        component: TransactionList,
        meta: {
            requiresAuth: true,
            toolbar: ({ spaceStore }: { spaceStore: ReturnType<typeof useSpaceStore> }) => [

                { id: 'openTransactionCreation', text: '', icon: 'pi pi-plus', onClickId: 'openTransactionCreation' },
            ],
            navStack: 'transactions',
            title: "Transactions"

        }
    },
    {
        path: '/transactions/create', name: RouteName.TransactionCreate, component: TransactionCreateUpdate, meta: {
            requiresAuth: true,
            toolbar: ({ spaceStore }: { spaceStore: ReturnType<typeof useSpaceStore> }) => [
                { id: 'createTransaction', text: '', icon: 'pi pi-save', onClickId: 'createTransaction' },
            ],
            navStack: 'transactions',
            title: "Create transaction"
        }
    },
    {
        path: '/transactions/:id/edit', name: RouteName.TransactionUpdate, component: TransactionCreateUpdate, meta: {
            requiresAuth: true,
            toolbar: ({ spaceStore }: { spaceStore: ReturnType<typeof useSpaceStore> }) => [

                { id: 'deleteTransaction', text: '', icon: 'pi pi-trash', onClickId: 'deleteTransaction' },
                { id: 'updateTransaction', text: '', icon: 'pi pi-save', onClickId: 'updateTransaction' },
            ],
            navStack: 'settings',
            title: "Edit transaction"
        }
    },

    {
        path: '/targets',
        name: RouteName.TargetList,
        component: TargetList,
        meta: {
            requiresAuth: true,
            toolbar: ({ spaceStore }: { spaceStore: ReturnType<typeof useSpaceStore> }) => [

                { id: 'openTargetCreation', text: '', icon: 'pi pi-plus', onClickId: 'openTargetCreation' },
            ],
            navStack: 'targets',
            title: "Targets"

        }
    },
    // {
    //     path: '/transactions/create', name: RouteName.TransactionCreate, component: TransactionCreateUpdate, meta: {
    //         requiresAuth: true,
    //         toolbar: ({spaceStore}: { spaceStore: ReturnType<typeof useSpaceStore> }) => [
    //             {id: 'createTransaction', text: '', icon: 'pi pi-save', onClickId: 'createTransaction'},
    //         ],
    //         navStack: 'transactions',
    //         title: "Create transaction"
    //     }
    // },
    // {
    //     path: '/transactions/:id/edit', name: RouteName.TransactionUpdate, component: TransactionCreateUpdate, meta: {
    //         requiresAuth: true,
    //         toolbar: ({spaceStore}: { spaceStore: ReturnType<typeof useSpaceStore> }) => [
    //
    //             {id: 'deleteTransaction', text: '', icon: 'pi pi-trash', onClickId: 'deleteTransaction'},
    //             {id: 'updateTransaction', text: '', icon: 'pi pi-save', onClickId: 'updateTransaction'},
    //         ],
    //         navStack: 'settings',
    //         title: "Edit transaction"
    //     }
    // },

    {
        path: '/settings',
        name: RouteName.SettingsList,
        component: SettingsList,
        meta: { requiresAuth: true, navStack: 'settings', title: "Settings" }
    },
    {
        path: '/categories', name: RouteName.CategoriesList, component: CategoriesList, meta: {
            requiresAuth: true,
            toolbar: ({ spaceStore }: { spaceStore: ReturnType<typeof useSpaceStore> }) => [

                { id: 'openCategoryCreation', text: '', icon: 'pi pi-plus', onClickId: 'openCategoryCreation' },
            ],
            navStack: 'settings',
            title: "Categories"
        }
    },
    {
        path: '/categories/create', name: RouteName.CategoryCreate, component: CategoryCreateUpdate, meta: {
            requiresAuth: true,
            toolbar: ({ spaceStore }: { spaceStore: ReturnType<typeof useSpaceStore> }) => [

                { id: 'createCategory', text: '', icon: 'pi pi-save', onClickId: 'createCategory' },
            ],
            navStack: 'settings',
            title: "Create category"
        }
    },
    {
        path: '/categories/:id/edit', name: RouteName.CategoryUpdate, component: CategoryCreateUpdate, meta: {
            requiresAuth: true,
            toolbar: ({ spaceStore }: { spaceStore: ReturnType<typeof useSpaceStore> }) => [

                { id: 'deleteCategory', text: '', icon: 'pi pi-trash', onClickId: 'deleteCategory' },
                { id: 'updateCategory', text: '', icon: 'pi pi-save', onClickId: 'updateCategory' },
            ],
            navStack: 'settings',
            title: "Edit category"
        }

    },

    {
        path: '/recurrents', name: RouteName.RecurrentsList, component: RecurrentsList, meta: {
            requiresAuth: true,
            toolbar: ({ spaceStore }: { spaceStore: ReturnType<typeof useSpaceStore> }) => [

                { id: 'openRecurrentCreation', text: '', icon: 'pi pi-plus', onClickId: 'openRecurrentCreation' },
            ],
            navStack: 'settings',
            title: "Recurrents"
        },
    },
    {
        path: '/recurrents/create', name: RouteName.RecurrentCreate, component: RecurrentyCreateUpdate, meta: {
            requiresAuth: true,
            toolbar: ({ spaceStore }: { spaceStore: ReturnType<typeof useSpaceStore> }) => [

                { id: 'createRecurrent', text: '', icon: 'pi pi-save', onClickId: 'createRecurrent' },
            ],
            navStack: 'settings',
            title: "Create recurrent"
        }
    },
    {
        path: '/recurrents/:id/edit', name: RouteName.RecurrentUpdate, component: RecurrentyCreateUpdate, meta: {
            requiresAuth: true,
            toolbar: ({ spaceStore }: { spaceStore: ReturnType<typeof useSpaceStore> }) => [

                { id: 'deleteRecurrent', text: '', icon: 'pi pi-trash', onClickId: 'deleteRecurrent' },
                { id: 'updateRecurrent', text: '', icon: 'pi pi-save', onClickId: 'updateRecurrent' },
            ],
            navStack: 'settings',
            title: "Edit recurrent"
        }
    },
    {
        path: '/space-settings',
        name: RouteName.SpaceSettings,
        component: SpaceSettings,
        meta: {
            requiresAuth: true,
            toolbar: ({ spaceStore }: { spaceStore: ReturnType<typeof useSpaceStore> }) => [
                {
                    id: 'space',
                    text: spaceStore.selectedSpaceName ?? 'Select Space',
                    icon: 'pi pi-home',
                    onClickId: 'openSpacePicker',
                },
                // {id: 'save', text: 'Save', icon: 'pi pi-check', onClickId: 'saveSettings'},
            ],
            navStack: 'settings',
            title: "Space settings"
        },
    },
    {
        path: '/notification-settings',
        name: RouteName.NotificationSettings,
        component: NotificationSettings,
        meta: {
            requiresAuth: true,
            navStack: 'settings',
            title: 'Notifications'
        }
    },
]

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes,
    scrollBehavior() {
        return { top: 0, left: 0, behavior: 'auto' }
    },
})

function isAuthed() {
    return !!localStorage.getItem('token')
}

router.beforeEach((to, _from, next) => {
    const authed = isAuthed()

    if (to.meta.requiresAuth && !authed) {
        const back = encodeURIComponent(to.fullPath)
        return next(`/login?back=${back}`)
    }

    if (to.meta.guestOnly && authed) {
        return next({ name: RouteName.SettingsList })
    }

    return next()
})

// 🔁 Авто-обновление тулбара при каждом переходе
router.afterEach((to) => {
    const toolbar = useToolbarStore()
    const cfg = to.meta.toolbar

    if (typeof cfg === 'function') {
        // даём конфигу доступ к сторам (расширяй при необходимости)
        toolbar.setByConfig(({ ...ctx }) => cfg({ spaceStore: useSpaceStore(), ...ctx }))
    } else {
        toolbar.setByConfig(cfg)
    }

    if (to.meta.title) {
        document.title = `${to.meta.title as string} | Luminic Space`
    } else {
        document.title = "Luminic Space"
    }
})

export default router
