/**
 * Collaboration form date picker component
 * Provides a reusable date picker field with label, error message, and chat icon functionality
 */
'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React from 'react';
import { cn } from '../utils/cn.js';
import { format_date, DEFAULT_DATE_FORMAT } from '../utils/date_format.js';
import { use_logger } from '../logger/context.js';
export { DEFAULT_DATE_FORMAT } from '../utils/date_format.js';
import { CollabFormFieldContainer, CollabFormFieldLabel, CollabFormFieldError, CollabFormFieldReferenceTag, } from './hazo_collab_form_base.js';
import { BaseFieldLayout } from './shared/base_field_layout.js';
import { use_base_form_field } from './shared/use_base_form_field.js';
/**
 * Convert ISO date string to Date object
 */
function iso_string_to_date(iso_string) {
    if (!iso_string)
        return undefined;
    const date = new Date(iso_string + 'T00:00:00');
    return isNaN(date.getTime()) ? undefined : date;
}
/**
 * Convert Date object to ISO date string (YYYY-MM-DD)
 */
function date_to_iso_string(date) {
    if (!date)
        return '';
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}
/**
 * Format date for display using the specified date format
 */
function format_date_display(iso_string, date_format = DEFAULT_DATE_FORMAT) {
    if (!iso_string)
        return '';
    return format_date(iso_string, date_format);
}
/**
 * Collaboration form date picker component
 * Displays a labeled date picker field with error message and chat icon
 */
