import { useState, useEffect, useRef, type FC } from 'react';
import DatePicker from 'react-multi-date-picker';
import persian from 'react-date-object/calendars/persian';
import persian_fa from 'react-date-object/locales/persian_fa';
import DateObject from 'react-date-object';
import { clx } from '../helpers/utils';
import { Calendar } from 'iconsax-react';
import Error from './Error';

type Props = {
    onChange: (date: string) => void;
    defaulValue?: string;
    error_text?: string;
    placeholder: string;
    reset?: boolean;
    isDateTime?: boolean;
    className?: string;
    label?: string
};

const DatePickerComponent: FC<Props> = (props: Props) => {
    const [value, setValue] = useState<DateObject | null>(null);
    const isSettingDefaultValue = useRef(false);
    const isInitialized = useRef(false);

    useEffect(() => {
        if (props.reset) {
            setValue(null);
        }
    }, [props.reset]);

    useEffect(() => {
        // فقط وقتی کاربر تاریخ رو تغییر داده onChange رو صدا بزن
        if (isSettingDefaultValue.current) {
            isSettingDefaultValue.current = false;
            return;
        }

        // اگر هنوز initialize نشده و value null هست، onChange رو صدا نزن
        if (!isInitialized.current && !value) {
            return;
        }

        isInitialized.current = true;

        if (value) {
            // تبدیل تاریخ شمسی به میلادی
            const gregorianDate = value.toDate();
            const year = gregorianDate.getFullYear();
            const month = String(gregorianDate.getMonth() + 1).padStart(2, '0');
            const day = String(gregorianDate.getDate()).padStart(2, '0');
            const formattedDate = `${year}-${month}-${day}`;
            props.onChange(formattedDate);
        } else {
            props.onChange('');
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [value]);

    useEffect(() => {
        if (props.defaulValue) {
            try {
                const defaultDate = new DateObject({
                    date: props.defaulValue,
                    calendar: persian,
                    locale: persian_fa,
                });

                const currentValueStr = value ? `${value.year}-${value.month.number}-${value.day}` : null;
                const defaultValueStr = `${defaultDate.year}-${defaultDate.month.number}-${defaultDate.day}`;

                if (currentValueStr !== defaultValueStr) {
                    isSettingDefaultValue.current = true;
                    setValue(defaultDate);
                }
            } catch (error) {
                console.error('Error parsing date:', error);
            }
        } else if (!props.defaulValue && value) {
            isSettingDefaultValue.current = true;
            setValue(null);
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [props.defaulValue]);

    return (
        <div className="w-full">
            {props.label &&
                <div className='text-xs'>
                    {props.label}
                </div>}
            <div className={clx(props.label && 'mt-1.5')}>
                <div className="relative">
                    <DatePicker
                        placeholder={props.placeholder}
                        value={value}
                        onChange={(date) => setValue(date as DateObject)}
                        calendar={persian}
                        locale={persian_fa}
                        calendarPosition="bottom-right"
                        className={`rmdp-mobile ${props.className}`}
                    />
                    <Calendar size={18} color='black' className='pointer-events-none absolute top-0 bottom-0 left-2 my-auto' />
                </div>
                {props.error_text && props.error_text !== '' && (
                    <Error errorText={props.error_text} />
                )}
            </div>
        </div>
    );
};

export default DatePickerComponent;