import { Navigate, Route, Routes } from 'react-router-dom'
import { useAuthStore } from './stores/authStore'
import { ProtectedRoute } from './components/routing/ProtectedRoute'
import { MustChangePasswordGate } from './components/routing/MustChangePasswordGate'
import { LoginPage } from './features/auth/pages/LoginPage'
import { CreateUserPage } from './features/users/pages/CreateUserPage'
import { UsersListPage } from './features/users/pages/UsersListPage'
import { UserDetailPage } from './features/users/pages/UserDetailPage'
import { UserEditPage } from './features/users/pages/UserEditPage'
import { ChangeMyPasswordPage } from './features/profile/pages/ChangeMyPasswordPage'
import { RolesPage } from './features/roles/pages/RolesPage'
import { NewRolPage } from './features/roles/pages/NewRolPage'
import { EditRolPage } from './features/roles/pages/EditRolPage'
import { RolPermisosPage } from './features/permisos/pages/RolPermisosPage'
import { AuditPage } from './pages/admin/audit/AuditPage'
import { MediosListPage } from './features/medios/pages/MediosListPage'
import { CreateMedioPage } from './features/medios/pages/CreateMedioPage'
import { EditMedioPage } from './features/medios/pages/EditMedioPage'
import { MedioDetailPage } from './features/medios/pages/MedioDetailPage'
import { SeccionesListPage } from './features/secciones/pages/SeccionesListPage'
import { CreateSeccionPage } from './features/secciones/pages/CreateSeccionPage'
import { EditSeccionPage } from './features/secciones/pages/EditSeccionPage'
import { SeccionDetailPage } from './features/secciones/pages/SeccionDetailPage'
import { PuntosDeVentaListPage } from './features/puntos-de-venta/pages/PuntosDeVentaListPage'
import { CreatePuntoDeVentaPage } from './features/puntos-de-venta/pages/CreatePuntoDeVentaPage'
import { PuntoDeVentaDetailPage } from './features/puntos-de-venta/pages/PuntoDeVentaDetailPage'
import { EditPuntoDeVentaPage } from './features/puntos-de-venta/pages/EditPuntoDeVentaPage'
import { TiposDeIvaPage } from './features/fiscal/iva/pages/TiposDeIvaPage'
import { TiposDeIibbPage } from './features/fiscal/iibb/pages/TiposDeIibbPage'
import { RubrosPage } from './features/rubros/pages/RubrosPage'
import { ProductTypesPage } from './features/product-types/pages/ProductTypesPage'
import { ProductsPage } from './features/products/pages/ProductsPage'
import { HomePage } from './pages/HomePage'
import { PublicLayout } from './layouts/PublicLayout'
import { ProtectedLayout } from './layouts/ProtectedLayout'

function PublicRoute({ children }: { children: React.ReactNode }) {
  const user = useAuthStore((s) => s.user)
  if (user) {
    return <Navigate to="/" replace />
  }
  return <>{children}</>
}

/**
 * Wraps a protected route with ProtectedLayout + MustChangePasswordGate.
 * The gate forces users with mustChangePassword=true to /perfil/contrasena.
 */
function ProtectedPage({
  children,
  requiredPermissions,
}: {
  children: React.ReactNode
  requiredPermissions?: string[]
}) {
  return (
    <ProtectedRoute requiredPermissions={requiredPermissions}>
      <MustChangePasswordGate>
        <ProtectedLayout>{children}</ProtectedLayout>
      </MustChangePasswordGate>
    </ProtectedRoute>
  )
}

