refactor: rename swift → cortex in code and documentation

Complete rename of "swift" terminology to "cortex" across the codebase:

Code Changes:
- Rename directories: lib/swift → lib/cortex, components/swift → components/cortex
- Rename API routes: /api/swift/* → /api/cortex/*
- Rename page routes: /epd/swift → /epd/cortex
- Rename store: swift-store.ts → cortex-store.ts

Type Renames:
- SwiftIntent → CortexIntent
- SwiftStore → CortexStore
- useSwiftStore → useCortexStore
- SwiftContext → CortexContext
- useSwiftVoice → useCortexVoice

Documentation Updates (docs/intent/):
- Safety Net → Nudge (Layer 3 rename)
- SafetySuggestion → NudgeSuggestion
- evaluateSafetyNet → evaluateNudge
- SWIFT_* feature flags → CORTEX_*
- All path references updated to match new structure

Files affected: 47 files, ~700 lines changed

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
colinislit
2025-12-30 09:18:06 +01:00
parent c8aaba657e
commit 2170b23348
62 changed files with 364 additions and 355 deletions

View File

@@ -0,0 +1,30 @@
'use client';
/**
* Artifact Area (v3.0 + E4)
*
* Displays artifacts using ArtifactContainer with tab support.
* Manages multiple artifacts with lifecycle actions.
*
* Epic: E1 (Foundation), E3 (Chat API), E4 (Artifact Area & Tabs)
* Stories: E1.S3, E3.S6, E4.S1, E4.S2
*/
import { useCortexStore } from '@/stores/cortex-store';
import { ArtifactContainer } from './artifact-container';
export function ArtifactArea() {
const openArtifacts = useCortexStore((s) => s.openArtifacts);
const activeArtifactId = useCortexStore((s) => s.activeArtifactId);
const switchArtifact = useCortexStore((s) => s.switchArtifact);
const closeArtifact = useCortexStore((s) => s.closeArtifact);
return (
<ArtifactContainer
artifacts={openArtifacts}
activeArtifactId={activeArtifactId}
onSelectArtifact={switchArtifact}
onCloseArtifact={closeArtifact}
/>
);
}

View File

