refactor: modularize upload page into location, input, and settings sections

This commit is contained in:
2026-06-18 17:11:26 +05:30
parent 9e76b8e6d0
commit 62ebf1ebf6
9 changed files with 552 additions and 599 deletions

View File

@@ -0,0 +1,50 @@
'use client';
import { FormField, SelectPopover } from '@/components/form';
const options = [
{ value: 'yolo', label: 'Road Defect Detection' },
{ value: 'yoloe', label: 'YOLOE Open-Vocabulary Detection' },
{ value: 'yoloe_trained_vl', label: 'YOLOE With Vision Language Model' },
{ value: 'culvert_detection', label: 'Culvert Detection' },
{ value: 'combined', label: 'Road Defect Detection with vl' },
] as const;
interface AnalysisSettingsSectionProps {
value: string;
onValueChange: (value: string) => void;
disabled?: boolean;
}
export function AnalysisSettingsSection({
value,
onValueChange,
disabled = false,
}: AnalysisSettingsSectionProps) {
return (
<section className="space-y-3">
<div>
<h2 className="text-sm font-semibold text-foreground">
Analysis Settings
</h2>
<p className="text-xs text-muted-foreground">
Select the AI model workflow for this job.
</p>
</div>
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
<FormField id="analysis-method" label="Analysis Method">
<SelectPopover
options={options}
value={value}
onValueChange={onValueChange}
disabled={disabled}
placeholder="Select method"
searchPlaceholder="Search methods"
emptyMessage="No methods found."
/>
</FormField>
</div>
</section>
);
}

View File

@@ -0,0 +1,50 @@
'use client';
import { UploadFileDropzone } from './UploadFileDropzone';
interface InputDataSectionProps {
videoFile: File | null;
gpsFile: File | null;
onVideoFileChange: (file: File | null) => void;
onGpsFileChange: (file: File | null) => void;
disabled?: boolean;
}
export function InputDataSection({
videoFile,
gpsFile,
onVideoFileChange,
onGpsFileChange,
disabled = false,
}: InputDataSectionProps) {
return (
<section className="space-y-3">
<div>
<h2 className="text-sm font-semibold text-foreground">Input Data</h2>
<p className="text-xs text-muted-foreground">
Attach the road video and GPS telemetry for processing.
</p>
</div>
<div className="grid grid-cols-1 gap-3 md:grid-cols-2">
<UploadFileDropzone
title="Drop video here or browse"
description="Accepted formats: MP4, MOV, AVI, MKV"
accept="video/*"
file={videoFile}
onFileChange={onVideoFileChange}
disabled={disabled}
/>
<UploadFileDropzone
title="Drop GPS JSON here or browse"
description="Accepted format: JSON telemetry file"
accept=".json,application/json"
file={gpsFile}
onFileChange={onGpsFileChange}
disabled={disabled}
/>
</div>
</section>
);
}

View File

