import type React from "react";
import { forwardRef, useEffect, useState } from "react";

import { Icon, IconAction } from "@ax/components";
import { getRange, getStringifyDateRange, isValidDate, isValidDateRange, stringToDate } from "@ax/helpers";

import * as S from "./style";

const DatePickerInput = (props: IDatePickerProps, ref: React.ForwardedRef<HTMLDivElement>): JSX.Element => {
	const { dates, onClick, handleChange, isOpen, error, disabled, handleValidation, validators } = props;
	const { start, end } = dates;
	const placeholder = "dd/mm/yyyy";

	const currentDate = getStringifyDateRange(start, end);

	const [value, setValue] = useState(currentDate);

	useEffect(() => setValue(currentDate), [currentDate]);

	const handleOnChange = (e: React.ChangeEvent<HTMLInputElement>) => {
		const inputValue = e.target.value;
		setValue(inputValue);
		const range = getRange(inputValue);
		const isRange = range.length === 2;

		if (isRange && isValidDateRange(inputValue)) {
			const start = stringToDate(range[0]);
			const end = stringToDate(range[1]);
			handleChange([start, end]);
		} else {
			if (isValidDate(inputValue)) {
				const date = stringToDate(inputValue);
				handleChange([date, null]);
			} else if (!inputValue) {
				handleChange([null, null]);
			}
		}
	};

	const handleOnKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
		const allowed = /^[0-9/\- ]$/;
		const isControlKey = e.key.length > 1; // Backspace, Delete, ArrowLeft, Tab, etc.

		// Detecta si se está usando Ctrl (Windows) o Cmd (Mac) para permitir atajos
		const isKeyboardShortcut = e.ctrlKey || e.metaKey;

		if (!isControlKey && !isKeyboardShortcut && !allowed.test(e.key)) {
			e.preventDefault();
		}
	};

	const handleOnBlur = (e: React.FocusEvent<HTMLInputElement>) => {
		const inputValue = e.target.value;

		handleValidation?.(inputValue, validators);
	};

	const CalendarIcon = <IconAction icon="calendar" onClick={onClick} disabled={disabled} />;
	const CloseIcon = (
		<S.IconWrapper>
			<Icon name="close" size="16" />
		</S.IconWrapper>
	);

	return (
		<S.InputWrapper ref={ref} error={error}>
			<S.Input
				value={value || ""}
				placeholder={placeholder}
				onChange={handleOnChange}
				onKeyDown={handleOnKeyDown}
				onBlur={handleOnBlur}
				disabled={disabled}
			/>
			<S.ButtonWrapper>{isOpen ? CloseIcon : CalendarIcon}</S.ButtonWrapper>
		</S.InputWrapper>
	);
};

interface IDatePickerProps {
	dates: any;
	handleChange: (value: any) => void;
	onClick?: (e: any) => void;
	isOpen: boolean;
	error?: boolean;
	disabled?: boolean;
	handleValidation?: (value: string, validators?: Record<string, unknown>) => void;
	validators?: Record<string, unknown>;
}

export default forwardRef(DatePickerInput);
