import { createFileRoute } from '@tanstack/react-router'

import { RouteErrorFallback } from '~/components/common/route-error-fallback'
import { parseAnchorSide, parsePositiveInt } from '~/features/diff-review/shared/navigation'
import { WorkspaceDiffsView } from '~/features/diff-review/workspace-diffs-view'

interface WorkspaceDiffsSearch {
  repo?: string
  path?: string
  review?: string
  line?: number
  side?: 'base' | 'head'
  github?: string
}

export const Route = createFileRoute('/workspaces/$workspaceId/diffs')({
  validateSearch: (search: Record<string, unknown>): WorkspaceDiffsSearch => ({
    repo: typeof search.repo === 'string' && search.repo.length > 0 ? search.repo : undefined,
    path: typeof search.path === 'string' && search.path.length > 0 ? search.path : undefined,
    review: typeof search.review === 'string' && search.review.length > 0 ? search.review : undefined,
    line: parsePositiveInt(search.line),
    side: parseAnchorSide(search.side),
    github: typeof search.github === 'string' && search.github.length > 0 ? search.github : undefined,
  }),
  errorComponent: RouteErrorFallback,
  component: WorkspaceDiffsRoute,
})

function WorkspaceDiffsRoute() {
  const { workspaceId } = Route.useParams()
  const { repo, path, review, line, side, github } = Route.useSearch()
  return (
    <WorkspaceDiffsView
      workspaceId={workspaceId}
      repo={repo}
      path={path}
      review={review}
      line={line}
      side={side}
      github={github}
    />
  )
}
