Files
hats-app/app/(dashboard)/task/client-detail/[client_id]/project-assignments/ProjectAssignmentForm.tsx
T
Ichsan Kurniawan ffcf3c6e58 Refactor task views with layout toggles
This commit reorganizes client and project-assignment screens into dedicated grid/list components, adds a shared layout toggle via the URL query string, and updates task pages to render the selected view consistently. It also moves shared client form logic into a client folder, improves status badge formatting, extends LazyImage with custom image classes, and updates the illustration assets and Lucide dependency used in the task UI.
2026-10-01 18:32:56 +07:00

765 lines
55 KiB
TypeScript

"use client"
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import { motion, AnimatePresence } from 'motion/react';
import { ArrowLeft, ArrowRight, Save, Briefcase, Clock, Search, Check, CheckCircle, Plus, Building2, CheckCircle2 } from 'lucide-react';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardContent, CardHeader, CardTitle, CardDescription, Card900 } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import {
Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList,
} from '@/components/ui/command';
import {
Popover, PopoverContent, PopoverTrigger,
} from '@/components/ui/popover';
import { DatePicker } from '@/components/ui/datepicker';
import { toast } from 'sonner';
import { cn } from '@/lib/utils';
import { Label } from '@/components/ui/label';
import * as yup from 'yup';
import { IClient, IEndUser } from '../../../types';
import { serverApiCall } from '@/lib/server-api';
import dayjs from 'dayjs';
import PageLoading from '@/components/loader/PageLoading';
import { IProjectAssignment } from '../../../type.assignment';
import { useFetchWithAxios } from '@/lib/axios/useFetch';
import { ComboboxCustomUI } from '@/components/ui/combobox-custom-ui';
import { LazyImage } from '@/components/ui/lazy-image';
import FormEndUser from '../../../component/FormEndUser';
import { IProject } from '../../../type.project';
import FormClient from '../../../component/client/FormClient';
type IStep = 'type' | 'clients' | 'details' | 'work-orders' | 'review';
export const assignmentSchema = yup.object({
type: yup.string().oneOf(['Project', 'IM']).required('Project type is required'),
// Details Step
client_id: yup.number().required('Client is required'),
end_user_id: yup.number().required('End user is required'),
name: yup.string().required('Assignment name is required'),
code: yup.string().required('Project code is required'),
year: yup.string().required('Year is required'),
startDate: yup.date().required('Start date is required'),
endDate: yup.date().nullable().min(yup.ref('startDate'), 'End date cannot be before start date').default(null),
description: yup.string().optional().nullable().default(''),
// Work Orders Step (Conditional based on 'type')
workOrder: yup.object().when('type', {
is: 'Project',
then: (schema) => schema.shape({
name: yup.string().required('Work order name is required'),
code: yup.string().required('Work order code is required'),
startDate: yup.date().required('Start date is required'),
endDate: yup.date().nullable().default(null),
description: yup.string().optional().nullable().default(''),
}),
otherwise: (schema) => schema.nullable().notRequired()
})
});
// Infer the TypeScript type from the Yup schema
export type AssignmentFormValues = yup.InferType<typeof assignmentSchema>;
export default function ProjectAssignmentForm({ client, clientId, isEdit, assignmentId }: { client?: IClient, clientId?: string, isEdit?: boolean, assignmentId?: string }) {
const [existAssignment, setIsExistAssignment] = useState<IProjectAssignment | null>(null)
const [step, setStep] = useState<IStep>('type');
const [loading, setIsLoading] = useState(false);
const [isFullLoading, setIsFullLoading] = useState(false)
const [isExistProject, setIsExistProject] = useState(false)
const [openProjectSearch, setOpenProjectSearch] = useState(false);
const [showEndUserForm, setShowEndUserForm] = useState(false)
const [showClientForm, setShowClientForm] = useState(false)
const [selectedClient, setSelectedClient] = useState<IClient | null>(client || null)
const [selectedEndUser, setSelectedEndUser] = useState<IEndUser | null>(null)
const router = useRouter();
const form = useForm<AssignmentFormValues>({
resolver: yupResolver(assignmentSchema),
defaultValues: {
client_id: clientId ? Number(clientId) : undefined,
type: 'Project',
name: '',
code: '',
year: new Date().getFullYear().toString(),
description: '',
workOrder: {
name: '',
code: '',
description: '',
}
},
mode: "onChange"
});
const assignmentType = form.watch('type');
const formValues = form.watch();
const { data: clientList, mutate: mutateClientList } = useFetchWithAxios('/client')
const { data: endUserList, mutate: mutateEndUserList } = useFetchWithAxios('/end-user')
const { data: projectList, mutate: mutateProjectList } = useFetchWithAxios(`/client/project/${formValues.client_id}`)
// 3. Navigation & Validation Logic
const steps: { id: IStep; label: string }[] = [
{ id: 'type', label: 'Type' },
{ id: 'clients', label: 'Clients' },
{ id: 'details', label: 'Details' },
...(assignmentType === 'Project' ? [{ id: 'work-orders' as IStep, label: 'Work Orders' }] : []),
{ id: 'review', label: 'Review' },
];
const currentStepIndex = steps.findIndex(s => s.id === step);
useEffect(() => {
if (!isEdit) return
async function getAssignmentDetail() {
setIsFullLoading(true)
const res: any = await serverApiCall('GET', `/project-assignment/${assignmentId}`)
if (res.success) {
const data: IProjectAssignment = res.data.data
form.setValue('type', data.project?.code ? 'Project' : 'IM')
form.setValue('client_id', data.client.id)
form.setValue('end_user_id', data.end_user.id)
form.setValue('name', data.project?.name || data.im_name)
form.setValue('code', data.project?.code || data.im_code)
form.setValue('year', data.project?.year || data.im_year)
form.setValue('startDate', data.project?.start_date || data.im_start_date)
form.setValue('endDate', data.project?.end_date || data.im_end_date)
form.setValue('description', data.project?.description || data.im_description)
form.setValue('workOrder.name' as any, data.wo_name)
form.setValue('workOrder.code' as any, data.wo_code)
form.setValue('workOrder.startDate' as any, data.wo_start_date)
form.setValue('workOrder.endDate' as any, data.wo_end_date)
form.setValue('workOrder.description' as any, data.wo_description)
setStep('clients')
setIsExistAssignment(res.data.data)
} else {
toast.error('Fail to get detail assignment', {
description: `(${res.code || '-'}) ${res.message}`
})
}
setIsFullLoading(false)
}
getAssignmentDetail()
}, [isEdit, assignmentId])
const handleNext = async () => {
let isStepValid = false;
if (step === 'type') {
isStepValid = await form.trigger(['type']);
if (isStepValid) setStep('clients');
}
else if (step === 'clients') {
isStepValid = await form.trigger(['client_id', 'end_user_id']);
if (isStepValid) setStep('details');
}
else if (step === 'details') {
isStepValid = await form.trigger(['name', 'code', 'year', 'startDate', 'endDate', 'description']);
if (isStepValid) setStep(assignmentType === 'Project' ? 'work-orders' : 'review');
}
else if (step === 'work-orders') {
// Trigger the parent key to validate all nested workOrder fields
isStepValid = await form.trigger('workOrder');
if (isStepValid) setStep('review');
}
};
const handleBack = () => {
if (step === 'clients') setStep('type');
if (step === 'details') setStep('clients');
else if (step === 'work-orders') setStep('details');
else if (step === 'review') setStep(assignmentType === 'Project' ? 'work-orders' : 'details');
};
const onSubmit = async (payload: AssignmentFormValues) => {
setIsLoading(true);
const newPayload = {
"client_id": Number(payload.end_user_id),
"end_user_id": payload.end_user_id ? Number(payload.end_user_id) : null,
"im_code": assignmentType === 'IM' ? payload.code : isEdit ? existAssignment?.im_code : "",
"im_name": assignmentType === 'IM' ? payload.name : isEdit ? existAssignment?.im_name : "",
"im_year": assignmentType === 'IM' ? Number(payload.year) : isEdit ? existAssignment?.im_year : 2026,
"im_start_date": assignmentType === 'IM' ? dayjs(payload.startDate).format('YYYY-MM-DD') : isEdit ? existAssignment?.im_start_date : "",
"im_end_date": assignmentType === 'IM' ? payload.endDate ? dayjs(payload.endDate).format('YYYY-MM-DD') : "" : isEdit ? existAssignment?.im_end_date : "",
"im_description": assignmentType === 'IM' ? payload.description : isEdit ? existAssignment?.im_description : "",
"project_code": assignmentType === 'Project' ? payload.code : '',
"project_name": assignmentType === 'Project' ? payload.name : '',
"project_year": assignmentType === 'Project' ? Number(payload.year) : 2026,
"project_start_date": assignmentType === 'Project' ? dayjs(payload.startDate).format('YYYY-MM-DD') : '',
"project_end_date": assignmentType === 'Project' ? payload.endDate ? dayjs(payload.endDate).format('YYYY-MM-DD') : '' : '',
"project_description": assignmentType === 'Project' ? payload.description : '',
"wo_code": (payload.workOrder as any).code,
"wo_name": (payload.workOrder as any).name,
"wo_start_date": (payload.workOrder as any).startDate ? dayjs((payload.workOrder as any).startDate).format('YYYY-MM-DD') : '',
"wo_end_date": (payload.workOrder as any).endDate ? dayjs((payload.workOrder as any).endDate).format('YYYY-MM-DD') : '',
"wo_description": (payload.workOrder as any).description,
"wo_warranty": isEdit ? existAssignment?.wo_warranty : '',
"project_assignment_status_id": isEdit ? existAssignment?.project_assignment_status?.id : 1,
"note": isEdit ? existAssignment?.note : "",
}
let res: any
if (isEdit) {
res = await serverApiCall('PUT', `/project-assignment/${assignmentId}`, newPayload)
} else {
res = await serverApiCall('POST', '/project-assignment', newPayload)
}
setIsLoading(false)
if (res.success) {
toast.success(`${payload.type} saved successfully`);
if (clientId) {
router.replace(`/task/client-detail/${clientId}`);
} else {
router.replace(`/task?tab=assignments`);
}
} else {
toast.error(`Fail to save assignment`, { description: `(${res.code || '-'}) ${res.message}` })
}
};
return (
<>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
{/* --- HEADER --- */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-4">
<Button type="button" variant="ghost" size="icon" onClick={() => router.back()}>
<ArrowLeft className="w-5 h-5" />
</Button>
<div>
<h1 className="text-3xl font-bold">{isEdit ? 'Update' : 'Create Project'} Assignment</h1>
<p className="text-muted-foreground">{clientId ? `For ${client?.name}` : 'Manage the creation and modification of assignment information'}</p>
</div>
</div>
</div>
{/* --- STEPPER --- */}
<div className="flex items-center justify-between px-2">
{steps.map((s, i) => (
<div key={s.id} className="flex items-center flex-1 last:flex-none">
<div className="flex flex-col items-center gap-2">
<div className={cn(
"w-10 h-10 rounded-full flex items-center justify-center border-2 transition-all duration-300",
i <= currentStepIndex ? "bg-zinc-900 dark:bg-zinc-100 border-primary text-secondary" : "border-border text-muted-foreground"
)}>
{i < currentStepIndex ? <Check className="w-5 h-5" /> : <span>{i + 1}</span>}
</div>
<span className={cn(
"text-xs font-medium hidden md:block",
i <= currentStepIndex ? "text-primary" : "text-muted-foreground"
)}>{s.label}</span>
</div>
{i < steps.length - 1 && (
<div className={cn(
"h-0.5 flex-1 mx-4 transition-all duration-500",
i < currentStepIndex ? "bg-primary" : "bg-border"
)} />
)}
</div>
))}
</div>
{/* --- FORM CONTENT --- */}
<AnimatePresence mode="wait">
<motion.div
key={step}
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -20 }}
transition={{ duration: 0.3 }}
>
{/* STEP 1: TYPE */}
{step === 'type' && (
<FormField control={form.control} name="type" render={({ field }) => (
<FormItem>
<div className="grid md:grid-cols-2 gap-6">
<Card onClick={() => field.onChange('Project')}
className={cn("cursor-pointer transition-all hover:border-his dark:hover:border-his duration-400", field.value === 'Project' && "ring-2 ring-his/10 border-his dark:ring-his/10 dark:border-his")}
>
<CardContent className="p-8 flex flex-col items-center text-center space-y-4">
<div className="w-16 h-16 rounded-2xl bg-orange-500/10 text-orange-500 flex items-center justify-center">
<Briefcase className="w-8 h-8" />
</div>
<div>
<h3 className="text-xl font-bold">Project</h3>
<p className="text-muted-foreground text-sm mt-2">
Standard project assignment. Requires Work Orders and detailed planning.
</p>
</div>
</CardContent>
</Card>
<Card onClick={() => field.onChange('IM')}
className={cn("cursor-pointer transition-all hover:border-his dark:hover:border-his duration-400", field.value === 'IM' && "ring-2 ring-his/10 border-his dark:ring-his/10 dark:border-his")}
>
<CardContent className="p-8 flex flex-col items-center text-center space-y-4">
<div className="w-16 h-16 rounded-2xl bg-purple-500/10 text-purple-500 flex items-center justify-center">
<Clock className="w-8 h-8" />
</div>
<div>
<h3 className="text-xl font-bold">Internal Memo (IM)</h3>
<p className="text-muted-foreground text-sm mt-2">
Used for Proof of Concept (PoC) stages. Can be converted to a Project later.
</p>
</div>
</CardContent>
</Card>
</div>
<FormMessage />
</FormItem>
)}
/>
)}
{/* STEP 2: CLIENTS */}
{step === 'clients' && (
<Card900>
<CardHeader>
<CardTitle>Client Details</CardTitle>
<CardDescription>Select the client and end user information for this assignment.</CardDescription>
</CardHeader>
<CardContent className="space-y-6 mb-8">
<FormField control={form.control} name='client_id'
render={({ field }) => (
<FormItem>
<FormLabel>Client</FormLabel>
<FormControl>
<div className="flex gap-4">
<ComboboxCustomUI options={clientList && clientList.length > 0 ? clientList.map((item: IClient) => ({ label: item.name, value: item.id, originalData: item })) : []}
value={field.value} onChange={field.onChange} onSelect={(option) => setSelectedClient(option.originalData as any)} placeholder='Select client' className='shrink' disabled={clientId ? true : false}
// --- CUSTOM DROPDOWN OPTIONS ---
renderOption={(option, isSelected) => {
const item = option.originalData as IClient;
return (
<div className={`flex items-center justify-between w-full py-1 rounded-sm ${isSelected ? 'bg-zinc-800' : ''}`}>
<div className="flex items-center gap-3">
<LazyImage className='w-10 h-10 rounded-md border border-border' alt={item.name} src={item.photo ? item.photo : '/assets/ilustration.png'} />
<div className="flex flex-col">
<span className={`text-sm ${isSelected ? 'font-bold text-primary' : ''}`}>
{item.name}
</span>
<span className="text-xs text-muted-foreground truncate">
{item.description}
</span>
</div>
</div>
{isSelected && <CheckCircle className="h-5 w-5 -translate-x-2" />}
</div>
);
}}
/>
{clientId ? null :
<Button type="button" variant="outline" size="icon" onClick={() => setShowClientForm(true)}>
<Plus className="w-4 h-4" />
</Button>
}
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField control={form.control} name='end_user_id'
render={({ field }) => (
<FormItem>
<FormLabel>End User</FormLabel>
<FormControl>
<div className="flex gap-4">
<ComboboxCustomUI options={endUserList && endUserList.length > 0 ? endUserList.map((item: IEndUser) => ({ label: item.name, value: item.id, originalData: item })) : []}
value={field.value} onChange={field.onChange} onSelect={(option) => setSelectedEndUser(option.originalData as any)} placeholder='Select end user' className='shrink'
// --- CUSTOM DROPDOWN OPTIONS ---
renderOption={(option, isSelected) => {
const user = option.originalData as IEndUser;
return (
<div className={`flex items-center justify-between w-full py-1 rounded-sm ${isSelected ? 'bg-zinc-800' : ''}`}>
<div className="flex items-center gap-3">
<LazyImage className='w-10 h-10 rounded-md border border-border' alt={user.name} src={user.photo ? user.photo : '/assets/ilustration.png'} />
<div className="flex flex-col">
<span className={`text-sm ${isSelected ? 'font-bold text-primary' : ''}`}>
{user.name}
</span>
<span className="text-xs text-muted-foreground truncate">
{user.description}
</span>
</div>
</div>
{isSelected && <CheckCircle className="h-5 w-5 -translate-x-2" />}
</div>
);
}}
/>
<Button type="button" variant="outline" size="icon" onClick={() => setShowEndUserForm(true)}>
<Plus className="w-4 h-4" />
</Button>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</CardContent>
</Card900>
)}
{/* STEP 3: DETAILS */}
{step === 'details' && (
<Card900>
<CardHeader>
<CardTitle>{assignmentType === 'IM' ? 'Internal Memo' : 'Project'} Details</CardTitle>
<CardDescription>Provide the basic information for this assignment.</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>{assignmentType === 'Project' ? "Project" : "Internal Memo"} Name</FormLabel>
<div className="flex gap-2">
<div className="flex-1 relative">
<FormControl>
<Input placeholder="e.g Software Development Sem 1 PO 4200049718..." {...field} disabled={isExistProject} />
</FormControl>
{assignmentType === 'Project' && (
<div className="absolute right-2 top-1/2 -translate-y-1/2">
<Popover open={openProjectSearch} onOpenChange={setOpenProjectSearch}>
<PopoverTrigger asChild>
<Button variant="ghost" size="sm" className="h-7 px-2 text-xs">
<Search className="w-3 h-3 mr-1" /> Existing
</Button>
</PopoverTrigger>
<PopoverContent className="p-0 w-75" align="end">
<Command>
<CommandInput placeholder="Search existing projects..." />
<CommandList>
<CommandEmpty>No projects found.</CommandEmpty>
<CommandGroup heading="Recent Projects">
{projectList.map((p: IProject) => (
<CommandItem
key={p.id}
onSelect={() => {
form.setValue('name', p.name!, { shouldValidate: true });
form.setValue('code', p.code!, { shouldValidate: true });
form.setValue('year', String(p.year), { shouldValidate: true });
form.setValue('startDate', new Date(p.start_date!), { shouldValidate: true });
form.setValue('endDate', new Date(p.end_date!), { shouldValidate: true });
form.setValue('description', p.description!, { shouldValidate: true });
setOpenProjectSearch(false);
setIsExistProject(true)
toast.info(`Autofilled details from ${p.name}`);
}}
>
<Check className={cn("mr-2 h-4 w-4", field.value === p.name ? "opacity-100" : "opacity-0")} />
{p?.name!}
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</div>
)}
</div>
</div>
<FormMessage />
</FormItem>
)}
/>
<div className="grid md:grid-cols-2 gap-4">
<FormField control={form.control} name="code" disabled={isExistProject} render={({ field }) => (
<FormItem>
<FormLabel>{assignmentType} Code</FormLabel>
<FormControl><Input placeholder="e.g. 24016" {...field} /></FormControl>
<FormMessage />
</FormItem>
)} />
<FormField control={form.control} name="year" disabled={isExistProject} render={({ field }) => (
<FormItem>
<FormLabel>{assignmentType} Year</FormLabel>
<FormControl><Input placeholder="e.g. 2024" {...field} /></FormControl>
<FormMessage />
</FormItem>
)} />
</div>
<div className="grid md:grid-cols-2 gap-4">
<FormField control={form.control} name="startDate" disabled={isExistProject} render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>Start Date</FormLabel>
<DatePicker date={field.value} setDate={field.onChange} disabled={isExistProject} />
<FormMessage />
</FormItem>
)} />
<FormField control={form.control} name="endDate" disabled={isExistProject} render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>End Date</FormLabel>
<DatePicker date={field.value as Date | undefined} setDate={field.onChange} disabled={isExistProject} />
<FormMessage />
</FormItem>
)} />
</div>
<FormField control={form.control} name="description" disabled={isExistProject} render={({ field }) => (
<FormItem>
<FormLabel>Description</FormLabel>
<FormControl>
<Textarea placeholder="Describe the scope..." className="min-h-30" {...field} value={field.value || ''} />
</FormControl>
<FormMessage />
</FormItem>
)} />
</CardContent>
</Card900>
)}
{/* STEP 4: WORK ORDERS */}
{step === 'work-orders' && (
<div className="space-y-6">
<div>
<h2 className="text-2xl font-bold">Work Order</h2>
<p className="text-muted-foreground">Define the initial task for this project.</p>
</div>
<Card900>
<CardContent className="p-6 space-y-4">
<div className="grid gap-4 md:grid-cols-2">
<FormField control={form.control} name={"workOrder.name" as any} render={({ field }) => (
<FormItem>
<FormLabel>WO Name</FormLabel>
<FormControl><Input placeholder="e.g. Initial Site Survey" {...field} value={field.value || ''} /></FormControl>
<FormMessage />
</FormItem>
)} />
<FormField control={form.control} name={"workOrder.code" as any} render={({ field }) => (
<FormItem>
<FormLabel>WO Code</FormLabel>
<FormControl><Input placeholder="e.g. WO-24016" {...field} value={field.value || ''} /></FormControl>
<FormMessage />
</FormItem>
)} />
</div>
<div className="grid gap-4 md:grid-cols-2">
<FormField control={form.control} name={"workOrder.startDate" as any} render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>WO Start Date</FormLabel>
<DatePicker date={field.value as Date | undefined} setDate={field.onChange} />
<FormMessage />
</FormItem>
)} />
<FormField control={form.control} name={"workOrder.endDate" as any} render={({ field }) => (
<FormItem className="flex flex-col">
<FormLabel>WO End Date</FormLabel>
<DatePicker date={field.value as Date | undefined} setDate={field.onChange} />
<FormMessage />
</FormItem>
)} />
</div>
<FormField control={form.control} name={"workOrder.description" as any} render={({ field }) => (
<FormItem>
<FormLabel>WO Description</FormLabel>
<FormControl><Textarea placeholder="Briefly describe the task.." className="min-h-30" {...field} value={field.value || ''} /></FormControl>
<FormMessage />
</FormItem>
)} />
</CardContent>
</Card900>
</div>
)}
{/* STEP 5: REVIEW */}
{step === 'review' && (
<div className="space-y-6">
<div className="flex flex-col gap-2">
<h2 className="text-2xl font-bold">Review Assignment</h2>
<p className="text-muted-foreground">Double check everything before saving.</p>
</div>
<div className="grid gap-6">
<Card className="overflow-hidden">
<div className="bg-primary/5 px-6 py-4 border-b flex justify-between items-center">
<CardTitle className="text-lg">Project Assignment Overview</CardTitle>
<Badge variant={formValues.type === 'IM' ? 'info' : 'default'} className="px-3">{formValues.type}</Badge>
</div>
<CardContent className="p-6 space-y-8">
{/* Business Relationship Section */}
<div className="grid md:grid-cols-2 gap-8">
<div className="space-y-3">
<Label className="text-[10px] text-muted-foreground uppercase tracking-widest font-bold">Client Information</Label>
<div className="flex items-center gap-4 p-4 rounded-xl border bg-card/50">
<div className="w-12 h-12 rounded-lg bg-white border flex items-center justify-center overflow-hidden shrink-0">
{selectedClient?.photo ?
<LazyImage src={selectedClient.photo} alt={selectedClient.name} className="w-11 h-11 object-contain rounded" />
:
<Briefcase className="w-6 h-6 text-muted-foreground" />
}
</div>
<div className="min-w-0">
<p className="font-bold text-lg truncate">{selectedClient?.name}</p>
<p className="text-xs text-muted-foreground truncate">{selectedClient?.description}</p>
</div>
</div>
</div>
<div className="space-y-3">
<Label className="text-[10px] text-muted-foreground uppercase tracking-widest font-bold">End User Information</Label>
<div className="flex items-center gap-4 p-4 rounded-xl border bg-card/50">
<div className="w-12 h-12 rounded-lg bg-white border flex items-center justify-center overflow-hidden shrink-0">
{selectedEndUser?.photo ?
<LazyImage src={selectedEndUser.photo} alt={selectedEndUser.name} className="w-11 h-11 object-contain rounded" />
:
<Building2 className="w-6 h-6 text-muted-foreground" />
}
</div>
<div className="min-w-0">
<p className="font-bold text-lg truncate">{selectedEndUser?.name}</p>
<p className="text-xs text-muted-foreground truncate">{selectedEndUser?.description}</p>
</div>
</div>
</div>
</div>
<Separator />
{/* Assignment Details */}
<div className="grid md:grid-cols-3 gap-6">
<div className="md:col-span-2 space-y-4">
<div className="space-y-1">
<Label className="text-[10px] text-muted-foreground uppercase tracking-wider font-semibold">{formValues.type === 'IM' ? 'Internal Memo' : 'Project'} Name</Label>
<p className="text-xl font-bold">{formValues.name}</p>
</div>
<div className="space-y-1">
<Label className="text-[10px] text-muted-foreground uppercase tracking-wider font-semibold">Description</Label>
<p className="text-sm text-muted-foreground leading-relaxed">
{formValues.description || 'No description provided.'}
</p>
</div>
</div>
<div className="space-y-4 bg-muted/30 p-4 rounded-lg self-start">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-1">
<Label className="text-[10px] text-muted-foreground uppercase tracking-wider">{formValues.type === 'IM' ? 'IM' : 'Project'} Year</Label>
<p className="font-mono text-sm">{formValues.year || '-'}</p>
</div>
<div className="space-y-1">
<Label className="text-[10px] text-muted-foreground uppercase tracking-wider">{formValues.type === 'IM' ? 'IM' : 'Project'} Code</Label>
<p className="font-mono text-sm">{formValues.code || '-'}</p>
</div>
<div className="space-y-1">
<Label className="text-[10px] text-muted-foreground uppercase tracking-wider">Start Date</Label>
<p className="text-sm font-medium">{formValues.startDate ? new Date(formValues.startDate).toLocaleDateString() : 'N/A'}</p>
</div>
<div className="space-y-1">
<Label className="text-[10px] text-muted-foreground uppercase tracking-wider">End Date</Label>
<p className="text-sm font-medium">{formValues.endDate ? new Date(formValues.endDate).toLocaleDateString() : 'N/A'}</p>
</div>
</div>
</div>
</div>
{(formValues.workOrder as any)?.name && (
<div className="space-y-4">
<div className="flex items-center gap-2">
<Separator className="flex-1" />
<Label className="text-[10px] text-muted-foreground uppercase tracking-widest font-bold px-2">Work Order Detail</Label>
<Separator className="flex-1" />
</div>
<div className="bg-primary/5 rounded-xl border border-primary/10 overflow-hidden">
<div className="p-4 flex flex-col md:flex-row md:items-center justify-between gap-4">
<div className="flex items-start gap-3">
<div className="w-8 h-8 rounded-full bg-primary/20 text-primary flex items-center justify-center shrink-0 mt-1">
<Building2 className="w-4 h-4" />
</div>
<div className="space-y-1">
<p className="font-bold text-primary">{(formValues.workOrder as any).name}</p>
<p className="text-xs text-muted-foreground line-clamp-2">{(formValues.workOrder as any).description}</p>
</div>
</div>
<div className="flex gap-4 text-right">
<div className="space-y-1">
<Label className="text-[9px] text-muted-foreground uppercase tracking-wider">WO Code</Label>
<p className="text-xs font-mono">{(formValues.workOrder as any).code || '-'}</p>
</div>
<div className="space-y-1">
<Label className="text-[9px] text-muted-foreground uppercase tracking-wider">Schedule</Label>
<p className="text-[10px] font-medium leading-none">
{(formValues.workOrder as any).startDate ? new Date((formValues.workOrder as any).startDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : '-'} — {(formValues.workOrder as any).endDate ? new Date((formValues.workOrder as any).endDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : '-'}
</p>
</div>
</div>
</div>
</div>
</div>
)}
</CardContent>
</Card>
</div>
<div className="flex items-center justify-center gap-2 text-sm text-muted-foreground">
<CheckCircle2 className="w-4 h-4 text-green-500" />
<span className="italic">Employees can be assigned after the assignment is created.</span>
</div>
</div>
)}
</motion.div>
</AnimatePresence>
{/* --- FOOTER NAVIGATION --- */}
<div className="fixed bottom-0 left-0 right-0 p-6 bg-background/80 backdrop-blur-md border-t flex justify-between z-50">
<Button type="button" variant="ghost" onClick={handleBack} disabled={step === 'type'}>
Back
</Button>
<div className="flex gap-4">
{step !== 'review' ?
<Button key="next-btn" type="button" className="gap-2" onClick={handleNext}>
Next Step <ArrowRight className="w-4 h-4" />
</Button>
:
<Button key="submit-btn" type="submit" className="gap-2" disabled={loading}>
{loading ? 'Saving...' : <><Save className="w-4 h-4" /> Save Assignment</>}
</Button>
}
</div>
</div>
</form>
</Form>
{showEndUserForm ? <FormEndUser onCancel={() => setShowEndUserForm(false)} onSuccess={() => { mutateEndUserList(); setShowEndUserForm(false) }} /> : null}
{showClientForm ? <FormClient onCancel={() => setShowClientForm(false)} onSuccess={() => { mutateClientList(); setShowClientForm(false) }} /> : null}
{isFullLoading ? <PageLoading /> : null}
</>
);
}