import {
  createRouter,
  createRootRoute,
  createRoute,
  Outlet,
  notFound,
} from '@tanstack/react-router';
import { Button, Result, Typography } from 'antd';
import { AppShell } from '../components/layout/AppShell';
import { RepPainel } from '../cockpits/rep/RepPainel';
import { ClientsPage } from '../cockpits/rep/ClientsPage';
import { ClientDetailPage } from '../cockpits/rep/ClientDetailPage';
import { OrdersPage } from '../cockpits/rep/OrdersPage';
import { OrderDetailPage } from '../cockpits/rep/OrderDetailPage';
import { OrderPrintPage } from '../cockpits/rep/OrderPrintPage';
import { NewClientPage } from '../cockpits/rep/NewClientPage';
import { NewOrderPage } from '../cockpits/rep/NewOrderPage';
import { CatalogPage } from '../cockpits/rep/CatalogPage';
import { OrdersErpPage } from '../cockpits/rep/OrdersErpPage';
import { RelatoriosPage } from '../cockpits/rep/RelatoriosPage';
import { CarteirePage } from '../cockpits/rep/CarteirePage';
import { FunilPage } from '../cockpits/rep/FunilPage';
import { ApprovalQueuePage } from '../cockpits/supervisor/ApprovalQueuePage';
import { SupervisorPainel } from '../cockpits/supervisor/SupervisorPainel';
import { GerPainel } from '../cockpits/ger/GerPainel';
import { EquipePage } from '../cockpits/ger/EquipePage';
import { PoliticasPage } from '../cockpits/ger/PoliticasPage';
import { ChamadosPage } from '../cockpits/rep/ChamadosPage';
import { GerChamadosPage } from '../cockpits/ger/GerChamadosPage';
import { GerConfigPage } from '../cockpits/ger/GerConfigPage';
import { authStore } from './auth-store';

function getRoleFromToken(): string {
  const token = authStore.get();
  if (!token) return 'rep';
  try {
    const payload = JSON.parse(atob(token.split('.')[1] ?? ''));
    return (payload.role as string) ?? 'rep';
  } catch {
    return 'rep';
  }
}

function HomeRoute() {
  const role = getRoleFromToken();
  if (role === 'manager' || role === 'admin') return <GerPainel />;
  if (role === 'supervisor') return <SupervisorPainel />;
  return <RepPainel />;
}

// Error boundary por rota: uma exceção de render (ex.: ZodError de payload
// inesperado) mostra esta tela em vez de derrubar o app inteiro em branco.
function RouteErrorPage({ error }: { error: Error }) {
  return (
    <Result
      status="error"
      title="Algo deu errado"
      subTitle={error.message || 'Erro inesperado ao exibir esta tela.'}
      extra={
        <Button type="primary" onClick={() => window.location.reload()}>
          Recarregar
        </Button>
      }
    />
  );
}

function NotFoundPage() {
  return (
    <div style={{ padding: 48, textAlign: 'center' }}>
      <Typography.Title level={3} type="secondary">
        Página não encontrada
      </Typography.Title>
    </div>
  );
}

// Suprime aviso de notFound não utilizado — usado via throw notFound() em loaders futuros.
void notFound;

const rootRoute = createRootRoute({
  component: () => (
    <AppShell>
      <Outlet />
    </AppShell>
  ),
  notFoundComponent: NotFoundPage,
  errorComponent: RouteErrorPage,
});

const indexRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/',
  component: HomeRoute,
});

const rafaelRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/rep',
  component: RepPainel,
});

const clientesRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/clientes',
  component: ClientsPage,
});

const novoClienteRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/clientes/novo',
  component: NewClientPage,
});

const clienteDetailRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/clientes/$id',
  component: ClientDetailPage,
});

const pedidosRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/pedidos',
  component: OrdersPage,
});

const novoOrderRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/pedidos/novo',
  component: NewOrderPage,
});

const pedidoDetailRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/pedidos/$id',
  component: OrderDetailPage,
});

const pedidoPrintRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/pedidos/$id/imprimir',
  component: OrderPrintPage,
});

const catalogoRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/catalogo',
  component: CatalogPage,
});

const pedidosErpRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/pedidos-erp',
  component: OrdersErpPage,
});

const relatoriosRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/relatorios',
  component: RelatoriosPage,
});

const carteiraRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/clientes/carteira',
  component: CarteirePage,
});

const funilRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/funil',
  component: FunilPage,
});

const aprovacoes = createRoute({
  getParentRoute: () => rootRoute,
  path: '/aprovacoes',
  component: ApprovalQueuePage,
});

const gerPainelRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/ger',
  component: GerPainel,
});

const equipeRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/ger/equipe',
  component: EquipePage,
});

const politicasRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/ger/politicas',
  component: PoliticasPage,
});

const chamadosRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/chamados',
  component: ChamadosPage,
});

const gerChamadosRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/ger/chamados',
  component: GerChamadosPage,
});

const gerConfigRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/ger/config',
  component: GerConfigPage,
});

const routeTree = rootRoute.addChildren([
  indexRoute,
  rafaelRoute,
  clientesRoute,
  novoClienteRoute,
  clienteDetailRoute,
  pedidosRoute,
  novoOrderRoute,
  pedidoDetailRoute,
  pedidoPrintRoute,
  catalogoRoute,
  pedidosErpRoute,
  relatoriosRoute,
  carteiraRoute,
  funilRoute,
  aprovacoes,
  gerPainelRoute,
  equipeRoute,
  politicasRoute,
  chamadosRoute,
  gerChamadosRoute,
  gerConfigRoute,
]);

export const router = createRouter({
  routeTree,
  defaultPreload: 'intent',
  defaultPreloadStaleTime: 0,
  defaultErrorComponent: RouteErrorPage,
});

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