Files
cat-sitting-planner/app/[lang]/dashboard/[planId]/_components/plan-dashboard.tsx

350 lines
17 KiB
TypeScript

"use client"
import { useState, useEffect } from "react"
import { format, eachDayOfInterval, isSameDay } from "date-fns"
import { de, enUS } from "date-fns/locale"
import { CalendarIcon, User, Home, X, Info, Utensils, Trash2, Check } from "lucide-react"
import { toast } from "sonner"
import { Button } from "@/components/ui/button"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group"
import { createBooking, deleteBooking, completeBooking } from "@/app/actions/booking"
import { PlanSettings } from "@/components/plan-settings"
type Booking = {
id: number
date: Date
sitterName: string | null
type: string
completedAt?: Date | string | null
}
type Plan = {
id: string
startDate: Date
endDate: Date
instructions: string | null
webhookUrl: string | null
notifyAll: boolean
bookings: Booking[]
feedingPerDay: number
feedingInterval: number
litterInterval: number
}
interface PlanDashboardProps {
plan: Plan;
dict: any;
settingsDict: any;
lang: string;
}
export function PlanDashboard({ plan, dict, settingsDict, lang }: PlanDashboardProps) {
const [selectedDate, setSelectedDate] = useState<Date | null>(null)
const [sitterName, setSitterName] = useState("")
const [bookingType, setBookingType] = useState<"SITTER" | "OWNER_HOME">("SITTER")
const [isDialogOpen, setIsDialogOpen] = useState(false)
const [isCancelDialogOpen, setIsCancelDialogOpen] = useState(false)
const [bookingToCancel, setBookingToCancel] = useState<number | null>(null)
const [cancelReason, setCancelReason] = useState("")
const [isSubmitting, setIsSubmitting] = useState(false)
const handleComplete = async (bookingId: number) => {
try {
await completeBooking(bookingId, plan.id, lang)
toast.success(dict.bookedSuccess) // reuse for now or add new toast
} catch (error) {
toast.error(dict.bookError)
}
}
const dateLocale = lang === "de" ? de : enUS
// Load saved name from localStorage
useEffect(() => {
const savedName = localStorage.getItem("sitter_name")
if (savedName) setSitterName(savedName)
}, [])
// Generate all days
const days = eachDayOfInterval({
start: new Date(plan.startDate),
end: new Date(plan.endDate),
})
const handleBook = async () => {
if (!selectedDate) return
if (bookingType === "SITTER" && !sitterName.trim()) {
toast.error(dict.namePlaceholder) // Could use a more specific key if needed
return
}
setIsSubmitting(true)
try {
await createBooking(plan.id, selectedDate, bookingType === "SITTER" ? sitterName : "Owner", bookingType, lang)
// Save name to localStorage if it's a sitter booking
if (bookingType === "SITTER") {
localStorage.setItem("sitter_name", sitterName)
}
toast.success(dict.bookedSuccess)
setIsDialogOpen(false)
} catch (error) {
toast.error(dict.bookError)
} finally {
setIsSubmitting(false)
}
}
const handleCancelClick = (bookingId: number) => {
setBookingToCancel(bookingId)
setCancelReason("")
setIsCancelDialogOpen(true)
}
const handleConfirmCancel = async () => {
if (!bookingToCancel) return
setIsSubmitting(true)
try {
await deleteBooking(bookingToCancel, plan.id, lang, cancelReason)
toast.success(dict.cancelSuccess)
setIsCancelDialogOpen(false)
setBookingToCancel(null)
} catch {
toast.error(dict.cancelError)
} finally {
setIsSubmitting(false)
}
}
return (
<div className="space-y-4">
<div className="flex justify-between items-center bg-muted/50 p-4 rounded-lg">
<div className="flex items-center gap-2">
<h2 className="text-lg font-semibold">{dict.overview}</h2>
{plan.instructions && (
<Dialog>
<DialogTrigger asChild>
<Button variant="ghost" size="sm" className="gap-2">
<Info className="w-4 h-4" />
{dict.instructions}
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>{dict.instructionsTitle}</DialogTitle>
</DialogHeader>
<div className="whitespace-pre-wrap">{plan.instructions}</div>
</DialogContent>
</Dialog>
)}
</div>
<div className="flex gap-2">
<Button variant="outline" size="sm" asChild>
<a href={`/api/plan/${plan.id}/ics`} target="_blank" rel="noopener noreferrer">
<CalendarIcon className="w-4 h-4 mr-2" />
{dict.export}
</a>
</Button>
<PlanSettings
planId={plan.id}
initialWebhookUrl={plan.webhookUrl}
initialInstructions={plan.instructions}
initialNotifyAll={plan.notifyAll}
dict={settingsDict}
lang={lang}
/>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{days.map((day) => {
const booking = plan.bookings.find((b) => isSameDay(new Date(b.date), day))
const isOwnerHome = booking?.type === "OWNER_HOME"
return (
<div
key={day.toISOString()}
className={`p-4 border rounded-lg flex flex-col justify-between transition-colors ${booking
? isOwnerHome
? "bg-blue-50 dark:bg-blue-900/20 border-blue-200"
: "bg-green-50 dark:bg-green-900/20 border-green-200"
: "bg-card hover:bg-accent/50"
}`}
>
<div className="flex justify-between items-start mb-2">
<div className="font-semibold flex items-center gap-2">
<CalendarIcon className="w-4 h-4 opacity-70" />
{format(day, "PPPP", { locale: dateLocale })}
</div>
{booking && (
<Button
variant="ghost"
size="icon"
className="h-6 w-6 -mr-2 -mt-2 opacity-50 hover:opacity-100 text-destructive"
onClick={() => handleCancelClick(booking.id)}
>
<X className="w-4 h-4" />
<span className="sr-only">Remove</span>
</Button>
)}
</div>
{booking ? (
<div className="space-y-3">
<div className="flex items-center gap-2">
{isOwnerHome ? (
<>
<Home className="w-5 h-5 text-blue-500" />
<span className="font-medium text-blue-700 dark:text-blue-300">{dict.ownerHome}</span>
</>
) : (
<>
<User className="w-5 h-5 text-green-600" />
<span className="font-medium text-green-700 dark:text-green-300">{booking.sitterName}</span>
</>
)}
</div>
{booking.type === "SITTER" && (
<div className="pt-1">
{booking.completedAt ? (
<div className="flex items-center gap-2 text-green-600 font-bold bg-green-100/50 dark:bg-green-900/30 px-3 py-1.5 rounded-full border border-green-200 dark:border-green-800 w-fit text-sm">
<Check className="w-4 h-4 stroke-[3px]" />
<span>{dict.jobDone}</span>
</div>
) : (
<Button
variant="outline"
size="sm"
className="w-full flex gap-2 items-center border-green-200 hover:bg-green-100/50 text-green-700 dark:border-green-800 dark:hover:bg-green-900/40 font-semibold"
onClick={() => handleComplete(booking.id)}
>
<Check className="w-4 h-4" />
{dict.markDone}
</Button>
)}
</div>
)}
</div>
) : (
<Dialog open={isDialogOpen && isSameDay(selectedDate!, day)} onOpenChange={(open: boolean) => {
setIsDialogOpen(open)
if (open) setSelectedDate(day)
else setSelectedDate(null)
}}>
<DialogTrigger asChild>
<Button variant="outline" className="w-full dashed border-2">{dict.illDoIt}</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>{dict.bookTitle.replace("{date}", format(day, "PPP", { locale: dateLocale }))}</DialogTitle>
<DialogDescription>
{dict.bookDesc}
</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<RadioGroup value={bookingType} onValueChange={(v: any) => setBookingType(v)} className="flex gap-4">
<div className="flex items-center space-x-2">
<RadioGroupItem value="SITTER" id="r1" />
<Label htmlFor="r1">{dict.imSitting}</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="OWNER_HOME" id="r2" />
<Label htmlFor="r2">{dict.ownerIsHome}</Label>
</div>
</RadioGroup>
{bookingType === "SITTER" && (
<div className="grid gap-2">
<Label htmlFor="name">{dict.nameLabel}</Label>
<Input
id="name"
value={sitterName}
onChange={(e) => setSitterName(e.target.value)}
placeholder={dict.namePlaceholder}
autoFocus
/>
</div>
)}
</div>
<DialogFooter>
<Button onClick={handleBook} disabled={isSubmitting}>
{isSubmitting ? dict.saving : dict.confirmBooking}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)}
<div className="mt-3 flex flex-wrap gap-2 pt-2 border-t border-border/50">
{Math.floor((day.getTime() - new Date(plan.startDate).setHours(0, 0, 0, 0)) / (1000 * 60 * 60 * 24)) % plan.feedingInterval === 0 && (
<div className="flex gap-1 items-center" title={`${plan.feedingPerDay}x ${dict.feeding}`}>
{Array.from({ length: plan.feedingPerDay }).map((_, i) => (
<Utensils key={i} className="w-3.5 h-3.5 text-orange-500/70" />
))}
</div>
)}
{Math.floor((day.getTime() - new Date(plan.startDate).setHours(0, 0, 0, 0)) / (1000 * 60 * 60 * 24)) % plan.litterInterval === 0 && (
<div className="flex items-center gap-1 text-xs text-muted-foreground/70" title={dict.litter}>
<Trash2 className="w-3.5 h-3.5 text-blue-500/70" />
</div>
)}
</div>
</div>
)
})}
</div>
{/* Cancellation Dialog */}
<Dialog open={isCancelDialogOpen} onOpenChange={setIsCancelDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>{dict.cancelTitle}</DialogTitle>
<DialogDescription>
{dict.cancelConfirm}
</DialogDescription>
</DialogHeader>
{plan.webhookUrl && (
<div className="grid gap-2 py-4">
<Label htmlFor="reason">{dict.cancelMessageLabel}</Label>
<Input
id="reason"
value={cancelReason}
onChange={(e) => setCancelReason(e.target.value)}
placeholder={dict.cancelMessagePlaceholder}
autoFocus
/>
</div>
)}
<DialogFooter>
<Button variant="outline" onClick={() => setIsCancelDialogOpen(false)} disabled={isSubmitting}>
{dict.cancel}
</Button>
<Button variant="destructive" onClick={handleConfirmCancel} disabled={isSubmitting}>
{isSubmitting ? dict.saving : dict.cancelSubmit}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
)
}