import { __ } from "@wordpress/i18n";
import "./editor.scss";
import getAdminLanguageFromCookies from "../../../utils/getAdminLanguageFromCookies.js";

import {
	useBlockProps,
	RichText,
	BlockControls,
	InspectorControls,
} from "@wordpress/block-editor";
import { DatePicker, PanelBody } from "@wordpress/components";

export default function Edit({ attributes, setAttributes }) {
	const { date } = attributes;

	function handleDateChange(newDate) {
		const options = {
			weekday: "long",
			year: "numeric",
			month: "long",
			day: "numeric",
		};

		const currentLang = getAdminLanguageFromCookies("wp-wpml_current_language");
		const currentLocale = currentLang === "nl" ? "nl-NL" : "fr-FR";

		const formattedTime = new Date(newDate).toLocaleDateString(
			currentLocale,
			options,
		);

		if (!formattedTime || !newDate) return;

		const date = {
			time: newDate,
			formattedTime: formattedTime,
		};

		setAttributes({ date });
	}
	const formattedDate = date && date.formattedTime ? date.formattedTime : "";
	const savedDate = date && date.time ? date.time : new Date().toString();

	return (
		<>
			<InspectorControls>
				<PanelBody title={__("Date", "multiblocks")}>
					<DatePicker currentDate={savedDate} onChange={handleDateChange} />
				</PanelBody>
			</InspectorControls>

			<time
				{...useBlockProps({
					className: `homegrade-blocks-date`,
				})}
				datetime={savedDate}
			>
				{formattedDate}
			</time>
		</>
	);
}