export const HazoCollabFormDate = React.forwardRef((props, ref) => {
    const base = use_base_form_field(props, ref);
    if (base.should_hide)
        return null;
    const { value, onChange, field_validator, date_mode = 'single', min_date, max_date, disabled_dates, date_wrapper_class_name, placeholder, caption_layout = 'dropdown', start_month, end_month, date_format = DEFAULT_DATE_FORMAT, } = props;
    const logger = use_logger();
    // State for popover open/close
    const [popover_open, set_popover_open] = React.useState(false);
    // Dynamic imports for shadcn components
    const [Components, setComponents] = React.useState(null);
    const [is_loading, set_is_loading] = React.useState(true);
    const [is_mounted, set_is_mounted] = React.useState(false);
    React.useEffect(() => {
        set_is_mounted(true);
    }, []);
    React.useEffect(() => {
        if (!is_mounted)
            return;
        const loadComponents = async () => {
            try {
                set_is_loading(true);
                const popoverModule = await import('hazo_ui').catch(() => null);
                const calendarModule = await import('hazo_ui').catch(() => null);
                const buttonModule = await import('hazo_ui').catch(() => null);
                const lucideModule = await import('lucide-react').catch(() => null);
                if (popoverModule && calendarModule && buttonModule && lucideModule) {
                    setComponents({
                        Popover: popoverModule.Popover,
                        PopoverTrigger: popoverModule.PopoverTrigger,
                        PopoverContent: popoverModule.PopoverContent,
                        Calendar: calendarModule.Calendar,
                        Button: buttonModule.Button,
                        CalendarIcon: lucideModule.CalendarIcon,
                    });
                }
                else {
                    logger.warn('[HazoCollabFormDate] shadcn components not found', {
                        required: ['popover', 'calendar', 'button', 'lucide-react'],
                        install_command: 'npx shadcn@latest add popover calendar button && npm install lucide-react',
                    });
                }
            }
            catch (error) {
                logger.warn('[HazoCollabFormDate] Error loading components', {
                    error: error instanceof Error ? error.message : String(error),
                });
            }
            finally {
                set_is_loading(false);
            }
        };
        loadComponents();
    }, [is_mounted]);
    // Date computation memos
    const get_calendar_date = React.useMemo(() => {
        if (date_mode === 'single') {
            return iso_string_to_date(value);
        }
        else {
            const range_value = value;
            if (!range_value)
                return undefined;
            return {
                from: iso_string_to_date(range_value.from),
                to: iso_string_to_date(range_value.to),
            };
        }
    }, [value, date_mode]);
    const disabled_dates_as_dates = React.useMemo(() => {
        if (!disabled_dates || disabled_dates.length === 0)
            return undefined;
        return disabled_dates.map(iso_string_to_date).filter((d) => d !== undefined);
    }, [disabled_dates]);
    const min_date_obj = React.useMemo(() => iso_string_to_date(min_date), [min_date]);
    const max_date_obj = React.useMemo(() => iso_string_to_date(max_date), [max_date]);
    const start_month_obj = React.useMemo(() => {
        if (start_month instanceof Date)
            return start_month;
        if (typeof start_month === 'string')
            return iso_string_to_date(start_month);
        const default_start = new Date();
        default_start.setFullYear(default_start.getFullYear() - 100);
        return default_start;
    }, [start_month]);
    const end_month_obj = React.useMemo(() => {
        if (end_month instanceof Date)
            return end_month;
        if (typeof end_month === 'string')
            return iso_string_to_date(end_month);
        return new Date();
    }, [end_month]);
    const handle_date_select = React.useCallback((selected_date) => {
        if (!selected_date) {
            if (field_validator) {
                base.set_validation_error(field_validator(null));
            }
            if (date_mode === 'single') {
                onChange('');
            }
            else {
                onChange({ from: '', to: '' });
            }
            return;
        }
        if (date_mode === 'single') {
            const date = selected_date;
            if (field_validator) {
                base.set_validation_error(field_validator(date));
            }
            onChange(date_to_iso_string(date));
            set_popover_open(false);
        }
        else {
            const range = selected_date;
            const new_range = {
                from: date_to_iso_string(range.from),
                to: date_to_iso_string(range.to),
            };
            if (field_validator) {
                base.set_validation_error(field_validator(range));
            }
            onChange(new_range);
            if (range.from && range.to) {
                set_popover_open(false);
            }
        }
    }, [date_mode, onChange, field_validator, base.set_validation_error]);
    const get_button_text = React.useMemo(() => {
        if (date_mode === 'single') {
            const date_str = value;
            if (!date_str)
                return placeholder || 'Pick a date';
            return format_date_display(date_str, date_format);
        }
        else {
            const range_value = value;
            if (!range_value || (!range_value.from && !range_value.to)) {
                return placeholder || 'Pick a date range';
            }
            if (range_value.from && range_value.to) {
                return `${format_date_display(range_value.from, date_format)} - ${format_date_display(range_value.to, date_format)}`;
            }
            if (range_value.from) {
                return `${format_date_display(range_value.from, date_format)} - ...`;
            }
            return placeholder || 'Pick a date range';
        }
    }, [value, date_mode, placeholder, date_format]);
    // Loading state
    if (is_loading) {
        return (_jsxs(CollabFormFieldContainer, { ...base.container_props, children: [_jsx(CollabFormFieldLabel, { ...base.label_props }), _jsx("div", { className: cn('cls_collab_date_wrapper flex items-center gap-2', date_wrapper_class_name), suppressHydrationWarning: true, children: _jsx("div", { className: cn(base.field_width_class_name || 'flex-1', base.field_width_class_name && 'flex-shrink-0'), children: _jsx("div", { className: "cls_collab_date_loading w-full h-9 rounded-md border border-input bg-muted animate-pulse" }) }) })] }));
    }
    // Fallback if components not available
    if (!Components) {
        return (_jsxs(CollabFormFieldContainer, { ...base.container_props, children: [_jsx(CollabFormFieldLabel, { ...base.label_props }), _jsx("div", { className: cn('cls_collab_date_wrapper flex items-center gap-2', date_wrapper_class_name), suppressHydrationWarning: true, children: _jsx("div", { className: cn(base.field_width_class_name || 'flex-1', base.field_width_class_name && 'flex-shrink-0'), children: _jsxs("div", { className: "cls_collab_date_fallback w-full rounded-md border border-destructive bg-destructive/10 px-3 py-2 text-sm text-destructive", children: [_jsx("div", { className: "font-medium", children: "Missing shadcn/ui components" }), _jsxs("div", { className: "mt-1 text-xs opacity-90", children: ["Run: ", _jsx("code", { className: "bg-destructive/20 px-1 rounded", children: "npx hazo-collab-forms-setup --date" })] }), _jsxs("div", { className: "mt-1 text-xs opacity-70", children: ["Or manually: ", _jsx("code", { className: "bg-destructive/20 px-1 rounded", children: "npx shadcn@latest add popover calendar button" })] })] }) }) }), _jsx(CollabFormFieldReferenceTag, { ...base.reference_tag_props }), _jsx(CollabFormFieldError, { ...base.error_props })] }));
    }
    const { Popover, PopoverTrigger, PopoverContent, Calendar, Button, CalendarIcon } = Components;
    return (_jsx(BaseFieldLayout, { base: base, wrapper_class_name: "cls_collab_date_wrapper", wrapper_extra_class_name: date_wrapper_class_name, children: _jsxs(Popover, { open: popover_open, onOpenChange: set_popover_open, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs(Button, { ref: base.component_ref, id: base.field_id_final, variant: "outline", disabled: base.is_field_disabled, className: cn('cls_collab_date_button w-full h-9 justify-start text-left font-normal', !value && 'text-muted-foreground', base.display_error && 'border-destructive focus-visible:ring-destructive', base.locked && 'bg-slate-100', base.skipped && 'bg-slate-100 opacity-60', base.show_required_highlight && 'bg-red-50'), "aria-invalid": base.display_error ? 'true' : 'false', "aria-describedby": base.display_error ? `${base.field_id_final}-error` : undefined, children: [_jsx(CalendarIcon, { className: "mr-2 h-4 w-4" }), get_button_text] }) }), _jsx(PopoverContent, { className: "w-auto p-0", align: "start", children: _jsx(Calendar, { mode: date_mode, selected: get_calendar_date, onSelect: handle_date_select, captionLayout: caption_layout, startMonth: start_month_obj, endMonth: end_month_obj, disabled: (date) => {
                            const normalized_date = new Date(date.getFullYear(), date.getMonth(), date.getDate());
                            if (min_date_obj) {
                                const normalized_min = new Date(min_date_obj.getFullYear(), min_date_obj.getMonth(), min_date_obj.getDate());
                                if (normalized_date < normalized_min)
                                    return true;
                            }
                            if (max_date_obj) {
                                const normalized_max = new Date(max_date_obj.getFullYear(), max_date_obj.getMonth(), max_date_obj.getDate());
                                if (normalized_date > normalized_max)
                                    return true;
                            }
                            if (disabled_dates_as_dates) {
                                const date_str = date_to_iso_string(date);
                                return disabled_dates_as_dates.some(d => date_to_iso_string(d) === date_str);
                            }
                            return false;
                        }, initialFocus: true }) })] }) }));
});
HazoCollabFormDate.displayName = 'HazoCollabFormDate';
//# sourceMappingURL=hazo_collab_form_date.js.map