Email for professionals and teams
"use client";
import { useEffect, useState } from "react";
import { CalendarDays, ChevronDown, Clock3, MapPin, MoreHorizontal, Plus, Trash2, UserRound } from "@/components/icons";
import clsx from "clsx";
import { useLanguage } from "@/components/language-provider";
import { folderColorKeys } from "@/lib/folders/color-keys";
import type { TranslationKey } from "@/lib/i18n/types";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { FOLDER_COLOR_OPTIONS } from "@/lib/folders/colors";
import { slugifyBookingName } from "@/lib/booking/utils";
import type { BookingEditorProps } from "./editor-types";
import type { BookingEditorSection } from "./types";
import { bookingFormWithName, durationLabel, formAvailabilityLabel, matchBookingHost, nextBookingTimeRange, WEEKDAYS } from "./utils";
import { BookingHostAvatar } from "./booking-host-avatar";
export function BookingEditor({ form, open, editingId, username, hosts, canManageHosts, currentUserId, saving, onChange, onClose, onSave, onDelete, onToggleEnabled, onClosed }: BookingEditorProps) {
const { t } = useLanguage();
const [activeSection, setActiveSection] = useState<BookingEditorSection>(null);
const [nameEditing, setNameEditing] = useState(false);
const [moreOpen, setMoreOpen] = useState(false);
const [hostQuery, setHostQuery] = useState("");
const [hostError, setHostError] = useState("");
useEffect(() => { if (open) { setActiveSection(null); setNameEditing(false); setMoreOpen(false); setHostQuery(""); setHostError(""); } }, [editingId, open]);
const sectionClass = "border-b border-neutral-200 px-5 py-5";
const headingClass = "flex w-full items-center justify-between gap-3 text-left text-base font-semibold text-neutral-900";
const fieldClass = "h-10 w-full rounded-xl border border-neutral-200 bg-white px-3 text-sm";
const toggle = (section: BookingEditorSection) => setActiveSection((current) => current === section ? null : section);
return <aside aria-label={t("booking.editor.details")} aria-hidden={!open} inert={!open} onTransitionEnd={(event) => { if (event.target === event.currentTarget && event.propertyName === "width" && !open) onClosed(); }} className={clsx("relative z-10 h-full shrink-0 overflow-hidden transition-[width] duration-300 ease-in-out motion-reduce:transition-none", open ? "w-full sm:w-[392px]" : "w-0")}>
<div className={clsx("flex h-full w-[min(392px,100vw)] flex-col overflow-hidden rounded-t-2xl bg-white shadow-2xl shadow-neutral-100 transition-transform duration-300 ease-in-out motion-reduce:transition-none", open ? "translate-x-0" : "translate-x-full")}>
<div className="min-h-0 flex-1 overflow-y-auto overscroll-contain scrollbar-gutter-stable">
<section className={sectionClass}>
<div className="flex items-center gap-3">
<button type="button" onClick={() => setActiveSection("event")} aria-label={t("booking.editor.editColor")} className="h-6 w-6 shrink-0 rounded-full" style={{ backgroundColor: form.color }} />
{nameEditing ? <Input autoFocus aria-label={t("booking.editor.meetingName")} value={form.name} onChange={(event) => onChange(bookingFormWithName(form, event.target.value))} onBlur={() => setNameEditing(false)} onKeyDown={(event) => { if (event.key === "Enter" || event.key === "Escape") setNameEditing(false); }} placeholder={t("booking.editor.newMeeting")} maxLength={120} className="min-w-0 flex-1 cursor-text bg-neutral-100 text-xl font-semibold" /> : <button type="button" onClick={() => { setActiveSection("event"); setNameEditing(true); }} className={clsx("min-w-0 flex-1 break-words text-left text-xl font-semibold text-neutral-900", activeSection === "event" ? "cursor-text rounded-lg bg-neutral-100 px-2 py-1" : "hover:text-blue-700")}>{form.name || t("booking.editor.newMeeting")}</button>}
<button type="button" onClick={() => toggle("event")} aria-label={t("booking.editor.toggleDetails")} aria-expanded={activeSection === "event"} className="rounded-full p-1 text-neutral-500 hover:bg-neutral-100"><ChevronDown className={clsx("h-5 w-5 transition-transform", activeSection === "event" && "rotate-180")} /></button>
</div>
{activeSection === "event" && <div className="mt-5 space-y-4"><label className="block text-sm font-medium text-neutral-700">{t("booking.editor.slug")}<Input value={form.slug} onChange={(event) => onChange({ ...form, slug: slugifyBookingName(event.target.value) })} placeholder={t("booking.editor.slugPlaceholder")} maxLength={80} className="mt-2" /><span className="mt-1 block break-all text-xs font-normal text-neutral-500">/c/{username || t("booking.editor.yourName")}/{form.slug || t("booking.editor.eventSlug")}</span></label><label className="block text-sm font-medium text-neutral-700">{t("calendar.description")}<Textarea value={form.description} onChange={(event) => onChange({ ...form, description: event.target.value })} placeholder={t("booking.editor.descriptionPlaceholder")} maxLength={2000} rows={4} className="mt-2 resize-y" /></label><fieldset><legend className="text-sm font-medium text-neutral-700">{t("booking.editor.color")}</legend><div className="mt-2 flex flex-wrap gap-2" role="radiogroup" aria-label={t("calendar.eventColor")}>{FOLDER_COLOR_OPTIONS.map((option) => <button key={option.value} type="button" role="radio" aria-label={t(folderColorKeys[option.value])} aria-checked={form.color === option.value} onClick={() => onChange({ ...form, color: option.value })} className={clsx("flex h-8 w-8 items-center justify-center rounded-full border-2 border-white ring-2", form.color === option.value ? "ring-neutral-800" : "ring-transparent hover:ring-neutral-300")} style={{ backgroundColor: option.value }}>{form.color === option.value && <span className="h-2 w-2 rounded-full bg-white" />}</button>)}</div></fieldset></div>}
</section>
<section className={sectionClass}><button type="button" onClick={() => toggle("duration")} aria-expanded={activeSection === "duration"} className={headingClass}><span>{t("booking.editor.duration")}</span><ChevronDown className={clsx("h-5 w-5 text-neutral-500 transition-transform", activeSection === "duration" && "rotate-180")} /></button>{activeSection === "duration" ? <div className="mt-4"><select aria-label={t("booking.editor.meetingLength")} value={[15, 30, 45, 60].includes(form.durationMinutes) ? form.durationMinutes : "custom"} onChange={(event) => onChange({ ...form, durationMinutes: event.target.value === "custom" ? 90 : Number(event.target.value) })} className={fieldClass}><option value={15}>{t("booking.editor.minutes15")}</option><option value={30}>{t("booking.editor.minutes30")}</option><option value={45}>{t("booking.editor.minutes45")}</option><option value={60}>{t("booking.editor.hour1")}</option><option value="custom">{t("booking.editor.custom")}</option></select>{![15, 30, 45, 60].includes(form.durationMinutes) && <Input aria-label={t("booking.editor.customMinutes")} type="number" min={5} max={480} step={5} value={form.durationMinutes} onChange={(event) => onChange({ ...form, durationMinutes: Number(event.target.value) })} className="mt-3" />}</div> : <button type="button" onClick={() => toggle("duration")} className="mt-2 flex w-full items-center gap-2 text-left text-sm text-neutral-500"><Clock3 className="h-4 w-4" />{durationLabel(form.durationMinutes, t)}</button>}</section>
<section className={sectionClass}><button type="button" onClick={() => toggle("location")} aria-expanded={activeSection === "location"} className={headingClass}><span>{t("booking.editor.location")}</span><ChevronDown className={clsx("h-5 w-5 text-neutral-500 transition-transform", activeSection === "location" && "rotate-180")} /></button>{activeSection === "location" ? <Input aria-label={t("booking.editor.location")} value={form.location} onChange={(event) => onChange({ ...form, location: event.target.value })} placeholder={t("booking.editor.locationPlaceholder")} maxLength={240} className="mt-4" /> : <button type="button" onClick={() => toggle("location")} className="mt-2 flex w-full items-center gap-2 text-left text-sm text-neutral-500"><MapPin className="h-4 w-4" />{form.location || t("booking.noLocation")}</button>}</section>
<section className={sectionClass}><button type="button" onClick={() => toggle("availability")} aria-expanded={activeSection === "availability"} className={headingClass}><span>{t("booking.editor.availability")}</span><ChevronDown className={clsx("h-5 w-5 text-neutral-500 transition-transform", activeSection === "availability" && "rotate-180")} /></button>{activeSection === "availability" ? <div className="mt-4 space-y-4"><fieldset aria-label={t("booking.editor.availableDays")}><div className="flex flex-wrap gap-1">{WEEKDAYS.map((day) => <button key={day} type="button" aria-label={t(`weekday.${day}` as TranslationKey)} aria-pressed={form.weekdays.includes(day)} onClick={() => onChange({ ...form, weekdays: form.weekdays.includes(day) ? form.weekdays.filter((value) => value !== day) : [...form.weekdays, day].sort() })} className={clsx("rounded-full px-3 py-1.5 text-xs font-medium", form.weekdays.includes(day) ? "bg-blue-600 text-white" : "bg-neutral-100 text-neutral-600 hover:bg-neutral-200")}>{t(`calendar.weekdayShort.${day}` as TranslationKey)}</button>)}</div></fieldset><div className="flex flex-row gap-8 mt-2"><p className="text-sm font-medium text-neutral-700 mt-3">{t("booking.editor.times")}</p>
<div className="space-y-2 flex flex-col items-start flex-1 min-w-0 w-fll">{form.timeRanges.map((range, index) => <div key={index} className="flex items-end gap-2 w-full"><label className="min-w-0 flex-1 text-xs text-neutral-500">{t("calendar.from")}<Input type="time" step={900} value={range.startTime} onChange={(event) => onChange({ ...form, timeRanges: form.timeRanges.map((item, itemIndex) => itemIndex === index ? { ...item, startTime: event.target.value } : item) })} className="mt-1 flex-1 min-w-0" /></label><label className="min-w-0 flex-1 text-xs text-neutral-500">{t("calendar.to")}<Input type="time" step={900} value={range.endTime} onChange={(event) => onChange({ ...form, timeRanges: form.timeRanges.map((item, itemIndex) => itemIndex === index ? { ...item, endTime: event.target.value } : item) })} className="mt-1 flex-1 min-w-0" /></label><button type="button" aria-label={t("booking.editor.removeTime", { n: index + 1 })} disabled={form.timeRanges.length === 1} onClick={() => onChange({ ...form, timeRanges: form.timeRanges.filter((_, itemIndex) => itemIndex !== index) })} className="mb-1 rounded-full p-2 text-neutral-500 hover:bg-neutral-100 disabled:opacity-30"><Trash2 className="h-4 w-4" /></button></div>)}
<button type="button" disabled={form.timeRanges.length >= 12} onClick={() => onChange({ ...form, timeRanges: [...form.timeRanges, nextBookingTimeRange(form.timeRanges, form.durationMinutes)] })} className="mt-3 inline-flex items-center gap-1 text-sm font-medium text-blue-700 hover:text-blue-600 disabled:opacity-50"><Plus className="h-4 w-4" />{t("booking.editor.addTime")}</button>
</div></div>
<p className="text-xs text-neutral-500">{t("booking.editor.timesUse", { zone: form.timeZone })}</p></div> : <button type="button" onClick={() => toggle("availability")} className="mt-2 flex w-full items-center gap-2 text-left text-sm text-neutral-500"><CalendarDays className="h-4 w-4 shrink-0" />{formAvailabilityLabel(form, t)}</button>}</section>
<section className={sectionClass}>
<button type="button" onClick={() => toggle("host")} aria-expanded={activeSection === "host"} className={headingClass}><span>{t("booking.editor.host")}</span><ChevronDown className={clsx("h-5 w-5 text-neutral-500 transition-transform", activeSection === "host" && "rotate-180")} /></button>
{activeSection === "host" ? <div className="mt-4 space-y-4">
<div className="space-y-2">{form.hostIds.map((id) => { const host = hosts.find((item) => item.id === id); const isCurrentUser = id === currentUserId; return <div key={id} className="flex items-center gap-3 rounded-xl bg-neutral-50 px-3 py-2">{host ? <BookingHostAvatar host={host} currentUserId={currentUserId} /> : <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-neutral-200 text-neutral-500"><UserRound className="h-4 w-4" /></span>}<span className="min-w-0 flex-1"><span className="block truncate text-sm font-medium text-neutral-900">{host?.name || t("booking.editor.unavailableUser")}{isCurrentUser ? t("booking.editor.you") : ""}</span><span className="block truncate text-xs text-neutral-500">{host?.email}</span></span>{!isCurrentUser && <button type="button" onClick={() => onChange({ ...form, hostIds: form.hostIds.filter((hostId) => hostId !== id) })} className="text-xs font-medium text-neutral-500 hover:text-red-600">{t("resend.remove")}</button>}</div>; })}</div>
{canManageHosts && <form onSubmit={(event) => { event.preventDefault(); const match = matchBookingHost(hosts, hostQuery, t); if (!match.host) { setHostError(match.error); return; } if (form.hostIds.includes(match.host.id)) { setHostError(t("booking.editor.alreadyHost")); return; } if (form.hostIds.length >= 20) { setHostError(t("booking.editor.maxHosts")); return; } onChange({ ...form, hostIds: [...form.hostIds, match.host.id] }); setHostQuery(""); setHostError(""); }}><label htmlFor="booking-host-input" className="block text-sm font-medium text-neutral-700">{t("booking.editor.addHost")}</label><div className="mt-2 flex gap-2"><Input id="booking-host-input" value={hostQuery} onChange={(event) => { setHostQuery(event.target.value); setHostError(""); }} placeholder={t("booking.editor.nameOrEmail")} autoComplete="off" aria-invalid={!!hostError} aria-describedby={hostError ? "booking-host-error" : undefined} className="min-w-0 flex-1" /><Button type="submit" variant="outline" className="shrink-0 rounded-full">{t("booking.editor.add")}</Button></div>{hostError && <p id="booking-host-error" role="alert" className="mt-2 text-xs text-red-600">{hostError}</p>}</form>}
</div> : <button type="button" onClick={() => toggle("host")} className="mt-2 flex w-full items-center gap-2 text-left text-sm text-neutral-500"><span className="flex shrink-0 -space-x-1">{form.hostIds.slice(0, 3).map((id) => { const host = hosts.find((item) => item.id === id); return host ? <BookingHostAvatar key={id} host={host} currentUserId={currentUserId} size="small" /> : <span key={id} className="flex h-5 w-5 items-center justify-center rounded-full bg-neutral-200"><UserRound className="h-3 w-3" /></span>; })}</span><span className="truncate">{form.hostIds.map((id) => hosts.find((host) => host.id === id)?.name ?? t("booking.editor.userFallback")).join(", ")}</span></button>}
</section>
</div>
<div className="relative flex shrink-0 items-center justify-end gap-2 bg-white px-4 py-3">{editingId && <div className="relative"><Button type="button" variant="outline" onClick={() => setMoreOpen((value) => !value)} className="h-9 rounded-full px-3"><MoreHorizontal className="h-4 w-4" />{t("booking.editor.more")}</Button>{moreOpen && <div className="absolute bottom-full right-0 z-20 mb-2 w-40 rounded-xl border border-neutral-200 bg-white p-1 shadow-lg"><button type="button" onClick={() => { setMoreOpen(false); onToggleEnabled(); }} className="block w-full rounded-lg px-3 py-2 text-left text-sm hover:bg-neutral-100">{form.enabled ? t("booking.turnOff") : t("booking.turnOn")}</button><button type="button" onClick={() => { setMoreOpen(false); onDelete(); }} className="block w-full rounded-lg px-3 py-2 text-left text-sm text-red-600 hover:bg-red-50">{t("common.delete")}</button></div>}</div>}<Button type="button" variant="ghost" disabled={saving} onClick={onClose} className="h-9 rounded-full px-4">{t("common.cancel")}</Button><Button type="button" disabled={saving} onClick={onSave} className="h-9 rounded-full px-4">{saving ? t("common.saving") : editingId ? t("settings.mailbox.saveChanges") : t("booking.editor.create")}</Button></div>
</div>
</aside>;
}