import { useEffect, useState } from "react";
import DatePicker, { registerLocale } from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

import { Button, FloatingMenu, Icon } from "@ax/components";
import { dateToString, stringToDate } from "@ax/helpers";
import type { IQueryValue } from "@ax/types";

import en from "date-fns/locale/en-GB";

import * as S from "./style";

const ContentFilter = (props: IContentFilterProps): JSX.Element => {
	const { filterItems, value } = props;

	const initialState = value?.length ? value[0].label.split("-") : null;
	const startInitial = initialState ? stringToDate(initialState[0]) : null;
	const endInitial = initialState ? stringToDate(initialState[1]) : null;

	registerLocale("en", en);

	const [startDate, setStartDate] = useState<Date | null>(startInitial);
	const [endDate, setEndDate] = useState<Date | null>(endInitial);

	useEffect(() => {
		if (!value.length) {
			setStartDate(null);
			setEndDate(null);
		}
	}, [value]);

	const handleChange = (dates: [Date | null, Date | null]) => {
		const [start, end] = dates;
		setStartDate(start);
		setEndDate(end);
	};

	const handleClick = () => {
		if (startDate) {
			const startString = dateToString(startDate, "yyyy/MM/dd");
			const startHuman = dateToString(startDate, "MMM d yyyy");
			const endString = endDate ? dateToString(endDate, "yyyy/MM/dd") : startString;
			const endHuman = endDate ? dateToString(endDate, "MMM d yyyy") : startHuman;
			const selectedDate = `${startString}-${endString}`;
			const label = startHuman !== endHuman ? `${startHuman} - ${endHuman}` : startHuman;
			filterItems("date", [{ label, value: selectedDate }]);
		}
	};

	const isActive = false;

	const Header = () => (
		<S.StyledHeader isActive={isActive}>
			Date
			<S.IconsWrapper>
				{isActive ? <Icon name="Filter" size="16" /> : <Icon name="DownArrow" size="16" />}
			</S.IconsWrapper>
		</S.StyledHeader>
	);

	return (
		<FloatingMenu Button={Header} position="left" closeOnSelect={false}>
			<S.DatePickerWrapper data-testid="dateWrapper">
				<DatePicker
					locale={"en"}
					selected={startDate}
					onChange={handleChange}
					startDate={startDate}
					endDate={endDate}
					maxDate={new Date()}
					selectsRange
					inline
					disabledKeyboardNavigation
				/>
			</S.DatePickerWrapper>
			{!!startDate && (
				<S.ButtonWrapper>
					<Button type="button" onClick={handleClick} buttonStyle="minimal" data-close-menu>
						Apply
					</Button>
				</S.ButtonWrapper>
			)}
		</FloatingMenu>
	);
};

export interface IContentFilterProps {
	filterItems(pointer: string, filter: IQueryValue[]): void;
	value: IQueryValue[];
}

export default ContentFilter;
