'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useEffect, useRef } from 'react';
import { AlertTriangle, Calendar, Eye, EyeOff, Save, Copy, Loader2, Clock, Share2, XCircle, } from 'lucide-react';
import { toast } from 'sonner';
import { FieldRenderer } from '../fields/FieldRenderer.js';
import { RelationshipField } from '../fields/RelationshipField.js';
import { Button } from '../components/ui/Button.js';
import { LivePreview } from '../components/LivePreview.js';
import { VersionHistory } from '../components/VersionHistory.js';
import { PresenceIndicator } from '../components/PresenceIndicator.js';
import { SEOPanel } from '../components/SEOPanel.js';
import { SchedulePublishDialog } from '../components/SchedulePublishDialog.js';
import { SharePreviewLinkDialog } from '../components/SharePreviewLinkDialog.js';
import { cmsApi } from '../lib/api.js';
export function DocumentEdit({ collectionSlug, documentId, config, onNavigate, }) {
    const isNew = !documentId;
    const [values, setValues] = useState({});
    const [initialValues, setInitialValues] = useState({});
    const [seoData, setSeoData] = useState({});
    const [initialSeoData, setInitialSeoData] = useState({});
    const [layoutAssignments, setLayoutAssignments] = useState({});
    const [initialLayoutAssignments, setInitialLayoutAssignments] = useState({});
    const [saving, setSaving] = useState(false);
    const [loading, setLoading] = useState(!isNew);
    const [showPreview, setShowPreview] = useState(false);
    const [showVersions, setShowVersions] = useState(false);
    const [showSchedule, setShowSchedule] = useState(false);
    const [showShareLink, setShowShareLink] = useState(false);
    const [docStatus, setDocStatus] = useState('DRAFT');
    const [scheduledAt, setScheduledAt] = useState(null);
    const [scheduledUnpublishAt, setScheduledUnpublishAt] = useState(null);
    const hasLoadedRef = useRef(false);
    const collections = config?.collections;
    const collection = Array.isArray(collections)
        ? collections.find((c) => c.slug === collectionSlug)
        : collections?.[collectionSlug];
    const layoutConfig = config?.layout;
    const layoutRegions = layoutConfig?.regions
        ? Object.entries(layoutConfig.regions).map(([name, region]) => ({
            name,
            collection: region.collection,
            label: region.label ?? name.charAt(0).toUpperCase() + name.slice(1),
        }))
        : [];
    const hasLayout = layoutRegions.length > 0 && (collection?.type === 'page' || collection?.urlPrefix !== undefined);
    const previewUrl = collection?.admin?.preview ? collection.admin.preview({}) : undefined;
    const fields = collection?.fields
        ? Array.isArray(collection.fields)
            ? collection.fields
            : Object.entries(collection.fields).map(([name, def]) => ({ name, ...def }))
        : [];
    const useAsTitleField = collection?.admin?.useAsTitle ?? 'title';
    const displayTitle = isNew
        ? `New ${collection?.labels?.singular ?? collectionSlug}`
        : `Edit ${values[useAsTitleField] ?? 'Document'}`;
    const isDirty = JSON.stringify(values) !== JSON.stringify(initialValues) ||
        JSON.stringify(seoData) !== JSON.stringify(initialSeoData) ||
        JSON.stringify(layoutAssignments) !== JSON.stringify(initialLayoutAssignments);
    useEffect(() => {
        if (!isNew && documentId && !hasLoadedRef.current) {
            hasLoadedRef.current = true;
            loadDocument();
        }
    }, [documentId, isNew]);
    useEffect(() => {
        if (!isDirty)
            return;
        const handler = (e) => {
            e.preventDefault();
        };
        window.addEventListener('beforeunload', handler);
        return () => window.removeEventListener('beforeunload', handler);
    }, [isDirty]);
    const SEO_FIELDS = [
        'metaTitle',
        'metaDescription',
        'focusKeyphrase',
        'canonical',
        'robotsPolicy',
        'noIndex',
        'noFollow',
        'ogTitle',
        'ogDescription',
        'ogImage',
        'twitterTitle',
        'twitterDescription',
        'twitterImage',
        'isCornerstone',
        'schemaType',
    ];
    async function loadDocument() {
        setLoading(true);
        const res = await cmsApi(`/collections/${collectionSlug}/${documentId}`);
        if (res.data) {
            const doc = res.data;
            const docData = doc.data && typeof doc.data === 'object' ? doc.data : {};
            const merged = {
                ...docData,
                title: doc.title ?? docData.title,
                slug: doc.slug ?? docData.slug,
            };
            setValues(merged);
            setInitialValues(merged);
            setDocStatus(doc.status ?? 'DRAFT');
            setScheduledAt(doc.scheduledAt ?? null);
            setScheduledUnpublishAt(doc.scheduledUnpublishAt ?? null);
            const loadedSeo = {};
            for (const key of SEO_FIELDS) {
                if (docData[key] !== undefined) {
                    ;
                    loadedSeo[key] = docData[key];
                }
            }
            setSeoData(loadedSeo);
            setInitialSeoData(loadedSeo);
            if (docData._layout && typeof docData._layout === 'object') {
                const loaded = docData._layout;
                setLayoutAssignments(loaded);
                setInitialLayoutAssignments(loaded);
            }
        }
        else if (res.error) {
            toast.error(`Failed to load document: ${res.error}`);
        }
        setLoading(false);
    }
    function handleFieldChange(name, value) {
        setValues((prev) => ({ ...prev, [name]: value }));
    }
    async function handleSave() {
        setSaving(true);
        const layoutPayload = Object.keys(layoutAssignments).length > 0 ? { _layout: layoutAssignments } : {};
        const payload = { ...values, ...seoData, ...layoutPayload };
        try {
            if (isNew) {
                const res = await cmsApi(`/collections/${collectionSlug}`, {
                    method: 'POST',
                    body: JSON.stringify(payload),
                });
                if (res.error) {
                    toast.error(res.error);
                }
                else {
                    toast.success('Document created');
                    const newId = res.data?.id;
                    setInitialValues(values);
                    setInitialSeoData(seoData);
                    setInitialLayoutAssignments(layoutAssignments);
                    if (newId && onNavigate) {
                        onNavigate(`/${collectionSlug}/${newId}`);
                    }
                }
            }
            else {
                const res = await cmsApi(`/collections/${collectionSlug}/${documentId}`, {
                    method: 'PUT',
                    body: JSON.stringify(payload),
                });
                if (res.error) {
                    toast.error(res.error);
                }
                else {
                    toast.success('Changes saved');
                    setInitialValues(values);
                    setInitialSeoData(seoData);
                    setInitialLayoutAssignments(layoutAssignments);
                    if (res.data?.status)
                        setDocStatus(res.data.status);
                }
            }
        }
        catch {
            toast.error('An unexpected error occurred');
        }
        setSaving(false);
    }
    async function handlePublish() {
        if (isNew)
            return;
        setSaving(true);
        const layoutPayload = Object.keys(layoutAssignments).length > 0 ? { _layout: layoutAssignments } : {};
        const res = await cmsApi(`/collections/${collectionSlug}/${documentId}`, {
            method: 'PUT',
            body: JSON.stringify({ ...values, ...seoData, ...layoutPayload, status: 'PUBLISHED' }),
        });
        if (res.error) {
            toast.error(res.error);
        }
        else {
            toast.success('Document published');
            setDocStatus('PUBLISHED');
            setInitialValues(values);
            setInitialSeoData(seoData);
            setInitialLayoutAssignments(layoutAssignments);
        }
        setSaving(false);
    }
    async function handleUnpublish() {
        if (isNew)
            return;
        setSaving(true);
        const layoutPayload = Object.keys(layoutAssignments).length > 0 ? { _layout: layoutAssignments } : {};
        const res = await cmsApi(`/collections/${collectionSlug}/${documentId}`, {
            method: 'PUT',
            body: JSON.stringify({ ...values, ...seoData, ...layoutPayload, status: 'DRAFT' }),
        });
        if (res.error) {
            toast.error(res.error);
        }
        else {
            toast.success('Document unpublished');
            setDocStatus('DRAFT');
            setInitialValues(values);
            setInitialSeoData(seoData);
            setInitialLayoutAssignments(layoutAssignments);
        }
        setSaving(false);
    }
    async function handleDuplicate() {
        if (isNew || !documentId)
            return;
        const res = await cmsApi(`/collections/${collectionSlug}`, {
            method: 'POST',
            body: JSON.stringify({
                ...values,
                title: values.title ? `${values.title} (Copy)` : undefined,
                slug: values.slug ? `${values.slug}-copy` : undefined,
            }),
        });
        if (res.error) {
            toast.error(res.error);
        }
        else {
            toast.success('Document duplicated');
            const newId = res.data?.id;
            if (newId && onNavigate) {
                onNavigate(`/${collectionSlug}/${newId}`);
            }
        }
    }
    const mainFields = fields.filter((f) => !['status', 'publishedAt', 'featured', 'featuredImage'].includes(f.name));
    const sidebarFields = fields.filter((f) => ['publishedAt', 'featured', 'featuredImage'].includes(f.name));
    const contentField = fields.find((f) => f.type === 'richText' || f.name === 'content' || f.name === 'body');
    const htmlContent = contentField ? (values[contentField.name] ?? '') : '';
    const docSlug = values.slug ?? '';
    const statusColor = docStatus === 'PUBLISHED'
        ? 'bg-green-100 text-green-800'
        : docStatus === 'SCHEDULED'
            ? 'bg-blue-100 text-blue-800'
            : 'bg-yellow-100 text-yellow-800';
    if (loading) {
        return (_jsx("div", { className: "flex min-h-[300px] items-center justify-center", children: _jsx(Loader2, { className: "h-8 w-8 animate-spin text-gray-400" }) }));
    }
    return (_jsxs("div", { className: "space-y-4", children: [_jsxs("div", { className: "flex items-center justify-between", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx("h1", { className: "text-2xl font-bold", children: displayTitle }), _jsx("span", { className: `inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${statusColor}`, children: docStatus }), documentId && _jsx(PresenceIndicator, { documentId: documentId }), isDirty && _jsx("span", { className: "text-xs font-medium text-amber-600", children: "Unsaved changes" })] }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsxs("button", { onClick: () => setShowPreview((v) => !v), className: "inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]", title: showPreview ? 'Hide preview' : 'Show preview', children: [showPreview ? _jsx(EyeOff, { className: "h-4 w-4" }) : _jsx(Eye, { className: "h-4 w-4" }), "Preview"] }), !isNew && (_jsxs(_Fragment, { children: [_jsxs("button", { onClick: () => setShowShareLink(true), className: "inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]", title: "Share a signed preview link for the current draft", children: [_jsx(Share2, { className: "h-4 w-4" }), "Share preview"] }), _jsxs("button", { onClick: () => setShowVersions(true), className: "inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]", title: "Version history", children: [_jsx(Clock, { className: "h-4 w-4" }), "History"] }), _jsxs("button", { onClick: handleDuplicate, className: "inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]", title: "Duplicate this document", children: [_jsx(Copy, { className: "h-4 w-4" }), "Duplicate"] })] }))] })] }), _jsxs("div", { className: showPreview ? 'grid grid-cols-2 gap-6' : '', children: [_jsxs("div", { className: "space-y-6", children: [fields.length === 0 ? (_jsxs("div", { className: "flex flex-col items-center justify-center rounded-lg border border-[var(--border)] py-16 text-center", children: [_jsx("div", { className: "mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-gray-100", children: _jsx(AlertTriangle, { className: "h-6 w-6 text-gray-400" }) }), _jsx("h3", { className: "mb-1 text-sm font-medium text-gray-900", children: "Collection schema not found" }), _jsx("p", { className: "text-sm text-gray-500", children: "No fields are defined for this collection." })] })) : (_jsxs("div", { className: "grid grid-cols-1 gap-6 lg:grid-cols-3", children: [_jsx("div", { className: "space-y-6 lg:col-span-2", children: mainFields.map((field) => (_jsx(FieldRenderer, { field: field, value: values[field.name], onChange: (val) => handleFieldChange(field.name, val) }, field.name))) }), _jsxs("div", { className: "space-y-6", children: [_jsxs("div", { className: "rounded-lg border border-[var(--border)] bg-[var(--card)] p-4", children: [_jsx("h3", { className: "mb-4 font-semibold", children: "Status" }), _jsxs("div", { className: "space-y-3", children: [!isNew && docStatus === 'DRAFT' && (_jsx(Button, { variant: "primary", className: "w-full", onClick: handlePublish, loading: saving, children: "Publish" })), !isNew && docStatus === 'PUBLISHED' && (_jsx(Button, { variant: "secondary", className: "w-full", onClick: handleUnpublish, loading: saving, children: "Unpublish" })), !isNew && (_jsxs("button", { onClick: () => setShowSchedule(true), className: "inline-flex w-full items-center justify-center gap-1.5 rounded-md border border-[var(--border)] bg-white px-3 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-50", children: [_jsx(Calendar, { className: "h-4 w-4" }), scheduledAt || scheduledUnpublishAt ? 'Reschedule' : 'Schedule'] })), !isNew && (scheduledAt || scheduledUnpublishAt) && (_jsxs("div", { className: "space-y-1 rounded-md border border-blue-100 bg-blue-50 px-3 py-2 text-xs text-blue-900", children: [scheduledAt && (_jsxs("div", { className: "flex items-center gap-1.5", children: [_jsx(Calendar, { className: "h-3.5 w-3.5" }), "Publishes ", new Date(scheduledAt).toLocaleString()] })), scheduledUnpublishAt && (_jsxs("div", { className: "flex items-center gap-1.5", children: [_jsx(XCircle, { className: "h-3.5 w-3.5" }), "Unpublishes ", new Date(scheduledUnpublishAt).toLocaleString()] }))] }))] })] }), sidebarFields.length > 0 && (_jsxs("div", { className: "rounded-lg border border-[var(--border)] bg-[var(--card)] p-4", children: [_jsx("h3", { className: "mb-4 font-semibold", children: "Metadata" }), sidebarFields.map((field) => (_jsx("div", { className: "mb-4", children: _jsx(FieldRenderer, { field: field, value: values[field.name], onChange: (val) => handleFieldChange(field.name, val) }) }, field.name)))] })), _jsx(SEOPanel, { title: values[useAsTitleField] ?? values.title ?? '', slug: docSlug, content: htmlContent, seoData: seoData, onChange: setSeoData, siteUrl: config?.siteUrl }), hasLayout && (_jsxs("div", { className: "rounded-lg border border-[var(--border)] bg-[var(--card)] p-4", children: [_jsx("h3", { className: "mb-1 font-semibold", children: "Layout" }), _jsx("p", { className: "mb-4 text-xs text-[var(--muted-foreground)]", children: "Assign header/footer variants. Child pages inherit from ancestors." }), _jsx("div", { className: "space-y-4", children: layoutRegions.map((region) => (_jsxs("div", { children: [_jsx(RelationshipField, { label: region.label, value: layoutAssignments[region.name] ?? '', onChange: (val) => {
                                                                        setLayoutAssignments((prev) => {
                                                                            const next = { ...prev };
                                                                            if (val && typeof val === 'string') {
                                                                                next[region.name] = val;
                                                                            }
                                                                            else {
                                                                                delete next[region.name];
                                                                            }
                                                                            return next;
                                                                        });
                                                                    }, relationTo: region.collection, helpText: !layoutAssignments[region.name]
                                                                        ? 'Inheriting from parent page or site default'
                                                                        : undefined }), layoutAssignments[region.name] && (_jsx("button", { type: "button", onClick: () => {
                                                                        setLayoutAssignments((prev) => {
                                                                            const next = { ...prev };
                                                                            delete next[region.name];
                                                                            return next;
                                                                        });
                                                                    }, className: "mt-1 text-xs text-[var(--primary)] hover:underline", children: "Clear override (inherit from parent)" }))] }, region.name))) })] }))] })] })), _jsxs("div", { className: "sticky bottom-0 flex items-center justify-end gap-3 border-t border-[var(--border)] bg-[var(--background)] px-4 py-3", children: [_jsx(Button, { variant: "secondary", onClick: () => onNavigate?.(`/${collectionSlug}`), children: "Cancel" }), _jsxs(Button, { variant: "primary", loading: saving, onClick: handleSave, "data-shortcut": "save", children: [_jsx(Save, { className: "mr-1.5 h-4 w-4" }), isNew ? 'Create' : 'Save Changes'] })] })] }), showPreview && (_jsx(LivePreview, { collection: collectionSlug, documentId: documentId, previewUrl: previewUrl, values: values, onClose: () => setShowPreview(false) }))] }), !isNew && documentId && (_jsx(VersionHistory, { collectionSlug: collectionSlug, documentId: documentId, open: showVersions, onClose: () => setShowVersions(false), onRestore: (data) => {
                    const restoredData = data;
                    setValues(restoredData);
                    setInitialValues(restoredData);
                } })), !isNew && documentId && (_jsx(SchedulePublishDialog, { collectionSlug: collectionSlug, documentId: documentId, scheduledAt: scheduledAt, scheduledUnpublishAt: scheduledUnpublishAt, open: showSchedule, onClose: () => setShowSchedule(false), onScheduled: (next) => {
                    setDocStatus(next.status);
                    setScheduledAt(next.scheduledAt);
                    setScheduledUnpublishAt(next.scheduledUnpublishAt);
                } })), !isNew && documentId && (_jsx(SharePreviewLinkDialog, { collectionSlug: collectionSlug, documentId: documentId, documentSlug: docSlug, siteUrl: config?.siteUrl, urlPrefix: collection?.urlPrefix ?? collectionSlug, open: showShareLink, onClose: () => setShowShareLink(false) }))] }));
}
//# sourceMappingURL=DocumentEdit.js.map