import DatePicker, { registerLocale } from 'react-datepicker';
import { ko } from 'date-fns/esm/locale';
import { getMonth, getYear } from 'date-fns';
import range from 'lodash/range';
import { months } from '../../../assets/data';
registerLocale('ko', ko);

const DatePickerComponent = ({ selectedDate, handleSelectedDate, pastDate, disabled, name, readOnly, maxDate, type }) => {
	const years = range(1990, getYear(new Date()) + 100, 1);

	const parseDate = (date) => {
		if (!date) return null;

		try {
			// 이미 Date 객체인 경우
			if (date instanceof Date) {
				return date;
			}

			// 문자열인 경우
			if (typeof date === 'string') {
				// ISO 형식의 날짜 문자열인 경우 (예: "2025-01-03T15:00:00")
				if (date.includes('T')) {
					return new Date(date);
				}

				// 일반 날짜 문자열인 경우 (예: "2025-01-03")
				const [year, month, day] = date.split('-').map(num => num.trim());
				return new Date(year, month - 1, day);
			}

			return null;
		} catch (error) {
			console.error('Date parsing error:', error);
			return null;
		}
	};

	const parsedDate = parseDate(selectedDate);

	return (
		<DatePicker
			onKeyDown={event => {
				if (event.keyCode === 8) {
					event.preventDefault();
				}
			}}
			disabled={disabled}
			readOnly={readOnly}
			// selected={type !== 'retention' ? '' : parsedDate}
			selected={parsedDate}
			onChange={data => handleSelectedDate(data)}
			className="datepicker"
			placeholderText={name ? name : '검색기간 선택'}
			calendarClassName="calendar"
			dateFormat="yyyy - MM - dd"
			locale="ko"
			minDate={pastDate}
			maxDate={maxDate}
			renderCustomHeader={({ date, changeYear, changeMonth, decreaseMonth, increaseMonth, prevMonthButtonDisabled, nextMonthButtonDisabled }) => (
				<div className="calendar-top">
					<button
						className="btn-prev"
						onClick={e => {
							e.preventDefault();
							decreaseMonth();
						}}
						disabled={prevMonthButtonDisabled}></button>
					<select value={getYear(date)} onChange={({ target: { value } }) => changeYear(value)}>
						{years.map(option => (
							<option key={option} value={option}>
								{option}
							</option>
						))}
					</select>
					.
					<select value={months[getMonth(date)]} onChange={({ target: { value } }) => changeMonth(months.indexOf(value))}>
						{months.map(option => (
							<option key={option} value={option}>
								{option}
							</option>
						))}
					</select>
					<button
						className="btn-next"
						onClick={e => {
							e.preventDefault();
							increaseMonth();
						}}
						disabled={nextMonthButtonDisabled}></button>
				</div>
			)}
		/>
	);
};

export default DatePickerComponent;