@@ -0,0 +1,269 @@
'use client';
/**
* Artifact Container Component
*
* Container die meerdere artifacts kan beheren met tabs.
* Max 3 artifacts tegelijk, tabs alleen zichtbaar bij >1 artifact.
*
* Epic: E4 (Artifact Area & Tabs)
* Story: E4.S1 (ArtifactContainer component)
*/
import { ArtifactTab } from './artifact-tab';
import { AgendaBlock, type AgendaBlockProps } from './blocks/agenda-block';
import { DagnotatieBlock } from '../blocks/dagnotitie-block';
import { ZoekenBlock } from '../blocks/zoeken-block';
import { OverdrachtBlock } from '../blocks/overdracht-block';
import { PatientDashboardBlock } from '../blocks/patient-dashboard-block';
import { FallbackPicker } from '../blocks/fallback-picker';
import { APPOINTMENT_TYPES, type AppointmentTypeCode, type LocationClassCode } from '@/app/epd/agenda/types';
import type { Artifact, BlockType } from '@/stores/cortex-store';
interface ArtifactContainerProps {
artifacts: Artifact[];
activeArtifactId: string | null;
onSelectArtifact: (id: string) => void;
onCloseArtifact: (id: string) => void;
}
type AgendaIntent = 'agenda_query' | 'create_appointment' | 'cancel_appointment' | 'reschedule_appointment';
type AgendaMode = AgendaBlockProps['mode'];
const AGENDA_MODE_MAP: Record<AgendaIntent, AgendaMode> = {
agenda_query: 'list',
create_appointment: 'create',
cancel_appointment: 'cancel',
reschedule_appointment: 'reschedule',
};
const LOCATION_CODE_MAP: Record<string, LocationClassCode> = {
praktijk: 'AMB',
online: 'VR',
thuis: 'HH',
};
function coerceDate(value: unknown): Date | undefined {
if (value instanceof Date) return value;
if (typeof value === 'string' || typeof value === 'number') {
const parsed = new Date(value);
if (!Number.isNaN(parsed.getTime())) {
return parsed;
}
}
return undefined;
}
function coerceDateRange(raw: any): AgendaBlockProps['dateRange'] | undefined {
const start = coerceDate(raw?.start);
const end = coerceDate(raw?.end);
if (!start || !end) return undefined;
return {
start,
end,
label: typeof raw?.label === 'string' ? raw.label : 'custom',
};
}
function resolveAppointmentType(value: unknown): AppointmentTypeCode | undefined {
if (typeof value !== 'string') return undefined;
if (value in APPOINTMENT_TYPES) return value as AppointmentTypeCode;
return undefined;
}
function resolveLocation(value: unknown): LocationClassCode | undefined {
if (typeof value !== 'string') return undefined;
if (value in LOCATION_CODE_MAP) return LOCATION_CODE_MAP[value];
if (value === 'AMB' || value === 'VR' || value === 'HH') return value;
return undefined;
}
function buildAgendaPrefill(prefill: Record<string, any> | undefined): AgendaBlockProps['prefillData'] {
if (!prefill || typeof prefill !== 'object') return undefined;
const patient =
prefill.patient ||
(prefill.patientName || prefill.patientId
? {
id: prefill.patientId || '',
name: prefill.patientName || '',
}
: undefined);
const datetimeDate =
coerceDate(prefill?.datetime?.date) ||
(prefill?.datetime?.time ? new Date() : undefined);
const datetime = datetimeDate
? {
date: datetimeDate,
time: typeof prefill?.datetime?.time === 'string' ? prefill.datetime.time : '',
}
: undefined;
const appointmentType = resolveAppointmentType(prefill?.appointmentType || prefill?.type);
const location = resolveLocation(prefill?.location);
const newDatetimeDate =
coerceDate(prefill?.newDatetime?.date) ||
(prefill?.newDatetime?.time ? new Date() : undefined);
const newDatetime = newDatetimeDate
? {
date: newDatetimeDate,
time: typeof prefill?.newDatetime?.time === 'string' ? prefill.newDatetime.time : '',
}
: undefined;
return {
patient,
datetime,
type: appointmentType,
location,
notes: typeof prefill?.notes === 'string' ? prefill.notes : undefined,
identifier: prefill?.identifier,
newDatetime,
};
}
/**
* Render the appropriate block component based on artifact type
*/
function renderArtifactBlock(artifact: Artifact, onCloseArtifact: (id: string) => void) {
switch (artifact.type) {
case 'dagnotitie':
return <DagnotatieBlock key={artifact.id} prefill={artifact.prefill} />;
case 'zoeken':
return <ZoekenBlock key={artifact.id} prefill={artifact.prefill} />;
case 'overdracht':
return <OverdrachtBlock key={artifact.id} prefill={artifact.prefill} />;
case 'agenda_query':
case 'create_appointment':
case 'cancel_appointment':
case 'reschedule_appointment': {
const agendaType = artifact.type as AgendaIntent;
const rawPrefill = artifact.prefill as Record<string, any>;
const dateRange = coerceDateRange(rawPrefill?.dateRange);
const prefillData = buildAgendaPrefill(rawPrefill);
const appointments = Array.isArray(rawPrefill?.appointments)
? rawPrefill.appointments
: undefined;
const disambiguationOptions = Array.isArray(rawPrefill?.disambiguationOptions)
? rawPrefill.disambiguationOptions
: undefined;
return (
<AgendaBlock
key={artifact.id}
mode={AGENDA_MODE_MAP[agendaType]}
appointments={appointments}
dateRange={dateRange}
prefillData={prefillData}
disambiguationOptions={disambiguationOptions}
onClose={() => onCloseArtifact(artifact.id)}
/>
);
}
case 'patient-dashboard':
return <PatientDashboardBlock key={artifact.id} prefill={artifact.prefill} />;
case 'fallback':
return <FallbackPicker key={artifact.id} originalInput={artifact.prefill?.content} />;
default:
return (
<div className="p-4 text-slate-500">
Onbekend artifact type: {artifact.type}
</div>
);
}
}
/**
* Get user-friendly title for artifact type
*/
export function getArtifactTitle(type: BlockType, prefill?: any): string {
switch (type) {
case 'dagnotitie':
return prefill?.patientName
? `Dagnotitie - ${prefill.patientName}`
: 'Dagnotitie';
case 'zoeken':
return 'Patiënt Zoeken';
case 'overdracht':
return 'Dienst Overdracht';
case 'agenda_query':
return 'Agenda';
case 'create_appointment':
return prefill?.patientName
? `Nieuwe afspraak - ${prefill.patientName}`
: 'Nieuwe afspraak';
case 'cancel_appointment':
return 'Afspraak annuleren';
case 'reschedule_appointment':
return 'Afspraak verzetten';
case 'fallback':
return 'Kies een actie';
case 'patient-dashboard':
return prefill?.patientName
? `Dashboard - ${prefill.patientName}`
: 'Patiëntoverzicht';
default:
return 'Artifact';
}
}
export function ArtifactContainer({
artifacts,
activeArtifactId,
onSelectArtifact,
onCloseArtifact,
}: ArtifactContainerProps) {
// Find active artifact
const activeArtifact = artifacts.find((a) => a.id === activeArtifactId);
// Show placeholder if no artifacts
if (artifacts.length === 0) {
return (
<div className="h-full flex items-center justify-center bg-slate-50 p-6">
<div className="max-w-lg text-center text-slate-500">
<div className="text-5xl mb-4">📋</div>
<h3 className="text-xl font-medium text-slate-700 mb-3">
Artifacts verschijnen hier
</h3>
<p className="text-sm">
Vraag me iets in de chat om te beginnen!
</p>
</div>
</div>
);
}
return (
<div className="h-full flex flex-col bg-slate-50">
{/* Tabs - alleen tonen bij >1 artifact */}
{artifacts.length > 1 && (
<div className="flex bg-white border-b border-slate-200">
{artifacts.map((artifact) => (
<ArtifactTab
key={artifact.id}
artifact={artifact}
isActive={artifact.id === activeArtifactId}
onSelect={onSelectArtifact}
onClose={onCloseArtifact}
/>
))}
</div>
)}
{/* Active artifact content */}
<div className="flex-1 flex items-center justify-center p-6 overflow-y-auto">
{activeArtifact ? (
<div key={activeArtifact.id} className="artifact-enter w-full">
{renderArtifactBlock(activeArtifact, onCloseArtifact)}
</div>
) : (
<div className="text-slate-500">
Selecteer een artifact om te bekijken
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,63 @@
'use client';
/**
* Artifact Tab Component
*
* Tab voor een individueel artifact in de ArtifactContainer.
* Toont titel, close button, en active state.
*
* Epic: E4 (Artifact Area & Tabs)
* Story: E4.S1 (ArtifactContainer component)
*/
import { X } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { Artifact } from '@/stores/cortex-store';
interface ArtifactTabProps {
artifact: Artifact;
isActive: boolean;
onSelect: (id: string) => void;
onClose: (id: string) => void;
}
export function ArtifactTab({ artifact, isActive, onSelect, onClose }: ArtifactTabProps) {
return (
<div
className={cn(
'group flex items-center gap-2 px-4 py-2.5 border-r border-slate-200 cursor-pointer transition-colors',
'hover:bg-slate-50 min-w-[140px] max-w-[200px]',
isActive && 'bg-white border-b-2 border-b-amber-500'
)}
onClick={() => onSelect(artifact.id)}
>
{/* Tab title */}
<span
className={cn(
'flex-1 text-sm font-medium truncate',
isActive ? 'text-slate-900' : 'text-slate-600'
)}
title={artifact.title}
>
{artifact.title}
</span>
{/* Close button */}
<button
onClick={(e) => {
e.stopPropagation();
onClose(artifact.id);
}}
className={cn(
'p-0.5 rounded hover:bg-slate-200 text-slate-400 hover:text-slate-700 transition-colors',
'opacity-0 group-hover:opacity-100',
isActive && 'opacity-100'
)}
title="Sluiten"
aria-label={`Sluit ${artifact.title}`}
>
<X size={14} />
</button>
</div>
);
}

View File

@@ -0,0 +1,88 @@
'use client';
import React from 'react';
import { AppointmentTypeCode, LocationClassCode, CalendarEvent } from '@/app/epd/agenda/types';
import { AgendaListView } from './agenda-list-view';
import { AgendaCreateForm } from './agenda-create-form';
import { AgendaCancelView } from './agenda-cancel-view';
import { AgendaRescheduleForm } from './agenda-reschedule-form';
import { motion, AnimatePresence } from 'framer-motion';
export interface AgendaBlockProps {
mode: 'list' | 'create' | 'cancel' | 'reschedule';
appointments?: CalendarEvent[];
dateRange?: { start: Date; end: Date; label: string };
prefillData?: {
patient?: { id: string; name: string };
datetime?: { date: Date; time: string };
type?: AppointmentTypeCode;
location?: LocationClassCode;
notes?: string;
identifier?: { encounterId?: string; encounter?: CalendarEvent };
newDatetime?: { date: Date; time: string };
};
disambiguationOptions?: CalendarEvent[];
onClose?: () => void;
}
export function AgendaBlock({
mode,
appointments,
dateRange,
prefillData,
disambiguationOptions,
onClose,
}: AgendaBlockProps) {
const renderContent = () => {
switch (mode) {
case 'list':
return (
<AgendaListView
key="list"
appointments={appointments}
dateRange={dateRange}
onClose={onClose}
onCancelAppointment={(evt) => console.log('Cancel requested', evt)}
onViewDetails={(evt) => window.location.href = `/epd/agenda?focus=${evt.id}`}
/>
);
case 'create':
return <AgendaCreateForm key="create" prefillData={prefillData} onClose={onClose} />;
case 'cancel':
return (
<AgendaCancelView
key="cancel"
disambiguationOptions={disambiguationOptions}
prefillData={prefillData}
onClose={onClose}
/>
);
case 'reschedule':
return <AgendaRescheduleForm key="reschedule" prefillData={prefillData} onClose={onClose} />;
default:
return <div key="error" className="p-4 text-red-500">Unknown mode: {mode}</div>;
}
};
return (
<motion.div
initial={{ opacity: 0, y: 20, scale: 0.98 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: 10, scale: 0.98 }}
transition={{ type: "spring", stiffness: 350, damping: 25 }}
className="w-full max-w-[600px] max-h-[80vh] h-[600px] overflow-hidden bg-white/95 backdrop-blur-xl border border-black/5 rounded-2xl shadow-2xl flex flex-col"
>
<AnimatePresence mode="wait" initial={false}>
<motion.div
key={mode}
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -20 }}
transition={{ duration: 0.2 }}
className="flex flex-col h-full overflow-hidden"
>
{renderContent()}
</motion.div>
</AnimatePresence>
</motion.div>
);
}

View File

@@ -0,0 +1,223 @@
'use client';
import React, { useState } from 'react';
import { format } from 'date-fns';
import { nl } from 'date-fns/locale';
import { AlertTriangle, Calendar, Clock, X, CheckCircle2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Label } from '@/components/ui/label';
import { cancelEncounter } from '@/app/epd/agenda/actions';
import { CalendarEvent, APPOINTMENT_TYPES, AppointmentTypeCode } from '@/app/epd/agenda/types';
import { motion } from 'framer-motion';
interface AgendaCancelViewProps {
disambiguationOptions?: CalendarEvent[];
prefillData?: {
identifier?: { encounterId?: string };
};
onClose?: () => void;
}
export function AgendaCancelView({ disambiguationOptions, prefillData, onClose }: AgendaCancelViewProps) {
const [selectedEncounterId, setSelectedEncounterId] = useState<string | undefined>(
prefillData?.identifier?.encounterId
);
// If we have disambiguation options and no selection yet, default to first?
// Better to let user choose.
const [isSubmitting, setIsSubmitting] = useState(false);
const [isSuccess, setIsSuccess] = useState(false);
const [error, setError] = useState<string | null>(null);
// If there's only one option provided via disambiguationOptions (and no prefill), select it automatically?
// Logic: if prefill encounterId is set, use that.
// If not, and disambiguationOptions has 1 item, use that.
// If not, wait for user selection.
const effectiveEncounter = disambiguationOptions?.find(e => e.id === selectedEncounterId) ||
(disambiguationOptions?.length === 1 ? disambiguationOptions[0] : undefined);
const handleCancel = async () => {
const idToCancel = selectedEncounterId || effectiveEncounter?.id;
if (!idToCancel) {
setError('Selecteer eerst een afspraak om te annuleren.');
return;
}
setIsSubmitting(true);
setError(null);
try {
const result = await cancelEncounter(idToCancel);
if (result.success) {
setIsSuccess(true);
// Wait a moment before closing or let user close
setTimeout(() => onClose?.(), 2000);
} else {
setError(result.error || 'Kon de afspraak niet annuleren.');
}
} catch (err) {
console.error('Cancel error:', err);
setError('Er is een onverwachte fout opgetreden.');
} finally {
setIsSubmitting(false);
}
};
if (isSuccess) {
return (
<div className="flex flex-col items-center justify-center p-8 text-center h-full">
<div className="bg-green-50 p-3 rounded-full mb-4">
<CheckCircle2 className="h-8 w-8 text-green-600" />
</div>
<h3 className="text-lg font-semibold text-gray-900">Afspraak geannuleerd</h3>
<p className="text-sm text-gray-500 mt-1 mb-6">De afspraak is succesvol verwijderd uit de agenda.</p>
<Button onClick={onClose} variant="outline" className="border-black/5 bg-white/50 hover:bg-white">Sluiten</Button>
</div>
);
}
// Disambiguation Mode
if (!effectiveEncounter && disambiguationOptions && disambiguationOptions.length > 1) {
return (
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.3 }}
className="flex flex-col h-full bg-transparent"
>
<div className="flex items-center justify-between p-5 border-b border-black/5">
<h3 className="font-semibold text-lg text-red-700">Afspraak annuleren</h3>
<Button variant="ghost" size="icon" onClick={onClose} className="h-9 w-9 hover:bg-black/5 rounded-full">
<X className="h-5 w-5" />
</Button>
</div>
<div className="flex-1 p-5 overflow-y-auto">
<p className="text-sm text-gray-600 mb-4 font-medium">
Er zijn meerdere afspraken gevonden. Welke wil je annuleren?
</p>
<RadioGroup value={selectedEncounterId} onValueChange={setSelectedEncounterId} className="space-y-3">
{disambiguationOptions.map((evt) => {
const encounter = evt.extendedProps.encounter;
const typeCode = encounter.type_code as AppointmentTypeCode;
const dateStr = format(new Date(evt.start), 'd MMM yyyy', { locale: nl });
const timeStr = format(new Date(evt.start), 'HH:mm');
return (
<div key={evt.id} className="flex items-center space-x-3 border border-black/5 rounded-xl p-4 hover:bg-white/50 cursor-pointer bg-white/40 transition-colors">
<RadioGroupItem value={evt.id} id={evt.id} />
<Label htmlFor={evt.id} className="flex-1 cursor-pointer">
<div className="font-semibold text-gray-900">{evt.title}</div>
<div className="text-sm text-gray-500 mt-0.5">
{dateStr} om {timeStr} {encounter.type_display || APPOINTMENT_TYPES[typeCode]}
</div>
</Label>
</div>
);
})}
</RadioGroup>
</div>
<div className="p-5 bg-gray-50/80 backdrop-blur-sm border-t border-black/5 flex justify-between gap-3">
<Button variant="outline" onClick={onClose} className="flex-1 border-black/10 bg-white/50 hover:bg-white h-10 rounded-lg">Annuleren</Button>
<Button
onClick={() => { /* State updates automatically via RadioGroup */ }}
disabled={!selectedEncounterId}
className="flex-1 bg-red-600 hover:bg-red-700 text-white shadow-md hover:shadow-lg h-10 rounded-lg"
>
Volgende
</Button>
</div>
</motion.div>
);
}
// Confirmation Mode (Single Match)
if (effectiveEncounter) {
const encounter = effectiveEncounter.extendedProps.encounter;
const typeCode = encounter.type_code as AppointmentTypeCode;
const dateStr = format(new Date(effectiveEncounter.start), 'EEEE d MMMM yyyy', { locale: nl });
const timeStr = format(new Date(effectiveEncounter.start), 'HH:mm');
const endTimeStr = effectiveEncounter.end ? format(new Date(effectiveEncounter.end), 'HH:mm') : '';
return (
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.3 }}
className="flex flex-col h-full bg-transparent"
>
<div className="flex items-center justify-between p-5 border-b border-black/5">
<h3 className="font-semibold text-lg text-red-700">Weet je het zeker?</h3>
<Button variant="ghost" size="icon" onClick={onClose} className="h-9 w-9 hover:bg-black/5 rounded-full">
<X className="h-5 w-5" />
</Button>
</div>
<div className="flex-1 p-5">
<div className="bg-red-50/70 border border-red-100/50 rounded-xl p-4 mb-6">
<div className="flex items-start gap-3">
<div className="p-2 bg-red-100 rounded-full mt-0.5">
<AlertTriangle className="h-4 w-4 text-red-600" />
</div>
<div className="text-sm text-red-900">
<p className="font-semibold text-base">Deze actie kan niet ongedaan worden gemaakt.</p>
<p className="mt-1 opacity-90 leading-relaxed">De afspraak met <span className="font-semibold">{effectiveEncounter.title}</span> wordt permanent uit de agenda verwijderd.</p>
</div>
</div>
</div>
<div className="border border-black/5 rounded-xl p-5 bg-white/60 shadow-sm backdrop-blur-sm">
<h4 className="font-semibold text-gray-900 mb-3 text-lg">{effectiveEncounter.title}</h4>
<div className="space-y-3 text-sm text-gray-600">
<div className="flex items-center gap-3">
<Calendar className="h-4 w-4 text-gray-400" />
<span className="capitalize font-medium">{dateStr}</span>
</div>
<div className="flex items-center gap-3">
<Clock className="h-4 w-4 text-gray-400" />
<span className="font-medium">{timeStr} {endTimeStr && `- ${endTimeStr}`}</span>
</div>
<div className="flex items-center gap-3">
<span className="inline-block w-5 text-center text-gray-400"></span>
<span className="font-medium bg-gray-100 px-2 py-0.5 rounded text-gray-700">{encounter.type_display || APPOINTMENT_TYPES[typeCode]}</span>
</div>
</div>
</div>
{error && (
<div className="mt-4 p-4 bg-red-50 text-red-700 text-sm rounded-xl border border-red-100">
{error}
</div>
)}
</div>
<div className="p-5 bg-gray-50/80 backdrop-blur-sm border-t border-black/5 flex justify-between gap-3">
<Button variant="outline" onClick={onClose} disabled={isSubmitting} className="flex-1 border-black/10 bg-white/50 hover:bg-white h-10 rounded-lg">
Terug
</Button>
<Button
onClick={handleCancel}
disabled={isSubmitting}
className="flex-1 bg-red-600 hover:bg-red-700 text-white shadow-md hover:shadow-lg h-10 rounded-lg"
>
{isSubmitting ? 'Annuleren...' : 'Ja, annuleer afspraak'}
</Button>
</div>
</motion.div>
);
}
// Fallback / Loading
return (
<div className="p-4">
<p>Geen afspraak geselecteerd.</p>
<Button onClick={onClose} variant="link">Sluiten</Button>
</div>
);
}

