"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { format } from "date-fns";
import { Calendar as CalendarIcon } from "lucide-react";
import { useEditContext } from "../client/editContext";
import { cn } from "../../lib/utils";
import { Button } from "../../components/ui/button";
import { Popover, PopoverContent, PopoverTrigger, } from "../../components/ui/popover";
import { Calendar } from "../../components/ui/calendar";
import { useEffect, useState } from "react";
import { Loader2 } from "lucide-react";
// Helper function to format date to compact ISO format: YYYYMMDDTHHMMSSZ
const formatDateToCompactISO = (date) => {
    const year = date.getUTCFullYear().toString();
    const month = (date.getUTCMonth() + 1).toString().padStart(2, "0");
    const day = date.getUTCDate().toString().padStart(2, "0");
    const hours = date.getUTCHours().toString().padStart(2, "0");
    const minutes = date.getUTCMinutes().toString().padStart(2, "0");
    const seconds = date.getUTCSeconds().toString().padStart(2, "0");
    return `${year}${month}${day}T${hours}${minutes}${seconds}Z`;
};
export function DateFieldEditor({ field, readOnly, }) {
    const editContext = useEditContext();
    const [isUpdating, setIsUpdating] = useState(false);
    const [date, setDate] = useState(undefined);
    useEffect(() => {
        // Parse the date from the field rawValue (compact ISO format: YYYYMMDDTHHMMSSZ)
        const dateString = field.rawValue;
        if (dateString && dateString.trim() !== "") {
            try {
                // Handle compact ISO format: 20250714T220000Z
                let parsedDate;
                if (dateString.match(/^\d{8}T\d{6}Z$/)) {
                    // Convert compact format to standard ISO: 20250714T220000Z -> 2025-07-14T22:00:00Z
                    const standardISO = dateString.replace(/(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z/, "$1-$2-$3T$4:$5:$6Z");
                    parsedDate = new Date(standardISO);
                }
                else {
                    // Fallback to direct parsing
                    parsedDate = new Date(dateString);
                }
                if (!isNaN(parsedDate.getTime())) {
                    setDate(parsedDate);
                }
                else {
                    setDate(undefined);
                }
            }
            catch (error) {
                console.warn("Failed to parse date from field value:", dateString);
                setDate(undefined);
            }
        }
        else {
            setDate(undefined);
        }
    }, [field.rawValue]);
    if (!editContext)
        return null;
    const fieldItem = field.descriptor.item;
    if (!fieldItem)
        return null;
    if (isUpdating) {
        return _jsx(Loader2, { className: "h-[18px] w-[18px] animate-spin" });
    }
    const handleDateSelect = async (selectedDate) => {
        if (readOnly)
            return;
        setIsUpdating(true);
        try {
            // Format date to compact ISO format: YYYYMMDDTHHMMSSZ
            const rawValue = selectedDate ? formatDateToCompactISO(selectedDate) : "";
            await editContext.operations.editField({
                field: field.descriptor,
                rawValue: rawValue,
                value: rawValue,
                refresh: "immediate",
            });
        }
        catch (error) {
            console.error("Failed to update date field:", error);
            // Show error to user if possible
            if (editContext.showToast) {
                editContext.showToast("Failed to update date. Please try again.");
            }
        }
        finally {
            setIsUpdating(false);
        }
    };
    return (_jsxs(Popover, { enableIframeClickDetection: false, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs(Button, { variant: "outline", "data-empty": !date, size: "sm", className: cn("bg-neutral-grey-5 h-7.5 justify-start p-0 text-left text-xs font-normal", !date && "text-muted-foreground"), disabled: readOnly, children: [_jsx(CalendarIcon, { className: "mr-2 h-4 w-4" }), date ? format(date, "PPP") : _jsx("span", { children: "Pick a date!" })] }) }), _jsx(PopoverContent, { className: "w-auto p-0", align: "start", children: _jsx("div", { className: "p-3", onMouseDown: (e) => e.stopPropagation(), onClick: (e) => e.stopPropagation(), children: _jsx(Calendar, { mode: "single", selected: date, onSelect: handleDateSelect }) }) })] }));
}
//# sourceMappingURL=DateFieldEditor.js.map