@@ -0,0 +1,145 @@
'use client';
import { useCallback, useEffect, useRef, useState } from 'react';
import { FormField } from '@/components/form';
import { PackageSelect } from '@/components/lookups/PackageSelect';
import { ProjectSelect } from '@/components/lookups/ProjectSelect';
import { SegmentSelect } from '@/components/lookups/SegmentSelect';
import { packageService, projectService, chainageService } from '@/services/api';
import type { Chainage, Package as PackageType, Project, SessionContext } from '@/types';
interface LocationSectionProps {
value: SessionContext | null;
onChange: (session: SessionContext | null) => void;
disabled?: boolean;
}
export function LocationSection({
value,
onChange,
disabled = false,
}: LocationSectionProps) {
const [projectId, setProjectId] = useState(value?.projectId ?? '');
const [packageId, setPackageId] = useState(value?.packageId ?? '');
const [segmentId, setSegmentId] = useState(value?.chainageId ?? '');
const [project, setProject] = useState<Project | null>(null);
const [selectedPackage, setSelectedPackage] = useState<PackageType | null>(
null,
);
const [segment, setSegment] = useState<Chainage | null>(null);
const latestProjectIdRef = useRef('');
const latestPackageIdRef = useRef('');
const latestSegmentIdRef = useRef('');
useEffect(() => {
if (project && selectedPackage && segment) {
onChange({
projectId: project.id,
projectName: project.name,
packageId: selectedPackage.id,
packageName: selectedPackage.name,
chainageId: segment.id,
chainageName: segment.segment_name,
chainageDirection: segment.direction,
});
return;
}
onChange(null);
}, [onChange, project, selectedPackage, segment]);
const handleProjectChange = useCallback((nextProjectId: string) => {
latestProjectIdRef.current = nextProjectId;
latestPackageIdRef.current = '';
latestSegmentIdRef.current = '';
setProjectId(nextProjectId);
setPackageId('');
setSegmentId('');
setProject(null);
setSelectedPackage(null);
setSegment(null);
if (!nextProjectId) return;
void projectService.getProjectById(nextProjectId).then((nextProject) => {
if (latestProjectIdRef.current === nextProjectId) {
setProject(nextProject);
}
});
}, []);
const handlePackageChange = useCallback((nextPackageId: string) => {
latestPackageIdRef.current = nextPackageId;
latestSegmentIdRef.current = '';
setPackageId(nextPackageId);
setSegmentId('');
setSelectedPackage(null);
setSegment(null);
if (!nextPackageId) return;
void packageService.getPackageById(nextPackageId).then((nextPackage) => {
if (latestPackageIdRef.current === nextPackageId) {
setSelectedPackage(nextPackage);
}
});
}, []);
const handleSegmentChange = useCallback((nextSegmentId: string) => {
latestSegmentIdRef.current = nextSegmentId;
setSegmentId(nextSegmentId);
setSegment(null);
if (!nextSegmentId) return;
void chainageService.getChainageById(nextSegmentId).then((nextSegment) => {
if (latestSegmentIdRef.current === nextSegmentId) {
setSegment(nextSegment);
}
});
}, []);
return (
<section className="space-y-3">
<div>
<h2 className="text-sm font-semibold text-foreground">Location</h2>
<p className="text-xs text-muted-foreground">
Select the project hierarchy for this analysis job.
</p>
</div>
<div className="grid grid-cols-1 gap-3 md:grid-cols-3">
<FormField label="Project" required>
<ProjectSelect
value={projectId}
onValueChange={handleProjectChange}
disabled={disabled}
/>
</FormField>
<FormField label="Package" required>
<PackageSelect
value={packageId}
onValueChange={handlePackageChange}
projectId={projectId}
enabled={Boolean(projectId)}
disabled={disabled || !projectId}
/>
</FormField>
<FormField label="Segment" required>
<SegmentSelect
value={segmentId}
onValueChange={handleSegmentChange}
packageId={packageId}
enabled={Boolean(packageId)}
disabled={disabled || !packageId}
/>
</FormField>
</div>
</section>
);
}

View File

