import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/* eslint-disable @typescript-eslint/no-explicit-any */
import { ThemeProvider, useTheme } from '@mui/material/styles';
import { DatePicker, LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import cx from 'classnames';
import { format, isValid, parse, parseISO } from 'date-fns';
import { enGB } from 'date-fns/locale';
import { useRef } from 'react';
import { Controller } from 'react-hook-form';
import { datePickerTheme } from './DatePickerTheme';
import './styles.scss';
const STORAGE_FORMAT = 'yyyy-MM-dd';
// Convert stored value (yyyy-MM-dd, ISO instant, etc.) to Date
const parseDate = (value) => {
    if (!value)
        return null;
    if (value instanceof Date)
        return isNaN(value.getTime()) ? null : value;
    const s = String(value).trim();
    if (!s)
        return null;
    const fromIso = parseISO(s);
    if (isValid(fromIso))
        return fromIso;
    try {
        const parsed = parse(s, STORAGE_FORMAT, new Date());
        return isNaN(parsed.getTime()) ? null : parsed;
    }
    catch {
        return null;
    }
};
// Format Date object into yyyy-MM-dd for storage
const formatDate = (date) => date && !isNaN(date.getTime()) ? format(date, STORAGE_FORMAT) : '';
export default function DatePickerField({ className, attr, label, createdForm, disabled, title, placeholder, required, onChange, onFocus, onBlur, onKeyDown, inputRef, width = '100%', height = '48px', minDate, maxDate, adapterLocale = enGB, displayFormat = 'dd/MM/yyyy', }) {
    const fieldName = attr;
    const outerTheme = useTheme();
    const inputElementRef = useRef(null);
    const hasError = () => !!createdForm.formState.errors[attr];
    const getClassNames = cx('ds-input-datepicker', className, { disabled });
    return (_jsx("div", { className: getClassNames, style: { width }, children: _jsx(Controller, { name: fieldName, control: createdForm.control, render: ({ field }) => (_jsxs(ThemeProvider, { theme: datePickerTheme(outerTheme), children: [_jsx(LocalizationProvider, { dateAdapter: AdapterDateFns, adapterLocale: adapterLocale, children: _jsx(DatePicker, { label: label, format: displayFormat, value: parseDate(field.value), onChange: (date, context) => {
                                if (date == null && context?.validationError != null) {
                                    return;
                                }
                                const formatted = formatDate(date);
                                field.onChange(formatted);
                                onChange && onChange(attr, formatted);
                            }, onAccept: () => {
                                // Trigger onBlur logic after date is selected from calendar
                                if (onBlur && inputElementRef.current) {
                                    const syntheticEvent = {
                                        target: inputElementRef.current,
                                        currentTarget: inputElementRef.current,
                                    };
                                    onBlur(syntheticEvent);
                                }
                            }, disabled: disabled, minDate: minDate, maxDate: maxDate, slotProps: {
                                textField: {
                                    required,
                                    variant: 'filled',
                                    InputLabelProps: { shrink: true },
                                    inputRef: (element) => {
                                        inputElementRef.current = element;
                                        // Also call the original inputRef if provided
                                        if (inputRef) {
                                            if (typeof inputRef === 'function') {
                                                inputRef(element);
                                            }
                                            else if ('current' in inputRef) {
                                                inputRef.current = element;
                                            }
                                        }
                                    },
                                    fullWidth: true,
                                    placeholder: placeholder || displayFormat,
                                    onFocus: (e) => {
                                        onFocus && onFocus(e);
                                    },
                                    onBlur: (e) => {
                                        onBlur && onBlur(e);
                                    },
                                    onKeyDown,
                                    error: !!hasError(),
                                    sx: {
                                        height,
                                    },
                                },
                            } }) }), title && !hasError() && _jsx("div", { className: "helper", children: title }), hasError() && (_jsx("div", { className: "helper error", children: String(createdForm.formState.errors[attr]?.message) }))] })) }) }));
}