View File

@@ -0,0 +1,371 @@
'use client';
import React, { useState, useEffect, useRef } from 'react';
import { format, addHours, parseISO } from 'date-fns';
import { nl } from 'date-fns/locale';
import { Calendar, Clock, MapPin, User, Check, X, AlertCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { motion } from 'framer-motion';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { createEncounter } from '@/app/epd/agenda/actions';
import {
APPOINTMENT_TYPES,
LOCATION_CLASSES,
AppointmentTypeCode,
LocationClassCode,
APPOINTMENT_TYPE_COLORS
} from '@/app/epd/agenda/types';
import { AgendaErrorAlert } from './agenda-error-state';
interface AgendaCreateFormProps {
prefillData?: {
patient?: { id: string; name: string };
datetime?: { date: Date; time: string };
type?: AppointmentTypeCode;
location?: LocationClassCode;
notes?: string;
};
onClose?: () => void;
}
interface PatientResult {
id: string;
name: string;
bsn?: string;
birthDate?: string;
}
export function AgendaCreateForm({ prefillData, onClose }: AgendaCreateFormProps) {
// Form State
const [patientId, setPatientId] = useState<string>(prefillData?.patient?.id || '');
const [patientName, setPatientName] = useState<string>(prefillData?.patient?.name || '');
const [date, setDate] = useState<string>(
prefillData?.datetime?.date ? format(prefillData.datetime.date, 'yyyy-MM-dd') : format(new Date(), 'yyyy-MM-dd')
);
const [time, setTime] = useState<string>(prefillData?.datetime?.time || '09:00');
const [type, setType] = useState<AppointmentTypeCode>(prefillData?.type || 'behandeling');
const [location, setLocation] = useState<LocationClassCode>(prefillData?.location || 'AMB');
const [notes, setNotes] = useState<string>(prefillData?.notes || '');
// UI State
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
// Patient Search State
const [searchQuery, setSearchQuery] = useState('');
const [searchResults, setSearchResults] = useState<PatientResult[]>([]);
const [isSearching, setIsSearching] = useState(false);
const [showResults, setShowResults] = useState(false);
const searchRef = useRef<HTMLDivElement>(null);
// Initialize search query if patient is prefilled but we want to allow editing
useEffect(() => {
if (prefillData?.patient?.name) {
setSearchQuery(prefillData.patient.name);
}
}, [prefillData]);
// Handle outside click to close search results
useEffect(() => {
function handleClickOutside(event: MouseEvent) {
if (searchRef.current && !searchRef.current.contains(event.target as Node)) {
setShowResults(false);
}
}
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
// Debounced search
useEffect(() => {
const timer = setTimeout(async () => {
if (searchQuery.length < 2 || patientId) return; // Don't search if too short or if patient already selected
setIsSearching(true);
try {
const res = await fetch(`/api/cortex/patients/search?q=${encodeURIComponent(searchQuery)}`);
if (res.ok) {
const data = await res.json();
setSearchResults(data.patients || []);
setShowResults(true);
}
} catch (err) {
console.error('Failed to search patients', err);
} finally {
setIsSearching(false);
}
}, 300);
return () => clearTimeout(timer);
}, [searchQuery, patientId]);
const handlePatientSelect = (patient: PatientResult) => {
setPatientId(patient.id);
setPatientName(patient.name);
setSearchQuery(patient.name);
setShowResults(false);
};
const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setSearchQuery(e.target.value);
setPatientId(''); // Clear selection on edit
setPatientName('');
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!patientId) {
setError('Selecteer a.u.b. een patiënt.');
return;
}
setIsSubmitting(true);
setError(null);
try {
// Construct Date objects
const startDate = new Date(`${date}T${time}`);
const endDate = addHours(startDate, 1); // Default duration 1 hour
// Map codes to displays
const typeDisplay = APPOINTMENT_TYPES[type];
const locationDisplay = LOCATION_CLASSES[location];
const result = await createEncounter({
patientId,
periodStart: startDate.toISOString(),
periodEnd: endDate.toISOString(),
typeCode: type,
typeDisplay,
classCode: location,
classDisplay: locationDisplay,
notes: notes || undefined,
});
if (result.success) {
onClose?.(); // Close on success
} else {
setError(result.error || 'Er is een fout opgetreden.');
}
} catch (err) {
console.error('Submit error:', err);
setError('Er is een onverwachte fout opgetreden.');
} finally {
setIsSubmitting(false);
}
};
return (
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.3, ease: 'easeOut' }}
className="flex flex-col h-full bg-transparent"
>
{/* Header */}
<div className="flex items-center justify-between p-5 border-b border-black/5">
<h3 className="font-semibold text-lg text-gray-900">Nieuwe afspraak inplannen</h3>
<Button variant="ghost" size="icon" onClick={onClose} className="h-9 w-9 text-gray-500 hover:text-gray-900 hover:bg-black/5 rounded-full">
<X className="h-5 w-5" />
</Button>
</div>
{/* Form Body */}
<form onSubmit={handleSubmit} className="flex-1 overflow-y-auto p-5 space-y-5">
{error && (
<AgendaErrorAlert
error={error}
onDismiss={() => setError(null)}
showFallbackLink={true}
/>
)}
{/* Patient Selection */}
<div className="space-y-2" ref={searchRef}>
<Label htmlFor="patient" className="text-sm font-medium text-gray-700">Patiënt <span className="text-red-500">*</span></Label>
<div className="relative">
<div className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400">
<User className="h-4 w-4" />
</div>
<Input
id="patient"
value={searchQuery}
onChange={handleSearchChange}
placeholder="Zoek op naam..."
className="pl-10 h-10 bg-white/50 backdrop-blur-sm border-black/10 focus:bg-white transition-colors"
autoComplete="off"
/>
{isSearching && (
<div className="absolute right-3 top-1/2 -translate-y-1/2">
<div className="animate-spin h-3 w-3 border-2 border-teal-500 border-t-transparent rounded-full"></div>
</div>
)}
{showResults && searchResults.length > 0 && (
<div className="absolute z-10 w-full mt-1 bg-white/95 backdrop-blur-xl border border-black/5 rounded-xl shadow-xl max-h-48 overflow-y-auto">
{searchResults.map((p) => (
<button
key={p.id}
type="button"
onClick={() => handlePatientSelect(p)}
className="w-full text-left px-4 py-3 hover:bg-teal-50/50 text-sm flex flex-col border-b last:border-0 border-black/5 transition-colors"
>
<span className="font-medium text-gray-900">{p.name}</span>
<span className="text-xs text-gray-500 mt-0.5">
{p.birthDate && format(new Date(p.birthDate), 'dd-MM-yyyy')}
{p.bsn && ` • BSN: ${p.bsn}`}
</span>
</button>
))}
</div>
)}
</div>
</div>
{/* Date & Time */}
<div className="grid grid-cols-2 gap-5">
<div className="space-y-2">
<Label htmlFor="date" className="text-sm font-medium text-gray-700">Datum <span className="text-red-500">*</span></Label>
<div className="relative">
<div className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400">
<Calendar className="h-4 w-4" />
</div>
<Input
id="date"
type="date"
value={date}
onChange={(e) => setDate(e.target.value)}
className="pl-10 h-10 bg-white/50 backdrop-blur-sm border-black/10 focus:bg-white transition-colors"
required
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="time" className="text-sm font-medium text-gray-700">Tijd <span className="text-red-500">*</span></Label>
<div className="relative">
<div className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400">
<Clock className="h-4 w-4" />
</div>
<Input
id="time"
type="time"
value={time}
onChange={(e) => setTime(e.target.value)}
className="pl-10 h-10 bg-white/50 backdrop-blur-sm border-black/10 focus:bg-white transition-colors"
required
/>
</div>
</div>
</div>
{/* Type Selection */}
<div className="space-y-2">
<Label className="text-sm font-medium text-gray-700">Type afspraak <span className="text-red-500">*</span></Label>
<div className="grid grid-cols-2 gap-2.5">
{(Object.keys(APPOINTMENT_TYPES) as AppointmentTypeCode[]).map((t) => {
const bg = APPOINTMENT_TYPE_COLORS[t].bg;
const text = APPOINTMENT_TYPE_COLORS[t].text;
const border = APPOINTMENT_TYPE_COLORS[t].border;
const isActive = type === t;
return (
<button
key={t}
type="button"
onClick={() => setType(t)}
className={`
px-3 py-2.5 text-xs font-medium rounded-lg border text-left transition-all
${isActive ? 'ring-2 ring-offset-1 ring-teal-500 shadow-sm' : 'hover:bg-black/5 bg-white/40'}
`}
style={{
backgroundColor: isActive ? bg : undefined,
color: isActive ? text : '#374151',
borderColor: isActive ? border : 'rgba(0,0,0,0.1)'
}}
>
<div className="flex items-center justify-between">
<span>{APPOINTMENT_TYPES[t]}</span>
{isActive && <Check className="h-3.5 w-3.5" />}
</div>
</button>
);
})}
</div>
</div>
{/* Location Selection */}
<div className="space-y-2">
<Label className="text-sm font-medium text-gray-700">Locatie <span className="text-red-500">*</span></Label>
<div className="flex gap-2.5">
{(Object.keys(LOCATION_CLASSES) as LocationClassCode[]).map((l) => (
<button
key={l}
type="button"
onClick={() => setLocation(l)}
className={`
flex-1 py-2.5 px-3 text-xs font-medium rounded-lg border flex items-center justify-center gap-2 transition-all
${location === l
? 'bg-teal-50 border-teal-200 text-teal-800 ring-2 ring-teal-500 ring-opacity-20 shadow-sm'
: 'bg-white/40 border-black/10 text-gray-600 hover:bg-black/5'}
`}
>
{l === 'AMB' && <MapPin className="h-3.5 w-3.5" />}
{l === 'VR' && <div className="h-3.5 w-3.5 border rounded-full" />}
{l === 'HH' && <div className="h-3.5 w-3.5 bg-current rounded-sm" />}
{LOCATION_CLASSES[l]}
</button>
))}
</div>
</div>
{/* Notes */}
<div className="space-y-2">
<Label htmlFor="notes" className="text-sm font-medium text-gray-700">Notities (optioneel)</Label>
<Textarea
id="notes"
value={notes}
onChange={(e) => setNotes(e.target.value)}
placeholder="Bijv. bijzonderheden, reden van komst..."
className="h-24 text-sm resize-none bg-white/50 backdrop-blur-sm border-black/10 focus:bg-white transition-colors rounded-lg"
/>
</div>
<div className="pt-2"></div>
</form>
{/* Footer / Actions */}
<div className="p-5 bg-gray-50/80 backdrop-blur-sm border-t border-black/5 flex justify-between gap-3">
<Button variant="outline" type="button" onClick={onClose} disabled={isSubmitting} className="flex-1 border-black/10 bg-white/50 hover:bg-white h-10 rounded-lg">
Annuleren
</Button>
<Button
type="button"
onClick={handleSubmit}
disabled={isSubmitting}
className="flex-1 bg-teal-600 hover:bg-teal-700 text-white shadow-md hover:shadow-lg transition-all h-10 rounded-lg"
>
{isSubmitting ? (
<div className="flex items-center gap-2">
<div className="h-3 w-3 border-2 border-white/50 border-t-white rounded-full animate-spin" />
<span>Bezig...</span>
</div>
) : (
'Afspraak inplannen'
)}
</Button>
</div>
</motion.div>
);
}