@@ -0,0 +1,93 @@
'use client';
import { useRef, useState } from 'react';
import { FileCheck2, UploadCloud } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { cn } from '@/lib/utils';
interface UploadFileDropzoneProps {
title: string;
description: string;
accept: string;
file: File | null;
onFileChange: (file: File | null) => void;
disabled?: boolean;
}
export function UploadFileDropzone({
title,
description,
accept,
file,
onFileChange,
disabled = false,
}: UploadFileDropzoneProps) {
const inputRef = useRef<HTMLInputElement | null>(null);
const [isDragging, setIsDragging] = useState(false);
const handleFiles = (files: FileList | null) => {
if (disabled) return;
onFileChange(files?.[0] ?? null);
};
return (
<div
role="button"
tabIndex={disabled ? -1 : 0}
aria-disabled={disabled}
onClick={() => {
if (!disabled) inputRef.current?.click();
}}
onKeyDown={(event) => {
if (!disabled && (event.key === 'Enter' || event.key === ' ')) {
event.preventDefault();
inputRef.current?.click();
}
}}
onDragOver={(event) => {
event.preventDefault();
if (!disabled) setIsDragging(true);
}}
onDragLeave={() => setIsDragging(false)}
onDrop={(event) => {
event.preventDefault();
setIsDragging(false);
handleFiles(event.dataTransfer.files);
}}
className={cn(
'group flex min-h-32 cursor-pointer flex-col justify-between rounded-md border border-dashed bg-card/60 p-4 transition-colors',
'hover:border-primary/60 hover:bg-secondary/40',
isDragging && 'border-primary bg-secondary/60',
disabled && 'pointer-events-none cursor-not-allowed opacity-60',
)}
>
<input
ref={inputRef}
type="file"
accept={accept}
className="hidden"
onChange={(event) => handleFiles(event.target.files)}
disabled={disabled}
/>
<div className="space-y-3">
<div className="flex size-9 items-center justify-center rounded-md border bg-background">
<UploadCloud className="size-4 text-muted-foreground" />
</div>
<div>
<p className="text-sm font-medium text-foreground">{title}</p>
<p className="mt-1 text-xs text-muted-foreground">{description}</p>
</div>
</div>
{file ? (
<Badge variant="secondary" className="mt-4 max-w-full justify-start">
<FileCheck2 className="size-3" />
<span className="truncate">{file.name}</span>
</Badge>
) : null}
</div>
);
}

View File

