import { __ } from "@wordpress/i18n";

import {
	useBlockProps,
	InspectorControls,
	MediaUpload,
	MediaUploadCheck,
	RichText,
} from "@wordpress/block-editor";

import {
	PanelBody,
	Button,
	TextControl,
	Card,
	CardBody,
	CardHeader,
	IconButton,
} from "@wordpress/components";

import { useState } from "@wordpress/element";

import "./editor.scss";

export default function Edit({ attributes, setAttributes }) {
	const { entries } = attributes;
	const [selectedYear, setSelectedYear] = useState(null);

	const addEntry = () => {
		const newEntries = [
			...entries,
			{
				year: new Date().getFullYear().toString(),
				title: "",
				description: "",
				imageUrl: "",
				imageId: 0,
			},
		];
		setAttributes({ entries: newEntries });
	};

	const updateEntry = (index, field, value) => {
		const newEntries = [...entries];
		newEntries[index] = {
			...newEntries[index],
			[field]: value,
		};
		setAttributes({ entries: newEntries });
	};

	const removeEntry = (index) => {
		const newEntries = entries.filter((_, i) => i !== index);
		setAttributes({ entries: newEntries });
	};

	const sortedEntries = [...entries].sort(
		(a, b) => parseInt(a.year) - parseInt(b.year)
	);

	const years = [...new Set(sortedEntries.map((entry) => entry.year))];

	return (
		<>
			<InspectorControls>
				<PanelBody title={__("Timeline Entries", "company-timeline")}>
					<Button
						variant="primary"
						onClick={addEntry}
						style={{ marginBottom: "16px" }}
					>
						{__("Add Timeline Entry", "company-timeline")}
					</Button>

					{sortedEntries.map((entry, index) => {
						const originalIndex = entries.findIndex(
							(e) =>
								e.year === entry.year &&
								e.title === entry.title &&
								e.description === entry.description
						);

						return (
							<Card key={index} style={{ marginBottom: "12px" }}>
								<CardHeader>
									<strong>
										{entry.year || __("New Entry", "company-timeline")}
									</strong>
								</CardHeader>
								<CardBody>
									<TextControl
										label={__("Year", "company-timeline")}
										value={entry.year}
										onChange={(value) =>
											updateEntry(originalIndex, "year", value)
										}
										type="number"
									/>
									<Button
										isDestructive
										onClick={() => removeEntry(originalIndex)}
										style={{ marginTop: "8px" }}
									>
										{__("Remove Entry", "company-timeline")}
									</Button>
								</CardBody>
							</Card>
						);
					})}
				</PanelBody>
			</InspectorControls>

			<div {...useBlockProps()}>
				<div className="wp-block-telex-company-timeline">
					<div className="timeline-sidebar">
						<div className="timeline-years">
							<h3>{__("Timeline", "company-timeline")}</h3>
							{years.map((year) => (
								<button
									key={year}
									className={`year-link ${
										selectedYear === year ? "active" : ""
									}`}
									onClick={() => setSelectedYear(year)}
								>
									{year}
								</button>
							))}
						</div>
					</div>

					<div className="timeline-content">
						{sortedEntries.map((entry, index) => {
							const originalIndex = entries.findIndex(
								(e) =>
									e.year === entry.year &&
									e.title === entry.title &&
									e.description === entry.description
							);

							return (
								<div
									key={index}
									className="timeline-entry"
									data-year={entry.year}
								>
									<div className="timeline-year-marker">
										<h2>{entry.year}</h2>
									</div>

									<div className="timeline-entry-content">
										<RichText
											tagName="h3"
											value={entry.title}
											onChange={(value) =>
												updateEntry(originalIndex, "title", value)
											}
											placeholder={__(
												"Enter milestone title...",
												"company-timeline"
											)}
											className="timeline-title"
										/>

										<RichText
											tagName="p"
											value={entry.description}
											onChange={(value) =>
												updateEntry(originalIndex, "description", value)
											}
											placeholder={__(
												"Enter milestone description...",
												"company-timeline"
											)}
											className="timeline-description"
										/>

										<MediaUploadCheck>
											<MediaUpload
												onSelect={(media) => {
													updateEntry(originalIndex, "imageUrl", media.url);
													updateEntry(originalIndex, "imageId", media.id);
												}}
												allowedTypes={["image"]}
												value={entry.imageId}
												render={({ open }) => (
													<div className="timeline-media">
														{entry.imageUrl ? (
															<>
																<img src={entry.imageUrl} alt={entry.title} />
																<Button
																	isDestructive
																	onClick={() => {
																		updateEntry(originalIndex, "imageUrl", "");
																		updateEntry(originalIndex, "imageId", 0);
																	}}
																>
																	{__("Remove Image", "company-timeline")}
																</Button>
															</>
														) : (
															<Button onClick={open} variant="secondary">
																{__("Add Image", "company-timeline")}
															</Button>
														)}
													</div>
												)}
											/>
										</MediaUploadCheck>
									</div>
								</div>
							);
						})}
					</div>
				</div>
			</div>
		</>
	);
}