View File

@@ -0,0 +1,186 @@
'use client';
import React from 'react';
import { AlertCircle, RefreshCw, ExternalLink } from 'lucide-react';
import { Button } from '@/components/ui/button';
/**
* AgendaErrorState Component
*
* Reusable error display for agenda operations.
* Epic 5.S3 - Provides user-friendly error messages with fallback links.
*/
interface AgendaErrorStateProps {
error: string | Error;
onRetry?: () => void;
showFallbackLink?: boolean;
context?: 'query' | 'create' | 'cancel' | 'reschedule';
}
/**
* Get user-friendly error message based on error type and context
*/
function getUserFriendlyMessage(error: string | Error, context?: string): string {
const errorString = error instanceof Error ? error.message : error;
// Check for specific error types
if (errorString.includes('401') || errorString.includes('Niet geautoriseerd')) {
return 'Je sessie is verlopen. Log opnieuw in.';
}
if (errorString.includes('404')) {
return 'De gevraagde afspraak kon niet worden gevonden.';
}
if (errorString.includes('403')) {
return 'Je hebt geen toegang tot deze afspraak.';
}
if (errorString.includes('500') || errorString.includes('server')) {
return 'Er ging iets mis op de server. Probeer het opnieuw.';
}
if (errorString.includes('network') || errorString.includes('Failed to fetch')) {
return 'Geen internetverbinding. Controleer je netwerkverbinding.';
}
if (errorString.includes('timeout')) {
return 'De aanvraag duurde te lang. Probeer het opnieuw.';
}
// Context-specific messages
if (context === 'query') {
return 'Er ging iets mis bij het ophalen van je afspraken.';
}
if (context === 'create') {
return 'Er ging iets mis bij het aanmaken van de afspraak.';
}
if (context === 'cancel') {
return 'Er ging iets mis bij het annuleren van de afspraak.';
}
if (context === 'reschedule') {
return 'Er ging iets mis bij het verzetten van de afspraak.';
}
// Fallback to provided error or generic message
return errorString || 'Er is een onverwachte fout opgetreden.';
}
export function AgendaErrorState({
error,
onRetry,
showFallbackLink = true,
context,
}: AgendaErrorStateProps) {
const userMessage = getUserFriendlyMessage(error, context);
// Check if this is an auth error (should redirect)
const isAuthError = userMessage.includes('sessie') || userMessage.includes('Log opnieuw in');
if (isAuthError) {
// Redirect to login
if (typeof window !== 'undefined') {
window.location.href = '/login';
}
return null;
}
return (
<div className="flex flex-col items-center justify-center p-8 text-center">
<div className="bg-red-50 p-4 rounded-full mb-4">
<AlertCircle className="h-8 w-8 text-red-500" />
</div>
<h3 className="font-semibold text-gray-900 mb-2">Er ging iets mis</h3>
<p className="text-sm text-gray-600 mb-6 max-w-md">
{userMessage}
</p>
<div className="flex flex-col sm:flex-row gap-3">
{onRetry && (
<Button
onClick={onRetry}
variant="outline"
className="gap-2 border-teal-200 text-teal-700 hover:bg-teal-50"
>
<RefreshCw className="h-4 w-4" />
Probeer opnieuw
</Button>
)}
{showFallbackLink && (
<Button
onClick={() => {
window.location.href = '/epd/agenda';
}}
variant={onRetry ? 'ghost' : 'outline'}
className="gap-2 text-teal-700 hover:bg-teal-50"
>
<ExternalLink className="h-4 w-4" />
Open volledige agenda
</Button>
)}
</div>
{/* Technical details (collapsed by default) */}
{process.env.NODE_ENV === 'development' && (
<details className="mt-6 text-left w-full max-w-md">
<summary className="text-xs text-gray-500 cursor-pointer hover:text-gray-700">
Technische details (dev only)
</summary>
<pre className="mt-2 text-xs bg-gray-100 p-3 rounded overflow-auto text-gray-700">
{error instanceof Error ? error.stack : error}
</pre>
</details>
)}
</div>
);
}
/**
* Inline error alert (for forms)
*/
interface AgendaErrorAlertProps {
error: string | Error;
onDismiss?: () => void;
showFallbackLink?: boolean;
}
export function AgendaErrorAlert({
error,
onDismiss,
showFallbackLink = false,
}: AgendaErrorAlertProps) {
const userMessage = getUserFriendlyMessage(error);
return (
<div className="p-3 bg-red-50 border border-red-200 rounded-md flex items-start gap-2 text-sm text-red-700">
<AlertCircle className="h-4 w-4 mt-0.5 flex-shrink-0" />
<div className="flex-1">
<p>{userMessage}</p>
{showFallbackLink && (
<a
href="/epd/agenda"
className="text-xs underline hover:no-underline mt-1 inline-block"
>
Open volledige agenda
</a>
)}
</div>
{onDismiss && (
<button
onClick={onDismiss}
className="text-red-400 hover:text-red-600"
aria-label="Sluit melding"
>
×
</button>
)}
</div>
);
}

