'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useState } from 'react';
import { Calendar, Clock, Loader2, X } from 'lucide-react';
import { toast } from 'sonner';
import { cmsApi } from '../lib/api.js';
/**
 * Convert a Date or ISO string to the `YYYY-MM-DDTHH:mm` shape that the
 * `<input type="datetime-local">` element expects, in the user's local
 * timezone (the input is timezone-naive but we present + parse it as local).
 */
function toLocalDateTimeInput(value) {
    if (!value)
        return '';
    const d = typeof value === 'string' ? new Date(value) : value;
    if (Number.isNaN(d.getTime()))
        return '';
    const pad = (n) => String(n).padStart(2, '0');
    return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
/** Round "now + 1 hour" to the next quarter-hour for a friendly default. */
function defaultScheduleTime() {
    const d = new Date(Date.now() + 60 * 60 * 1000);
    d.setMinutes(Math.ceil(d.getMinutes() / 15) * 15, 0, 0);
    return toLocalDateTimeInput(d);
}
export function SchedulePublishDialog({ collectionSlug, documentId, scheduledAt, scheduledUnpublishAt, open, onClose, onScheduled, }) {
    const [publishAt, setPublishAt] = useState('');
    const [unpublishAt, setUnpublishAt] = useState('');
    const [includeUnpublish, setIncludeUnpublish] = useState(false);
    const [saving, setSaving] = useState(false);
    const [cancelling, setCancelling] = useState(false);
    const hasExistingSchedule = Boolean(scheduledAt || scheduledUnpublishAt);
    useEffect(() => {
        if (!open)
            return;
        setPublishAt(scheduledAt ? toLocalDateTimeInput(scheduledAt) : defaultScheduleTime());
        setUnpublishAt(scheduledUnpublishAt ? toLocalDateTimeInput(scheduledUnpublishAt) : '');
        setIncludeUnpublish(Boolean(scheduledUnpublishAt));
    }, [open, scheduledAt, scheduledUnpublishAt]);
    async function handleSave() {
        if (!publishAt && !(includeUnpublish && unpublishAt)) {
            toast.error('Pick a publish or unpublish time');
            return;
        }
        // datetime-local is parsed by the browser as local time; new Date() on
        // that string respects the user's timezone and serialises to a UTC
        // ISO string the server can compare against `Date.now()` cleanly.
        const publishDate = publishAt ? new Date(publishAt) : null;
        const unpublishDate = includeUnpublish && unpublishAt ? new Date(unpublishAt) : null;
        if (publishDate && publishDate.getTime() <= Date.now()) {
            toast.error('Publish time must be in the future');
            return;
        }
        if (unpublishDate && unpublishDate.getTime() <= Date.now()) {
            toast.error('Unpublish time must be in the future');
            return;
        }
        if (publishDate && unpublishDate && unpublishDate <= publishDate) {
            toast.error('Unpublish time must be after publish time');
            return;
        }
        setSaving(true);
        const res = await cmsApi(`/collections/${collectionSlug}/${documentId}/schedule`, {
            method: 'POST',
            body: JSON.stringify({
                scheduledAt: publishDate ? publishDate.toISOString() : null,
                scheduledUnpublishAt: unpublishDate ? unpublishDate.toISOString() : null,
            }),
        });
        setSaving(false);
        if (res.error) {
            toast.error(res.error);
            return;
        }
        toast.success(publishDate ? 'Publish scheduled' : 'Unpublish scheduled');
        onScheduled?.({
            status: res.data?.status ?? 'SCHEDULED',
            scheduledAt: res.data?.scheduledAt ?? (publishDate ? publishDate.toISOString() : null),
            scheduledUnpublishAt: res.data?.scheduledUnpublishAt ?? (unpublishDate ? unpublishDate.toISOString() : null),
        });
        onClose();
    }
    async function handleCancelSchedule() {
        setCancelling(true);
        const res = await cmsApi(`/collections/${collectionSlug}/${documentId}/schedule`, {
            method: 'DELETE',
        });
        setCancelling(false);
        if (res.error) {
            toast.error(res.error);
            return;
        }
        toast.success('Schedule cancelled');
        onScheduled?.({
            status: res.data?.status ?? 'DRAFT',
            scheduledAt: null,
            scheduledUnpublishAt: null,
        });
        onClose();
    }
    if (!open)
        return null;
    return (_jsxs("div", { className: "fixed inset-0 z-50 flex items-center justify-center p-4", children: [_jsx("div", { className: "fixed inset-0 bg-black/40", onClick: onClose }), _jsxs("div", { className: "relative w-full max-w-md rounded-lg bg-white shadow-xl", children: [_jsxs("div", { className: "flex items-center justify-between border-b border-gray-200 px-4 py-3", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Calendar, { className: "h-5 w-5 text-gray-600" }), _jsx("h2", { className: "text-lg font-semibold text-gray-900", children: "Schedule publishing" })] }), _jsx("button", { onClick: onClose, className: "rounded-lg p-1.5 transition-colors hover:bg-gray-100", children: _jsx(X, { className: "h-5 w-5 text-gray-500" }) })] }), _jsxs("div", { className: "space-y-4 px-4 py-4", children: [_jsxs("div", { className: "space-y-1.5", children: [_jsx("label", { className: "text-sm font-medium text-gray-700", children: "Publish at" }), _jsxs("div", { className: "relative", children: [_jsx(Clock, { className: "pointer-events-none absolute top-2.5 left-2.5 h-4 w-4 text-gray-400" }), _jsx("input", { type: "datetime-local", value: publishAt, onChange: (e) => setPublishAt(e.target.value), min: toLocalDateTimeInput(new Date(Date.now() + 60 * 1000)), className: "w-full rounded-md border border-gray-300 bg-white py-2 pr-3 pl-9 text-sm focus:border-blue-500 focus:ring-1 focus:ring-blue-500 focus:outline-none" })] }), _jsx("p", { className: "text-xs text-gray-500", children: "The document will move from DRAFT to PUBLISHED at this time (your local timezone)." })] }), _jsxs("label", { className: "flex items-center gap-2 text-sm text-gray-700", children: [_jsx("input", { type: "checkbox", checked: includeUnpublish, onChange: (e) => setIncludeUnpublish(e.target.checked), className: "h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500" }), "Also schedule an unpublish"] }), includeUnpublish && (_jsxs("div", { className: "space-y-1.5", children: [_jsx("label", { className: "text-sm font-medium text-gray-700", children: "Unpublish at" }), _jsxs("div", { className: "relative", children: [_jsx(Clock, { className: "pointer-events-none absolute top-2.5 left-2.5 h-4 w-4 text-gray-400" }), _jsx("input", { type: "datetime-local", value: unpublishAt, onChange: (e) => setUnpublishAt(e.target.value), min: publishAt || toLocalDateTimeInput(new Date(Date.now() + 60 * 1000)), className: "w-full rounded-md border border-gray-300 bg-white py-2 pr-3 pl-9 text-sm focus:border-blue-500 focus:ring-1 focus:ring-blue-500 focus:outline-none" })] })] }))] }), _jsxs("div", { className: "flex items-center justify-between gap-2 border-t border-gray-200 px-4 py-3", children: [hasExistingSchedule ? (_jsxs("button", { onClick: handleCancelSchedule, disabled: cancelling || saving, className: "inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium text-red-700 hover:bg-red-50 disabled:opacity-50", children: [cancelling ? (_jsx(Loader2, { className: "h-4 w-4 animate-spin" })) : (_jsx(X, { className: "h-4 w-4" })), "Cancel schedule"] })) : (_jsx("span", {})), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("button", { onClick: onClose, className: "rounded-md px-3 py-1.5 text-sm text-gray-700 hover:bg-gray-100", children: "Close" }), _jsxs("button", { onClick: handleSave, disabled: saving || cancelling, className: "inline-flex items-center gap-1.5 rounded-md bg-blue-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50", children: [saving ? (_jsx(Loader2, { className: "h-4 w-4 animate-spin" })) : (_jsx(Calendar, { className: "h-4 w-4" })), hasExistingSchedule ? 'Reschedule' : 'Schedule'] })] })] })] })] }));
}
//# sourceMappingURL=SchedulePublishDialog.js.map