@@ -1,256 +1,134 @@
'use client'; 'use client';
import { useState, useEffect, useCallback } from 'react'; import { useState } from 'react';
import { useRouter } from 'next/navigation'; import { useRouter } from 'next/navigation';
import { import { Loader2, Play, TrendingUp } from 'lucide-react';
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { FormField } from '@/components/form';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Loader2, TrendingUp } from 'lucide-react';
import { PageHeader } from '@/components/page-header'; import { PageHeader } from '@/components/page-header';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { videoService } from '@/services/api'; import { videoService } from '@/services/api';
import { SessionContext } from '@/types'; import type { SessionContext } from '@/types';
import { ProjectSelectionSection } from '@/components/project-selection-section';
import { Reveal } from '@/components/ui/reveal';
import { cn } from '@/lib/utils';
import { ROUTES } from '@/utils/routes'; import { ROUTES } from '@/utils/routes';
const DETECTION_METHODS = [ import { AnalysisSettingsSection } from './components/AnalysisSettingsSection';
{ value: 'yolo', label: 'Road Defect Detection' }, import { InputDataSection } from './components/InputDataSection';
// { value: 'yolo_vl', label: 'YOLO with Vision-Language Model' }, import { LocationSection } from './components/LocationSection';
// { value: 'sam3', label: 'OpenAI SAM 3 Segmentation Model' },
{ value: 'yoloe', label: 'YOLOE Open-Vocabulary Detection' },
{ value: 'yoloe_trained_vl', label: 'YOLOE With Vision Language Model' },
{ value: 'culvert_detection', label: 'Culvert Detection' },
{ value: 'combined', label: 'Road Defect Detection with vl' },
// { value: 'gemini_video', label: 'Gemini AI Analysis' },
] as const;
export default function UploadPage() { export default function UploadPage() {
const router = useRouter(); const router = useRouter();
const [session, setSession] = useState<SessionContext | null>(null); const [session, setSession] = useState<SessionContext | null>(null);
const [isLoading, setIsLoading] = useState(true); const [videoFile, setVideoFile] = useState<File | null>(null);
const [gpsFile, setGpsFile] = useState<File | null>(null);
// Form states const [analysisMethod, setAnalysisMethod] = useState('yolo');
const [file, setFile] = useState<File | null>(null); const [isSubmitting, setIsSubmitting] = useState(false);
const [jsonFile, setJsonFile] = useState<File | null>(null);
const [selectMethod, setSelectMethod] = useState('yolo');
// Upload states
const [uploading, setUploading] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
// Load session on mount const isLocationComplete = Boolean(
useEffect(() => { session?.projectId && session.packageId && session.chainageId,
// We don't load session on mount for the upload page to ensure );
// project details are filled manually as requested. const canSubmit = Boolean(
setIsLoading(false); isLocationComplete && videoFile && gpsFile && analysisMethod,
}, []);
const handleSelectionChange = useCallback(
(selectedSession: SessionContext | null) => {
setSession(selectedSession);
},
[],
); );
const handleUpload = async () => { const handleSubmit = async () => {
if (!file) { if (!session?.chainageId || !videoFile || !gpsFile) {
setError('Please select a video file'); setError('Complete location and input data before starting analysis.');
return;
}
if (!jsonFile) {
setError('Please select a GPS JSON file');
return;
}
if (!session) {
setError('Please complete the project selection first');
return; return;
} }
const formData = new FormData(); const formData = new FormData();
formData.append('file', file); formData.append('file', videoFile);
formData.append('detection_mode', selectMethod); formData.append('detection_mode', analysisMethod);
formData.append('chainage_id', session.chainageId as string); formData.append('chainage_id', session.chainageId);
formData.append('json_file', jsonFile); formData.append('json_file', gpsFile);
setUploading(true); setIsSubmitting(true);
setError(null); setError(null);
try { try {
await videoService.uploadVideo(formData); await videoService.uploadVideo(formData);
router.push(ROUTES.TICKET); router.push(ROUTES.TICKET);
} catch (err) { } catch (err) {
let errorMessage = 'Upload failed'; setIsSubmitting(false);
if (err instanceof TypeError && err.message === 'Failed to fetch') { if (err instanceof TypeError && err.message === 'Failed to fetch') {
errorMessage = setError('Cannot connect to server. Please check if backend is running.');
'Cannot connect to server. Please check if backend is running.'; return;
} else if (err instanceof Error) {
errorMessage = err.message;
} }
setError(errorMessage); setError(err instanceof Error ? err.message : 'Upload failed');
setUploading(false);
} }
}; };
if (isLoading) {
return ( return (
<div className="min-h-screen flex items-center justify-center"> <div className="space-y-5">
<Loader2 className="h-10 w-10 animate-spin text-primary" />
</div>
);
}
const isSessionComplete = !!(
session?.projectId && session.packageId && session.chainageId
);
const isFormValid = isSessionComplete && file && jsonFile;
return (
<div className="min-h-screen pb-12">
<main>
{/* Header */}
<div className="mb-10">
<PageHeader <PageHeader
title="Intelligent Road Asset AI Analysis" title="Create Analysis Job"
description="High-precision detection for potholes, signboards, and culverts from video data" description="Configure location, upload data, and start AI analysis."
icon={TrendingUp} icon={TrendingUp}
/> />
</div>
<div className="space-y-8 mt-8"> <Card>
{/* Module 1: Project Selection */} <CardContent className="space-y-5 p-5">
<Reveal direction="up" delay={0.1}> <LocationSection
<Card className="border"> value={session}
<CardHeader> onChange={setSession}
<CardTitle className="text-xl font-bold"> disabled={isSubmitting}
1. Project Details
</CardTitle>
<CardDescription>
Select the target project, package, and segment.
</CardDescription>
</CardHeader>
<CardContent>
<ProjectSelectionSection
onSelectionChange={handleSelectionChange}
asStep={true}
hideButton={true}
/> />
</CardContent>
</Card>
</Reveal>
{/* Module 2: Upload Data */} <Separator />
<Reveal direction="up" delay={0.2}>
<Card <InputDataSection
className={cn( videoFile={videoFile}
'border transition-all duration-300', gpsFile={gpsFile}
!isSessionComplete && onVideoFileChange={(file) => {
'opacity-60 pointer-events-none grayscale-[0.5]', setVideoFile(file);
)}
>
<CardHeader>
<CardTitle className="text-xl font-bold flex items-center gap-2">
2. Upload Video Data
</CardTitle>
<CardDescription>
Provide the video file and GPS telemetry for processing.
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<div className="grid grid-cols-1 gap-6">
<FormField id="video-file" label="Video File" required>
<Input
id="video-file"
type="file"
accept="video/*"
onChange={(e) => {
setFile(e.target.files?.[0] || null);
setError(null); setError(null);
}} }}
disabled={uploading || !isSessionComplete} onGpsFileChange={(file) => {
/> setGpsFile(file);
</FormField>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<FormField id="json-file" label="GPS JSON File" required>
<Input
id="json-file"
type="file"
accept=".json,application/json"
onChange={(e) => {
setJsonFile(e.target.files?.[0] || null);
setError(null); setError(null);
}} }}
disabled={uploading || !isSessionComplete} disabled={isSubmitting}
required
/> />
</FormField>
<FormField id="select-method" label="Analysis Method"> <Separator />
<Select
value={selectMethod}
onValueChange={setSelectMethod}
disabled={uploading || !isSessionComplete}
>
<SelectTrigger id="select-method">
<SelectValue placeholder="Select method" />
</SelectTrigger>
<SelectContent>
{DETECTION_METHODS.map((method) => (
<SelectItem key={method.value} value={method.value}>
{method.label}
</SelectItem>
))}
</SelectContent>
</Select>
</FormField>
</div>
</div>
{/* Error Display */} <AnalysisSettingsSection
{error && ( value={analysisMethod}
<div className="p-4 rounded-md bg-destructive/5 border border-destructive/20 text-destructive text-sm font-medium animate-in fade-in slide-in-from-top-1"> onValueChange={setAnalysisMethod}
disabled={isSubmitting}
/>
{error ? (
<div className="rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">
{error} {error}
</div> </div>
)} ) : null}
<div> <div className="flex justify-end">
<Button <Button
onClick={handleUpload} type="button"
disabled={!isFormValid || uploading} size="lg"
className="w-full" disabled={!canSubmit || isSubmitting}
onClick={handleSubmit}
className="w-full gap-2 md:w-auto"
> >
{uploading ? ( {isSubmitting ? (
<span className="flex items-center gap-2"> <>
<Loader2 className="h-5 w-5 animate-spin" /> <Loader2 className="size-4 animate-spin" />
Uploading... Starting analysis...
</span> </>
) : ( ) : (
'Upload and Process' <>
<Play className="size-4" />
Start Analysis
</>
)} )}
</Button> </Button>
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
</Reveal>
</div>
</main>
</div> </div>
); );
} }