View File

@@ -0,0 +1,199 @@
'use client';
import React from 'react';
import { format } from 'date-fns';
import { nl } from 'date-fns/locale';
import { Calendar, MapPin, Globe, Home, Clock, X, Info, ChevronRight, Ban } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { motion } from 'framer-motion';
import {
CalendarEvent,
APPOINTMENT_TYPE_COLORS,
APPOINTMENT_TYPES,
LOCATION_CLASSES,
LocationClassCode,
AppointmentTypeCode
} from '@/app/epd/agenda/types';
interface AgendaListViewProps {
appointments?: CalendarEvent[];
dateRange?: { start: Date; end: Date; label: string };
onClose?: () => void;
onCancelAppointment?: (encounter: CalendarEvent) => void;
onViewDetails?: (encounter: CalendarEvent) => void;
}
const containerVariants = {
hidden: { opacity: 0 },
show: {
opacity: 1,
transition: {
staggerChildren: 0.1
}
}
};
const itemVariants = {
hidden: { opacity: 0, y: 10 },
show: { opacity: 1, y: 0 }
};
export function AgendaListView({
appointments = [],
dateRange,
onClose,
onCancelAppointment,
onViewDetails
}: AgendaListViewProps) {
const formatDateLabel = () => {
if (dateRange?.label) {
if (dateRange.label === 'vandaag' || dateRange.label === 'morgen') {
const dateStr = format(dateRange.start, 'd MMMM', { locale: nl });
return `Afspraken ${dateRange.label} - ${dateStr}`;
}
return `Afspraken ${dateRange.label}`;
}
// Fallback if no specific label
if (appointments.length > 0) {
return `Afspraken ${format(new Date(appointments[0].start), 'd MMMM', { locale: nl })}`;
}
return 'Afspraken';
};
const getLocationIcon = (classCode: string) => {
switch (classCode as LocationClassCode) {
case 'AMB': return <MapPin className="h-3 w-3" />;
case 'VR': return <Globe className="h-3 w-3" />;
case 'HH': return <Home className="h-3 w-3" />;
default: return <MapPin className="h-3 w-3" />;
}
};
return (
<div className="flex flex-col h-full bg-transparent">
{/* Header */}
<div className="flex items-center justify-between p-5 border-b border-black/5">
<div className="flex items-center gap-3 text-teal-700">
<div className="p-2 bg-teal-50 rounded-lg">
<Calendar className="h-5 w-5" />
</div>
<h3 className="font-semibold text-lg text-gray-900 capitalize leading-tight">{formatDateLabel()}</h3>
</div>
<Button variant="ghost" size="icon" onClick={onClose} className="h-9 w-9 text-gray-500 hover:text-gray-900 hover:bg-black/5 rounded-full">
<X className="h-5 w-5" />
</Button>
</div>
{/* Body */}
<motion.div
className="flex-1 overflow-y-auto p-5 space-y-3"
variants={containerVariants}
initial="hidden"
animate="show"
>
{appointments.length === 0 ? (
<motion.div
variants={itemVariants}
className="flex flex-col items-center justify-center h-full text-center text-gray-500"
>
<div className="bg-gray-50/50 p-4 rounded-full mb-4">
<Calendar className="h-8 w-8 text-gray-400" />
</div>
<p className="font-medium text-gray-900">Geen afspraken gevonden</p>
<p className="text-sm text-gray-500 mt-1 max-w-[200px]">
Er staan geen afspraken gepland voor deze periode.
</p>
<Button variant="outline" className="mt-6 gap-2 text-teal-700 border-teal-200/50 hover:bg-teal-50/50 bg-white/50">
<span className="text-lg leading-none">+</span> Maak nieuwe afspraak
</Button>
</motion.div>
) : (
appointments.map((evt) => {
const encounter = evt.extendedProps.encounter;
const patient = evt.extendedProps.patient;
const typeCode = encounter.type_code as AppointmentTypeCode;
const typeColor = APPOINTMENT_TYPE_COLORS[typeCode] || APPOINTMENT_TYPE_COLORS.overig;
const classCode = encounter.class_code as LocationClassCode;
const startTime = format(new Date(evt.start), 'HH:mm');
const endTime = evt.end ? format(new Date(evt.end), 'HH:mm') : '';
return (
<motion.div
key={evt.id}
variants={itemVariants}
className="group border border-black/5 rounded-2xl p-4 hover:border-teal-200/50 hover:shadow-md transition-all bg-white/60 hover:bg-white/90 backdrop-blur-sm"
>
<div className="flex justify-between items-start mb-3">
<div className="flex flex-col">
<div className="flex items-center gap-2 text-sm font-medium text-gray-500 mb-0.5">
<Clock className="h-3.5 w-3.5" />
<span>{startTime} {endTime && `- ${endTime}`}</span>
</div>
<button
className="text-left text-base font-semibold text-gray-900 hover:text-teal-700 hover:underline transition-colors"
onClick={() => console.log('Open patient context', patient?.id)}
>
{evt.title}
</button>
</div>
<Badge
variant="outline"
style={{
backgroundColor: typeColor.bg,
color: typeColor.text,
borderColor: typeColor.border
}}
className="whitespace-nowrap shadow-none px-2.5 py-0.5 text-xs font-medium rounded-md"
>
{encounter.type_display || APPOINTMENT_TYPES[typeCode] || typeCode}
</Badge>
</div>
<div className="flex items-center gap-4 text-xs text-gray-500 mt-2">
<div className="flex items-center gap-1.5" title={LOCATION_CLASSES[classCode]}>
{getLocationIcon(classCode)}
<span>{encounter.class_display || LOCATION_CLASSES[classCode] || classCode}</span>
</div>
{encounter.status === 'cancelled' && (
<Badge variant="destructive" className="h-5 px-1.5 font-normal rounded-sm">Geannuleerd</Badge>
)}
</div>
<div className="flex items-center justify-end gap-2 mt-4 pt-3 border-t border-black/5 opacity-0 group-hover:opacity-100 transition-opacity">
<Button
variant="ghost"
size="sm"
className="h-8 text-xs font-medium text-gray-500 hover:text-red-600 hover:bg-red-50/50 rounded-lg px-3"
onClick={() => onCancelAppointment?.(evt)}
>
Annuleren
</Button>
<Button
variant="ghost"
size="sm"
className="h-8 text-xs font-medium text-teal-700 hover:bg-teal-50/50 rounded-lg px-3"
onClick={() => onViewDetails?.(evt)}
>
Details <ChevronRight className="ml-1 h-3 w-3" />
</Button>
</div>
</motion.div>
);
})
)}
</motion.div>
{/* Footer */}
<div className="p-5 bg-gray-50/80 backdrop-blur-sm border-t border-black/5 text-center">
<a
href="/epd/agenda"
className="text-sm font-medium text-teal-700 hover:text-teal-800 hover:underline inline-flex items-center gap-1 transition-colors"
>
Open volledige agenda <ChevronRight className="h-4 w-4" />
</a>
</div>
</div>
);
}

