'use client'

import React, { useEffect, useState } from 'react';
import { DatePicker } from 'antd';
import { CalendarOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import 'dayjs/locale/ru';
import 'dayjs/locale/en';
import 'dayjs/locale/de';
import 'dayjs/locale/it';
import 'dayjs/locale/fr';
import 'dayjs/locale/es';
import { getLocale } from '../../utils/locale';

export const CustomDatePicker = (props: any) => {
    const { label, value, locale, ...other } = props;
    const [isActiveLabel, setIsActiveLabel] = useState<boolean>(false);

    dayjs.locale(locale);

    useEffect(() => {
        if (label) {
            setIsActiveLabel(!!value);
        } else {
            setIsActiveLabel(false);
        }
    }, [value]);

    const onOpenChange = (open: boolean) => {
        if (open) {
            if (!isActiveLabel) setIsActiveLabel(true)
        } else {
            setIsActiveLabel(!!value)
        }
    };

    return (
        <div className={`b-datepicker-wrap ${isActiveLabel ? 'b-datepicker__active' : ''}`}>
            <div className="b-datepicker-label">
                <span>{label}</span>
            </div>
            <DatePicker
                className="b-datepicker"
                format="YYYY-MM-DD"
                locale={getLocale(locale)}
                value={value}
                showNow={false}
                onOpenChange={onOpenChange}
                needConfirm={false}
                placeholder=""
                variant="filled"
                allowClear={false}
                popupClassName="b-datepicker-popup"
                minDate={dayjs().startOf('month')}
                suffixIcon={<CalendarOutlined style={{ color: '#2c7873', fontSize: 20 }} />}
                {...other}
            />
        </div>
    );
};