View File

@@ -0,0 +1,117 @@
'use client';
import { useMemo, useState } from 'react';
import { Check, ChevronDown } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover';
import { cn } from '@/lib/utils';
export interface SelectPopoverOption {
value: string;
label: string;
disabled?: boolean;
}
interface SelectPopoverProps {
options: readonly SelectPopoverOption[];
value: string;
onValueChange: (value: string) => void;
placeholder?: string;
searchPlaceholder?: string;
emptyMessage?: string;
disabled?: boolean;
align?: 'start' | 'center' | 'end';
}
export function SelectPopover({
options,
value,
onValueChange,
placeholder = 'Select option',
searchPlaceholder = 'Search',
emptyMessage = 'No options found.',
disabled = false,
align = 'start',
}: SelectPopoverProps) {
const [open, setOpen] = useState(false);
const [search, setSearch] = useState('');
const selectedOption = options.find((option) => option.value === value);
const filteredOptions = useMemo(() => {
const term = search.trim().toLowerCase();
if (!term) return options;
return options.filter((option) =>
option.label.toLowerCase().includes(term),
);
}, [options, search]);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
disabled={disabled}
className="h-10 w-full justify-between px-3 font-normal shadow-none"
>
<span
className={cn(
'truncate',
!selectedOption && 'text-muted-foreground',
)}
>
{selectedOption?.label ?? placeholder}
</span>
<ChevronDown className="size-4 opacity-60" />
</Button>
</PopoverTrigger>
<PopoverContent align={align} className="w-72 p-0 shadow-none">
<div className="border-b p-3">
<Input
value={search}
onChange={(event) => setSearch(event.target.value)}
placeholder={searchPlaceholder}
/>
</div>
<div className="max-h-72 overflow-y-auto p-2">
{filteredOptions.length ? (
filteredOptions.map((option) => {
const selected = option.value === value;
return (
<button
key={option.value}
type="button"
disabled={option.disabled}
onClick={() => {
onValueChange(option.value);
setOpen(false);
}}
className={cn(
'flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-muted',
option.disabled && 'cursor-not-allowed opacity-60',
)}
>
<span className="flex size-4 shrink-0 items-center justify-center">
{selected ? <Check className="size-3" /> : null}
</span>
<span className="truncate">{option.label}</span>
</button>
);
})
) : (
<div className="px-2 py-6 text-center text-sm text-muted-foreground">
{emptyMessage}
</div>
)}
</div>
</PopoverContent>
</Popover>
);
}

