"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { format } from "date-fns";
import { Calendar as CalendarIcon, Clock } 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";
// 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 DateTimeFieldEditor({ field, readOnly, }) {
    const editContext = useEditContext();
    const [isUpdating, setIsUpdating] = useState(false);
    const [date, setDate] = useState(undefined);
    const [time, setTime] = useState("");
    const [hours, setHours] = useState(0);
    const [minutes, setMinutes] = useState(0);
    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);
                    const parsedHours = parsedDate.getHours();
                    const parsedMinutes = parsedDate.getMinutes();
                    setHours(parsedHours);
                    setMinutes(parsedMinutes);
                    setTime(`${parsedHours.toString().padStart(2, "0")}:${parsedMinutes.toString().padStart(2, "0")}`);
                }
                else {
                    setDate(undefined);
                    setHours(0);
                    setMinutes(0);
                    setTime("");
                }
            }
            catch (error) {
                console.warn("Failed to parse date from field value:", dateString);
                setDate(undefined);
                setHours(0);
                setMinutes(0);
                setTime("");
            }
        }
        else {
            setDate(undefined);
            setHours(0);
            setMinutes(0);
            setTime("");
        }
    }, [field.rawValue]);
    if (!editContext)
        return null;
    const fieldItem = field.descriptor.item;
    if (!fieldItem)
        return null;
    const updateDateTime = async (newDate, newTime) => {
        if (readOnly)
            return;
        setIsUpdating(true);
        try {
            let finalDate;
            if (newDate || date) {
                const baseDate = newDate || date;
                const timeToUse = newTime !== undefined ? newTime : time;
                if (timeToUse && timeToUse.match(/^\d{2}:\d{2}$/)) {
                    const timeParts = timeToUse.split(":");
                    if (timeParts.length === 2 && timeParts[0] && timeParts[1]) {
                        const hours = parseInt(timeParts[0], 10);
                        const minutes = parseInt(timeParts[1], 10);
                        if (!isNaN(hours) && !isNaN(minutes)) {
                            finalDate = new Date(baseDate);
                            finalDate.setHours(hours, minutes, 0, 0);
                        }
                        else {
                            finalDate = baseDate;
                        }
                    }
                    else {
                        finalDate = baseDate;
                    }
                }
                else {
                    finalDate = baseDate;
                }
            }
            // Format date to compact ISO format: YYYYMMDDTHHMMSSZ
            const rawValue = finalDate ? formatDateToCompactISO(finalDate) : "";
            await editContext.operations.editField({
                field: field.descriptor,
                rawValue: rawValue,
                value: rawValue,
                refresh: "immediate",
            });
        }
        catch (error) {
            console.error("Failed to update datetime field:", error);
            // Show error to user if possible
            if (editContext.showToast) {
                editContext.showToast("Failed to update date/time. Please try again.");
            }
        }
        finally {
            setIsUpdating(false);
        }
    };
    const handleDateSelect = async (selectedDate) => {
        setDate(selectedDate);
        await updateDateTime(selectedDate, time);
    };
    const handleHoursChange = async (newHours) => {
        setHours(newHours);
        const newTime = `${newHours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}`;
        setTime(newTime);
        if (date) {
            await updateDateTime(date, newTime);
        }
    };
    const handleMinutesChange = async (newMinutes) => {
        setMinutes(newMinutes);
        const newTime = `${hours.toString().padStart(2, "0")}:${newMinutes.toString().padStart(2, "0")}`;
        setTime(newTime);
        if (date) {
            await updateDateTime(date, newTime);
        }
    };
    return (_jsxs("div", { className: "flex items-center gap-2", children: [_jsxs(Popover, { enableIframeClickDetection: false, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs(Button, { variant: "outline", size: "sm", "data-empty": !date, className: cn("justify-start rounded-[4px] bg-white px-2 text-left text-xs font-normal", "focus-visible:border-neutral-grey-100 aria-expanded:border-neutral-grey-100", !date && "text-muted-foreground"), disabled: readOnly, children: [_jsx(CalendarIcon, { strokeWidth: 1, 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 }) }) })] }), _jsxs("div", { className: cn("flex h-8 items-center justify-start gap-1 rounded-[4px] bg-white px-2 text-left text-xs font-normal", !date && "text-muted-foreground"), children: [_jsx(Clock, { strokeWidth: 1, className: "text-muted-foreground h-4 w-4" }), _jsxs(Popover, { enableIframeClickDetection: false, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsx(Button, { variant: "ghost", className: "h-8 w-12 bg-white p-0 text-xs", disabled: readOnly || !date, children: hours.toString().padStart(2, "0") }) }), _jsx(PopoverContent, { className: "w-auto p-2", align: "start", children: _jsx("div", { className: "grid max-h-48 grid-cols-4 gap-1 overflow-y-auto", onMouseDown: (e) => e.stopPropagation(), onClick: (e) => e.stopPropagation(), children: Array.from({ length: 24 }, (_, i) => (_jsx(Button, { variant: hours === i ? "default" : "ghost", className: "h-8 w-8 p-0 text-xs", onClick: () => handleHoursChange(i), children: i.toString().padStart(2, "0") }, i))) }) })] }), _jsx("span", { className: "text-muted-foreground", children: ":" }), _jsxs(Popover, { enableIframeClickDetection: false, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsx(Button, { variant: "ghost", className: "h-8 w-12 bg-white p-0 text-xs", disabled: readOnly || !date, children: minutes.toString().padStart(2, "0") }) }), _jsx(PopoverContent, { className: "w-auto p-2", align: "start", children: _jsx("div", { className: "grid max-h-48 grid-cols-4 gap-1 overflow-y-auto", onMouseDown: (e) => e.stopPropagation(), onClick: (e) => e.stopPropagation(), children: Array.from({ length: 60 }, (_, i) => (_jsx(Button, { variant: minutes === i ? "default" : "ghost", className: "h-8 w-8 p-0 text-xs", onClick: () => handleMinutesChange(i), children: i.toString().padStart(2, "0") }, i))) }) })] })] })] }));
}
//# sourceMappingURL=DateTimeFieldEditor.js.map