View File

@@ -0,0 +1,220 @@
'use client';
import React, { useState, useEffect } from 'react';
import { format, addHours } from 'date-fns';
import { nl } from 'date-fns/locale';
import { Calendar, Clock, X, ArrowRight, AlertCircle, CheckCircle2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { rescheduleEncounter } from '@/app/epd/agenda/actions';
import { CalendarEvent } from '@/app/epd/agenda/types';
import { motion } from 'framer-motion';
interface AgendaRescheduleFormProps {
prefillData?: {
identifier?: { encounterId?: string; encounter?: CalendarEvent };
newDatetime?: { date: Date; time: string };
};
onClose?: () => void;
}
export function AgendaRescheduleForm({ prefillData, onClose }: AgendaRescheduleFormProps) {
// Use encounter from prefill if provided directly (we might need to pass it in prefillData from parent)
const encounter = prefillData?.identifier?.encounter;
const encounterId = prefillData?.identifier?.encounterId;
// State for new date/time
const [date, setDate] = useState<string>(
prefillData?.newDatetime?.date
? format(prefillData.newDatetime.date, 'yyyy-MM-dd')
: encounter ? format(new Date(encounter.start), 'yyyy-MM-dd') : format(new Date(), 'yyyy-MM-dd')
);
const [time, setTime] = useState<string>(
prefillData?.newDatetime?.time
? prefillData.newDatetime.time
: encounter ? format(new Date(encounter.start), 'HH:mm') : '09:00'
);
const [isSubmitting, setIsSubmitting] = useState(false);
const [isSuccess, setIsSuccess] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!encounterId) {
setError('Geen afspraak ID gevonden.');
return;
}
setIsSubmitting(true);
setError(null);
try {
const startDate = new Date(`${date}T${time}`);
// Keep same duration? For simplicty default to 1 hour or original duration if we knew it.
// API rescheduleEncounter takes start/end.
let endDate = addHours(startDate, 1);
if (encounter && encounter.end) {
const originalDuration = new Date(encounter.end).getTime() - new Date(encounter.start).getTime();
endDate = new Date(startDate.getTime() + originalDuration);
}
// Check if not in past
if (startDate < new Date()) {
setError('Kan niet verplaatsen naar een datum in het verleden.');
setIsSubmitting(false);
return;
}
const result = await rescheduleEncounter(
encounterId,
startDate.toISOString(),
endDate.toISOString()
);
if (result.success) {
setIsSuccess(true);
setTimeout(() => onClose?.(), 2000);
} else {
setError(result.error || 'Kon de afspraak niet verzetten.');
}
} catch (err) {
console.error('Reschedule error:', err);
setError('Er is een onverwachte fout opgetreden.');
} finally {
setIsSubmitting(false);
}
};
if (isSuccess) {
return (
<div className="flex flex-col items-center justify-center p-8 text-center h-full">
<div className="bg-green-50 p-3 rounded-full mb-4">
<CheckCircle2 className="h-8 w-8 text-green-600" />
</div>
<h3 className="text-lg font-semibold text-gray-900">Afspraak verzet</h3>
<p className="text-sm text-gray-500 mt-1 mb-6">
De afspraak is verplaatst naar {format(new Date(`${date}T${time}`), 'd MMMM HH:mm', { locale: nl })}.
</p>
<Button onClick={onClose} variant="outline" className="border-black/5 bg-white/50 hover:bg-white">Sluiten</Button>
</div>
);
}
if (!encounter && !encounterId) {
return (
<div className="p-4 text-center">
<p className="text-red-500">Geen afspraak gevonden om te verzetten.</p>
<Button onClick={onClose} variant="link">Sluiten</Button>
</div>
);
}
// Calculate current date/time for display
const currentStart = encounter ? new Date(encounter.start) : null;
const currentStr = currentStart ? format(currentStart, 'd MMMM yyyy HH:mm', { locale: nl }) : 'Onbekend';
return (
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.3 }}
className="flex flex-col h-full bg-transparent"
>
{/* Header */}
<div className="flex items-center justify-between p-5 border-b border-black/5">
<h3 className="font-semibold text-lg text-teal-700">Afspraak verzetten</h3>
<Button variant="ghost" size="icon" onClick={onClose} className="h-9 w-9 hover:bg-black/5 rounded-full">
<X className="h-5 w-5" />
</Button>
</div>
{/* Form */}
<form onSubmit={handleSubmit} className="flex-1 p-5 overflow-y-auto space-y-6">
{/* Info Card */}
<div className="bg-blue-50/70 border border-blue-100/50 rounded-xl p-5 shadow-sm">
{encounter && <h4 className="font-semibold text-blue-900 mb-3 text-lg">{encounter.title}</h4>}
<div className="flex items-center gap-3 text-sm text-blue-800/60 decoration-slate-400 mb-2">
<Calendar className="h-4 w-4" />
<span className="line-through decoration-blue-900/30">{currentStr}</span>
</div>
<div className="pl-0.5 my-2">
<div className="h-6 border-l-2 border-blue-200 ml-2 border-dashed"></div>
<ArrowRight className="h-5 w-5 text-blue-500 my-1" />
<div className="h-2 border-l-2 border-blue-200 ml-2 border-dashed"></div>
</div>
<div className="flex items-center gap-3 text-base font-bold text-blue-800 bg-blue-100/50 p-3 rounded-lg border border-blue-200/50">
<Calendar className="h-5 w-5" />
<span>
{date && time ? format(new Date(`${date}T${time}`), 'd MMMM yyyy HH:mm', { locale: nl }) : '...'}
</span>
</div>
</div>
{error && (
<div className="p-4 bg-red-50 border border-red-200 rounded-xl flex items-center gap-3 text-sm text-red-700">
<AlertCircle className="h-5 w-5 shrink-0" />
{error}
</div>
)}
<div className="space-y-5">
<div className="space-y-2">
<Label htmlFor="date" className="text-sm font-medium text-gray-700">Nieuwe datum</Label>
<div className="relative">
<div className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400">
<Calendar className="h-4 w-4" />
</div>
<Input
id="date"
type="date"
value={date}
onChange={(e) => setDate(e.target.value)}
className="pl-10 h-10 bg-white/50 backdrop-blur-sm border-black/10 focus:bg-white transition-colors"
required
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="time" className="text-sm font-medium text-gray-700">Nieuwe tijd</Label>
<div className="relative">
<div className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400">
<Clock className="h-4 w-4" />
</div>
<Input
id="time"
type="time"
value={time}
onChange={(e) => setTime(e.target.value)}
className="pl-10 h-10 bg-white/50 backdrop-blur-sm border-black/10 focus:bg-white transition-colors"
required
/>
</div>
</div>
</div>
</form>
{/* Footer */}
<div className="p-5 bg-gray-50/80 backdrop-blur-sm border-t border-black/5 flex justify-between gap-3">
<Button variant="outline" type="button" onClick={onClose} disabled={isSubmitting} className="flex-1 border-black/10 bg-white/50 hover:bg-white h-10 rounded-lg">
Annuleren
</Button>
<Button
type="button"
onClick={handleSubmit}
disabled={isSubmitting}
className="flex-1 bg-teal-600 hover:bg-teal-700 text-white shadow-md hover:shadow-lg h-10 rounded-lg"
>
{isSubmitting ? 'Verplaatsen...' : 'Bevestig wijziging'}
</Button>
</div>
</motion.div>
);
}