View File

@@ -1,4 +1,6 @@
export { FormField } from './FormField'; export { FormField } from './FormField';
export { MultiSelectPopover } from './MultiSelectPopover'; export { MultiSelectPopover } from './MultiSelectPopover';
export type { MultiSelectOption } from './MultiSelectPopover'; export type { MultiSelectOption } from './MultiSelectPopover';
export { SelectPopover } from './SelectPopover';
export type { SelectPopoverOption } from './SelectPopover';
export { PasswordField } from './PasswordField'; export { PasswordField } from './PasswordField';

View File

@@ -1,373 +0,0 @@
'use client';
import { useState, useEffect, useRef, useCallback } from 'react';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Check, ArrowUp, ArrowDown } from 'lucide-react';
import { ProjectSelect } from '@/components/lookups/ProjectSelect';
import { PackageSelect } from '@/components/lookups/PackageSelect';
import { SegmentSelect } from '@/components/lookups/SegmentSelect';
import {
projectService,
packageService,
chainageService,
} from '@/services/api';
import {
Project,
Package as PackageType,
Chainage,
SessionContext,
} from '@/types';
import { cn } from '@/lib/utils';
type ProjectSelectionSectionProps = {
onSelectionComplete?: (session: SessionContext) => void;
onSelectionChange?: (session: SessionContext | null) => void;
asStep?: boolean;
hideButton?: boolean;
};
export function ProjectSelectionSection({
onSelectionComplete,
onSelectionChange,
asStep = false,
hideButton = false,
}: ProjectSelectionSectionProps) {
const [selectedProjectId, setSelectedProjectId] = useState('');
const [selectedPackageId, setSelectedPackageId] = useState('');
const [selectedChainageId, setSelectedChainageId] = useState('');
const [selectedProject, setSelectedProject] = useState<Project | null>(null);
const [selectedPackage, setSelectedPackage] = useState<PackageType | null>(
null,
);
const [selectedChainage, setSelectedChainage] = useState<Chainage | null>(
null,
);
const [error, setError] = useState<string | null>(null);
const lastReportedIdRef = useRef<string | null>(null);
const latestProjectIdRef = useRef('');
const latestPackageIdRef = useRef('');
const latestChainageIdRef = useRef('');
const handleProjectChange = useCallback((projectId: string) => {
latestProjectIdRef.current = projectId;
latestPackageIdRef.current = '';
latestChainageIdRef.current = '';
setSelectedProjectId(projectId);
setSelectedPackageId('');
setSelectedChainageId('');
setSelectedProject(null);
setSelectedPackage(null);
setSelectedChainage(null);
setError(null);
if (!projectId) {
return;
}
void projectService
.getProjectById(projectId)
.then((project) => {
if (latestProjectIdRef.current === projectId) {
setSelectedProject(project);
}
})
.catch((err) => {
if (latestProjectIdRef.current === projectId) {
console.error('Failed to resolve project:', err);
setError('Failed to load the selected project.');
}
});
}, []);
const handlePackageChange = useCallback((packageId: string) => {
latestPackageIdRef.current = packageId;
latestChainageIdRef.current = '';
setSelectedPackageId(packageId);
setSelectedChainageId('');
setSelectedPackage(null);
setSelectedChainage(null);
setError(null);
if (!packageId) {
return;
}
void packageService
.getPackageById(packageId)
.then((pkg) => {
if (latestPackageIdRef.current === packageId) {
setSelectedPackage(pkg);
}
})
.catch((err) => {
if (latestPackageIdRef.current === packageId) {
console.error('Failed to resolve package:', err);
setError('Failed to load the selected package.');
}
});
}, []);
const handleChainageChange = useCallback((chainageId: string) => {
latestChainageIdRef.current = chainageId;
setSelectedChainageId(chainageId);
setSelectedChainage(null);
setError(null);
if (!chainageId) {
return;
}
void chainageService
.getChainageById(chainageId)
.then((chainage) => {
if (latestChainageIdRef.current === chainageId) {
setSelectedChainage(chainage);
}
})
.catch((err) => {
if (latestChainageIdRef.current === chainageId) {
console.error('Failed to resolve segment:', err);
setError('Failed to load the selected segment.');
}
});
}, []);
// Handle change reporting
useEffect(() => {
if (onSelectionChange) {
const currentIds =
selectedProject && selectedPackage && selectedChainage
? `${selectedProject.id}-${selectedPackage.id}-${selectedChainage.id}`
: null;
if (currentIds !== lastReportedIdRef.current) {
lastReportedIdRef.current = currentIds;
if (selectedProject && selectedPackage && selectedChainage) {
onSelectionChange({
projectId: selectedProject.id,
projectName: selectedProject.name,
packageId: selectedPackage.id,
packageName: selectedPackage.name,
chainageId: selectedChainage.id,
chainageName: selectedChainage.segment_name,
chainageDirection: selectedChainage.direction,
});
} else {
onSelectionChange(null);
}
}
}
}, [selectedProject, selectedPackage, selectedChainage, onSelectionChange]);
const handleProceed = () => {
if (
selectedProject &&
selectedPackage &&
selectedChainage &&
onSelectionComplete
) {
onSelectionComplete({
projectId: selectedProject.id,
projectName: selectedProject.name,
packageId: selectedPackage.id,
packageName: selectedPackage.name,
chainageId: selectedChainage.id,
chainageName: selectedChainage.segment_name,
chainageDirection: selectedChainage.direction,
});
}
};
const isComplete = selectedProject && selectedPackage && selectedChainage;
// Step status helpers
const getStepStatus = (step: number) => {
if (step === 1) return selectedProjectId ? 'completed' : 'active';
if (step === 2)
return selectedPackageId
? 'completed'
: selectedProjectId
? 'active'
: 'pending';
if (step === 3)
return selectedChainageId
? 'completed'
: selectedPackageId
? 'active'
: 'pending';
return 'pending';
};
const content = (
<>
{/* Error Display */}
{error && (
<div className="p-4 rounded-md bg-destructive/10 border border-destructive/20 text-destructive text-sm mb-6">
{error}
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
<div className="space-y-2">
<Label htmlFor="project" className="text-sm font-semibold">
Project
</Label>
<ProjectSelect
value={selectedProjectId}
onValueChange={handleProjectChange}
enabled
/>
</div>
<div className="space-y-2">
<Label htmlFor="package" className="text-sm font-semibold">
Package
</Label>
<PackageSelect
value={selectedPackageId}
onValueChange={handlePackageChange}
projectId={selectedProjectId}
enabled={Boolean(selectedProjectId)}
disabled={!selectedProjectId}
/>
</div>
<div className="space-y-2">
<Label htmlFor="chainage" className="text-sm font-semibold">
Segment
</Label>
<SegmentSelect
value={selectedChainageId}
onValueChange={handleChainageChange}
packageId={selectedPackageId}
enabled={Boolean(selectedPackageId)}
disabled={!selectedPackageId}
/>
</div>
</div>
{/* Selected Summary - Only if not asStep or if specifically desired */}
{!asStep && isComplete && (
<div className="px-4 py-3 rounded-md bg-secondary/50 border text-sm mb-8">
<div className="flex items-center gap-2 flex-wrap text-muted-foreground">
<span className="font-semibold text-foreground">Selection:</span>
<span className="text-foreground">{selectedProject?.name}</span>
<span>/</span>
<span className="text-foreground">{selectedPackage?.name}</span>
<span>/</span>
<span className="text-foreground flex items-center gap-1.5">
{selectedChainage?.segment_name}
<span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-muted text-[10px] font-bold uppercase border">
{selectedChainage?.direction === 'UP' ? (
<ArrowUp className="h-2.5 w-2.5" />
) : (
<ArrowDown className="h-2.5 w-2.5" />
)}
{selectedChainage?.direction}
</span>
</span>
</div>
</div>
)}
{/* Proceed Button */}
{!hideButton && (
<Button
onClick={handleProceed}
disabled={!isComplete}
className="w-full h-14 text-base font-bold uppercase tracking-wider"
size="lg"
>
{isComplete ? 'Proceed to Upload' : 'Select all fields to proceed'}
</Button>
)}
</>
);
if (asStep) {
return content;
}
return (
<Card className="overflow-hidden">
<CardHeader className="pb-6">
<div className="flex flex-col gap-6">
<div>
<CardTitle className="text-2xl font-bold">
Select Project Segment
</CardTitle>
<CardDescription className="mt-2 text-base">
Select Project, Package & Segment to begin intelligent road
analysis.
</CardDescription>
</div>
{/* Step Progress Indicator */}
<div className="flex items-center justify-center pt-2">
{[1, 2, 3].map((step, index) => {
const status = getStepStatus(step);
const labels = ['Project', 'Package', 'Segment'];
return (
<div key={step} className="flex items-center">
<div className="flex flex-col items-center">
<div
className={cn(
'w-10 h-10 rounded-full flex items-center justify-center text-sm font-semibold transition-all',
status === 'completed'
? 'bg-primary text-primary-foreground'
: status === 'active'
? 'bg-primary text-primary-foreground ring-4 ring-primary/10'
: 'bg-muted text-muted-foreground',
)}
>
{status === 'completed' ? (
<Check className="h-5 w-5" />
) : (
step
)}
</div>
<span
className={cn(
'text-xs mt-2 font-medium',
status === 'pending'
? 'text-muted-foreground/60'
: 'text-foreground',
)}
>
{labels[index]}
</span>
</div>
{index < 2 && (
<div
className={cn(
'w-16 h-0.5 mx-2 mb-6 rounded-full',
getStepStatus(step + 1) !== 'pending'
? 'bg-primary'
: 'bg-border',
)}
/>
)}
</div>
);
})}
</div>
</div>
</CardHeader>
<CardContent className="pt-0">{content}</CardContent>
</Card>
);
}

View File

@@ -11,12 +11,3 @@ export interface SessionContext {
chainageDirection?: string | null; chainageDirection?: string | null;
} }
export const emptySessionContext: SessionContext = {
projectId: null,
projectName: null,
packageId: null,
packageName: null,
chainageId: null,
chainageName: null,
chainageDirection: null,
};