'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useEffect, useRef, useCallback } from 'react';
import { Search, X, Loader2, Plus } from 'lucide-react';
import { cmsApi } from '../lib/api.js';
const STATUS_STYLES = {
    PUBLISHED: 'bg-green-100 text-green-800',
    DRAFT: 'bg-yellow-100 text-yellow-800',
    ARCHIVED: 'bg-gray-100 text-gray-600',
    SCHEDULED: 'bg-blue-100 text-blue-800',
};
function relativeTime(dateStr) {
    if (!dateStr)
        return '';
    const diff = Date.now() - new Date(dateStr).getTime();
    const seconds = Math.floor(diff / 1000);
    if (seconds < 60)
        return 'just now';
    const minutes = Math.floor(seconds / 60);
    if (minutes < 60)
        return `${minutes}m ago`;
    const hours = Math.floor(minutes / 60);
    if (hours < 24)
        return `${hours}h ago`;
    const days = Math.floor(hours / 24);
    if (days < 30)
        return `${days}d ago`;
    const months = Math.floor(days / 30);
    if (months < 12)
        return `${months}mo ago`;
    return `${Math.floor(months / 12)}y ago`;
}
export function RelationshipField({ label, value, onChange, multi = false, required, helpText, relationTo = 'pages', useAsTitle = 'title', onNavigate, }) {
    const [searchTerm, setSearchTerm] = useState('');
    const [open, setOpen] = useState(false);
    const [options, setOptions] = useState([]);
    const [loading, setLoading] = useState(false);
    const dropdownRef = useRef(null);
    const debounceRef = useRef(null);
    const selectedIds = multi
        ? Array.isArray(value)
            ? value
            : []
        : typeof value === 'string' && value
            ? [value]
            : [];
    const fetchOptions = useCallback(async (query) => {
        setLoading(true);
        const searchParam = query ? `&search=${encodeURIComponent(query)}` : '';
        const res = await cmsApi(`/collections/${relationTo}?pageSize=50${searchParam}`);
        if (res.data) {
            const docs = res.data.docs ?? [];
            setOptions(docs);
        }
        setLoading(false);
    }, [relationTo]);
    useEffect(() => {
        if (open)
            fetchOptions(searchTerm);
    }, [open]);
    const handleSearch = useCallback((query) => {
        setSearchTerm(query);
        if (debounceRef.current)
            clearTimeout(debounceRef.current);
        debounceRef.current = setTimeout(() => fetchOptions(query), 300);
    }, [fetchOptions]);
    useEffect(() => {
        function handleClickOutside(e) {
            if (dropdownRef.current && !dropdownRef.current.contains(e.target)) {
                setOpen(false);
            }
        }
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);
    function getDocTitle(doc) {
        if (doc.title)
            return doc.title;
        const d = doc.data;
        if (d && typeof d === 'object') {
            if (typeof d[useAsTitle] === 'string')
                return d[useAsTitle];
            if (typeof d.title === 'string')
                return d.title;
            if (typeof d.name === 'string')
                return d.name;
        }
        return doc.id;
    }
    function handleToggle(id) {
        if (multi) {
            const next = selectedIds.includes(id)
                ? selectedIds.filter((v) => v !== id)
                : [...selectedIds, id];
            onChange(next);
        }
        else {
            onChange(id);
            setOpen(false);
        }
    }
    function handleRemove(id) {
        if (multi) {
            onChange(selectedIds.filter((v) => v !== id));
        }
        else {
            onChange('');
        }
    }
    const selectedItems = options.filter((opt) => selectedIds.includes(opt.id));
    const unselectedItems = options.filter((opt) => !selectedIds.includes(opt.id));
    function renderOption(opt, isSelected) {
        const status = opt.status ?? opt.data?.status;
        const collection = opt.collection ?? relationTo;
        const statusClass = STATUS_STYLES[status] ?? 'bg-gray-100 text-gray-600';
        return (_jsxs("button", { type: "button", onClick: () => handleToggle(opt.id), className: `flex w-full items-center gap-2 px-3 py-2 text-sm hover:bg-[var(--accent)] ${isSelected ? 'font-medium' : ''}`, children: [_jsxs("div", { className: "min-w-0 flex-1 text-left", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("span", { className: "truncate", children: getDocTitle(opt) }), isSelected && _jsx("span", { className: "shrink-0 text-[var(--primary)]", children: "\u2713" })] }), _jsxs("div", { className: "mt-0.5 flex items-center gap-2", children: [_jsx("span", { className: "text-[10px] text-[var(--muted-foreground)]", children: collection }), opt.updatedAt && (_jsx("span", { className: "text-[10px] text-[var(--muted-foreground)]", children: relativeTime(opt.updatedAt) }))] })] }), status && (_jsx("span", { className: `shrink-0 rounded px-1.5 py-0.5 text-[10px] font-medium ${statusClass}`, children: status }))] }));
    }
    return (_jsxs("div", { className: "relative", ref: dropdownRef, children: [_jsxs("label", { className: "mb-1 block text-sm font-medium", children: [label, required && _jsx("span", { className: "ml-0.5 text-[var(--destructive)]", children: "*" })] }), selectedItems.length > 0 && (_jsx("div", { className: "mb-2 flex flex-wrap gap-1", children: selectedItems.map((item) => (_jsxs("span", { className: "inline-flex items-center gap-1 rounded-md bg-[var(--accent)] px-2 py-1 text-xs", children: [getDocTitle(item), _jsx("button", { type: "button", onClick: () => handleRemove(item.id), className: "hover:text-[var(--destructive)]", children: _jsx(X, { className: "h-3 w-3" }) })] }, item.id))) })), _jsxs("div", { className: "relative", children: [_jsx(Search, { className: "pointer-events-none absolute top-1/2 left-2.5 h-4 w-4 -translate-y-1/2 text-[var(--muted-foreground)]" }), _jsx("input", { type: "text", value: searchTerm, onChange: (e) => handleSearch(e.target.value), onFocus: () => setOpen(true), placeholder: `Search ${relationTo}...`, className: "w-full rounded-md border border-[var(--border)] bg-[var(--input-background)] py-2 pr-3 pl-8 text-sm outline-none focus:ring-2 focus:ring-[var(--ring)]" }), loading && (_jsx(Loader2, { className: "absolute top-1/2 right-2.5 h-4 w-4 -translate-y-1/2 animate-spin text-[var(--muted-foreground)]" })), open && (_jsxs("ul", { className: "absolute z-50 mt-1 max-h-60 w-full overflow-y-auto rounded-md border border-[var(--border)] bg-[var(--popover)] py-1 shadow-lg", children: [unselectedItems.map((opt) => (_jsx("li", { children: renderOption(opt, false) }, opt.id))), selectedItems.length > 0 && unselectedItems.length > 0 && (_jsx("li", { className: "my-1 border-t border-[var(--border)]" })), selectedItems.map((opt) => (_jsx("li", { children: renderOption(opt, true) }, opt.id))), options.length === 0 && !loading && (_jsx("li", { className: "px-3 py-2 text-sm text-[var(--muted-foreground)]", children: "No results" })), _jsx("li", { className: "mt-1 border-t border-[var(--border)]", children: _jsxs("button", { type: "button", onClick: () => {
                                        setOpen(false);
                                        onNavigate?.(`/${relationTo}/new`);
                                    }, className: "flex w-full items-center gap-2 px-3 py-2 text-sm text-[var(--primary)] hover:bg-[var(--accent)]", children: [_jsx(Plus, { className: "h-3.5 w-3.5" }), "Create New"] }) })] }))] }), helpText && _jsx("p", { className: "mt-1 text-xs text-[var(--muted-foreground)]", children: helpText })] }));
}
//# sourceMappingURL=RelationshipField.js.map