import { Link, Outlet, RootRoute, Route, createRouter } from '@tanstack/react-router'
import { Suspense } from 'react'
import { TanStackRouterDevtools } from '@tanstack/router-devtools'
import { z } from 'zod'
import { HomeRoute } from './routes/home'
import { VendorOrderListRoute } from './routes/vendor-order-list'
import { LoginRoute } from './routes/login'
import { UserHomeRoute } from './routes/user-home'
import { SuperAdminRoute } from './routes/super-admin'
import { CreateCouponRoute } from './routes/create-coupon'
import { LocationMarkerRoute } from './routes/location-marker'
import { UserConnectRoute } from './routes/user-connect'
import Inauguration from './routes/inauguration'
import { DemoRoute } from './routes/demo'
import { OrderDetailsRoute } from './routes/order-details'
import { UserDetailsRoute } from './routes/user-details'
import { AuthWrapper } from './components/AuthWrapper'
import { SuperAdminGuard } from './components/SuperAdminGuard'
import { cn } from '@/lib/utils'

const basepath = normalizeBasePath(import.meta.env.BASE_URL)

const rootRoute = new RootRoute({
  component: RootComponent
})

const dashboardRoute = new Route({
  getParentRoute: () => rootRoute,
  path: '/',
  component: () => (
    <Suspense fallback={<p>Loading route…</p>}>
      <HomeRoute />
    </Suspense>
  )
})

const vendorOrderListRoute = new Route({
  getParentRoute: () => rootRoute,
  path: '/vendor-order-list',
  validateSearch: z.object({
    id: z.string().optional(),
  }),
  component: () => (
    <Suspense fallback={<p>Loading vendor orders…</p>}>
      <VendorOrderListRoute />
    </Suspense>
  )
})

const loginRoute = new Route({
  getParentRoute: () => rootRoute,
  path: '/login',
  component: () => (
    <Suspense fallback={<p>Loading login…</p>}>
      <LoginRoute />
    </Suspense>
  )
})

const inaugurationRoute = new Route({
  getParentRoute: () => rootRoute,
  path: '/inauguration',
  component: () => (
    <Suspense fallback={<p>Loading inauguration…</p>}>
      <Inauguration />
    </Suspense>
  )
})

const userHomeRoute = new Route({
  getParentRoute: () => rootRoute,
  path: '/user-home',
  component: () => (
    <Suspense fallback={<p>Loading user home…</p>}>
      <AuthWrapper>
        <UserHomeRoute />
      </AuthWrapper>
    </Suspense>
  )
})

const superAdminRoute = new Route({
  getParentRoute: () => rootRoute,
  path: '/super-admin',
  component: () => (
    <Suspense fallback={<p>Loading super admin…</p>}>
      <AuthWrapper>
        <SuperAdminGuard>
          <SuperAdminRoute />
        </SuperAdminGuard>
      </AuthWrapper>
    </Suspense>
  )
})

const createCouponRoute = new Route({
  getParentRoute: () => rootRoute,
  path: '/create-coupon',
  component: () => (
    <Suspense fallback={<p>Loading create coupon…</p>}>
      <AuthWrapper>
        <CreateCouponRoute />
      </AuthWrapper>
    </Suspense>
  )
})

const userConnectRoute = new Route({
  getParentRoute: () => rootRoute,
  path: '/user-connect',
  component: () => (
    <Suspense fallback={<p>Loading user connect…</p>}>
      <AuthWrapper>
        <UserConnectRoute />
      </AuthWrapper>
    </Suspense>
  )
})

const locationMarkerRoute = new Route({
  getParentRoute: () => rootRoute,
  path: '/location-marker',
  component: () => (
    <Suspense fallback={<p>Loading location marker…</p>}>
      <LocationMarkerRoute />
    </Suspense>
  )
})

const demoRoute = new Route({
  getParentRoute: () => rootRoute,
  path: '/demo',
  component: () => (
    <Suspense fallback={<p>Loading demo…</p>}>
      <DemoRoute />
    </Suspense>
  )
})

const orderDetailsRoute = new Route({
  getParentRoute: () => rootRoute,
  path: '/manage-orders/order-details/$id',
  component: () => (
    <Suspense fallback={<p>Loading order details…</p>}>
      <AuthWrapper>
        <OrderDetailsRoute />
      </AuthWrapper>
    </Suspense>
  )
})

const userDetailsRoute = new Route({
  getParentRoute: () => rootRoute,
  path: '/user-management/$id',
  component: () => (
    <Suspense fallback={<p>Loading user details…</p>}>
      <AuthWrapper>
        <UserDetailsRoute />
      </AuthWrapper>
    </Suspense>
  )
})

const routeTree = rootRoute.addChildren([
  dashboardRoute,
  vendorOrderListRoute,
  loginRoute,
  userHomeRoute,
  superAdminRoute,
  createCouponRoute,
  userConnectRoute,
  locationMarkerRoute,
  inaugurationRoute,
  demoRoute,
  orderDetailsRoute,
  userDetailsRoute
])

export function createAppRouter() {
  return createRouter({
    routeTree,
    basepath
  })
}

export type AppRouterInstance = ReturnType<typeof createAppRouter>

declare module '@tanstack/react-router' {
  interface Register {
    router: AppRouterInstance
  }
}

const navItems = [
  { to: '/', label: 'Dashboard', exact: true },
  { to: '/vendor-order-list', label: 'Vendor Order List' },
  { to: '/user-connect', label: 'User Connect' }
] as const

function RootComponent() {
  return (
    <div className="min-h-screen bg-slate-100">
      <div className="mx-auto flex min-h-screen max-w-6xl flex-col gap-6 px-4 py-6 md:px-8 md:py-10">
        <main className="flex-1">
          <Outlet />
        </main>
        <footer className="flex justify-center pb-6 text-xs text-slate-500">
          &copy; {new Date().getFullYear()} Meat Farmer. All rights reserved.
        </footer>
        {import.meta.env.DEV ? (
          <TanStackRouterDevtools position="bottom-right" />
        ) : null}
      </div>
    </div>
  )
}

function normalizeBasePath(value: string): string {
  if (!value) return '/'
  if (value === '/') return '/'
  return value.endsWith('/') ? value.slice(0, -1) : value
}