export function AppRoutes() {
  return (
    <Routes>
      {/* Public routes */}
      <Route
        path="/login"
        element={
          <PublicRoute>
            <PublicLayout>
              <LoginPage />
            </PublicLayout>
          </PublicRoute>
        }
      />

      {/* Change password — protected but NO MustChangePasswordGate (avoids redirect loop) */}
      <Route
        path="/perfil/contrasena"
        element={
          <ProtectedRoute>
            <ProtectedLayout>
              <ChangeMyPasswordPage />
            </ProtectedLayout>
          </ProtectedRoute>
        }
      />

      {/* Protected routes — all wrapped with MustChangePasswordGate */}
      <Route
        path="/"
        element={<ProtectedPage><HomePage /></ProtectedPage>}
      />

      <Route
        path="/usuarios"
        element={
          <ProtectedPage requiredPermissions={['administracion:usuarios:gestionar']}>
            <UsersListPage />
          </ProtectedPage>
        }
      />

      <Route
        path="/usuarios/nuevo"
        element={
          <ProtectedPage requiredPermissions={['administracion:usuarios:gestionar']}>
            <CreateUserPage />
          </ProtectedPage>
        }
      />

      <Route
        path="/usuarios/:id"
        element={
          <ProtectedPage requiredPermissions={['administracion:usuarios:gestionar']}>
            <UserDetailPage />
          </ProtectedPage>
        }
      />

      <Route
        path="/usuarios/:id/editar"
        element={
          <ProtectedPage requiredPermissions={['administracion:usuarios:gestionar']}>
            <UserEditPage />
          </ProtectedPage>
        }
      />

      <Route
        path="/admin/roles"
        element={
          <ProtectedPage requiredPermissions={['administracion:roles:gestionar']}>
            <RolesPage />
          </ProtectedPage>
        }
      />

      <Route
        path="/admin/roles/nuevo"
        element={
          <ProtectedPage requiredPermissions={['administracion:roles:gestionar']}>
            <NewRolPage />
          </ProtectedPage>
        }
      />

      <Route
        path="/admin/roles/:codigo/editar"
        element={
          <ProtectedPage requiredPermissions={['administracion:roles:gestionar']}>
            <EditRolPage />
          </ProtectedPage>
        }
      />

      <Route
        path="/admin/permisos"
        element={
          <ProtectedPage
            requiredPermissions={[
              'administracion:roles_permisos:gestionar',
              'administracion:permisos:ver',
            ]}
          >
            <RolPermisosPage />
          </ProtectedPage>
        }
      />

      <Route
        path="/admin/audit"
        element={
          <ProtectedPage requiredPermissions={['administracion:auditoria:ver']}>
            <AuditPage />
          </ProtectedPage>
        }
      />

      {/* Medios routes */}
      <Route
        path="/admin/medios"
        element={
          <ProtectedPage requiredPermissions={['administracion:medios:gestionar']}>
            <MediosListPage />
          </ProtectedPage>
        }
      />
      <Route
        path="/admin/medios/nuevo"
        element={
          <ProtectedPage requiredPermissions={['administracion:medios:gestionar']}>
            <CreateMedioPage />
          </ProtectedPage>
        }
      />
      <Route
        path="/admin/medios/:id"
        element={
          <ProtectedPage requiredPermissions={['administracion:medios:gestionar']}>
            <MedioDetailPage />
          </ProtectedPage>
        }
      />
      <Route
        path="/admin/medios/:id/edit"
        element={
          <ProtectedPage requiredPermissions={['administracion:medios:gestionar']}>
            <EditMedioPage />
          </ProtectedPage>
        }
      />

      {/* Secciones routes */}
      <Route
        path="/admin/secciones"
        element={
          <ProtectedPage requiredPermissions={['administracion:secciones:gestionar']}>
            <SeccionesListPage />
          </ProtectedPage>
        }
      />
      <Route
        path="/admin/secciones/nuevo"
        element={
          <ProtectedPage requiredPermissions={['administracion:secciones:gestionar']}>
            <CreateSeccionPage />
          </ProtectedPage>
        }
      />
      <Route
        path="/admin/secciones/:id"
        element={
          <ProtectedPage requiredPermissions={['administracion:secciones:gestionar']}>
            <SeccionDetailPage />
          </ProtectedPage>
        }
      />
      <Route
        path="/admin/secciones/:id/edit"
        element={
          <ProtectedPage requiredPermissions={['administracion:secciones:gestionar']}>
            <EditSeccionPage />
          </ProtectedPage>
        }
      />

      {/* Puntos de Venta routes */}
      <Route
        path="/admin/puntos-de-venta"
        element={
          <ProtectedPage requiredPermissions={['administracion:puntos_de_venta:gestionar']}>
            <PuntosDeVentaListPage />
          </ProtectedPage>
        }
      />
      <Route
        path="/admin/puntos-de-venta/nuevo"
        element={
          <ProtectedPage requiredPermissions={['administracion:puntos_de_venta:gestionar']}>
            <CreatePuntoDeVentaPage />
          </ProtectedPage>
        }
      />
      <Route
        path="/admin/puntos-de-venta/:id"
        element={
          <ProtectedPage requiredPermissions={['administracion:puntos_de_venta:gestionar']}>
            <PuntoDeVentaDetailPage />
          </ProtectedPage>
        }
      />
      <Route
        path="/admin/puntos-de-venta/:id/edit"
        element={
          <ProtectedPage requiredPermissions={['administracion:puntos_de_venta:gestionar']}>
            <EditPuntoDeVentaPage />
          </ProtectedPage>
        }
      />

      {/* Fiscal routes — ADM-009 */}
      <Route
        path="/admin/fiscal/iva"
        element={
          <ProtectedPage requiredPermissions={['administracion:fiscal:gestionar']}>
            <TiposDeIvaPage />
          </ProtectedPage>
        }
      />
      <Route
        path="/admin/fiscal/iibb"
        element={
          <ProtectedPage requiredPermissions={['administracion:fiscal:gestionar']}>
            <TiposDeIibbPage />
          </ProtectedPage>
        }
      />

      {/* Rubros routes — CAT-001 */}
      <Route
        path="/admin/rubros"
        element={
          <ProtectedPage requiredPermissions={['catalogo:rubros:gestionar']}>
            <RubrosPage />
          </ProtectedPage>
        }
      />

      {/* ProductTypes routes — PRD-001 */}
      <Route
        path="/admin/product-types"
        element={
          <ProtectedPage requiredPermissions={['catalogo:tipos:gestionar']}>
            <ProductTypesPage />
          </ProtectedPage>
        }
      />

      {/* Products routes — PRD-002 */}
      <Route
        path="/admin/products"
        element={
          <ProtectedPage requiredPermissions={['catalogo:productos:gestionar']}>
            <ProductsPage />
          </ProtectedPage>
        }
      />

      <Route path="*" element={<Navigate to="/" replace />} />
    </Routes>
  )
}
