import { memo, useEffect, useState } from "react";
import { connect } from "react-redux";

import { Button, FieldsBehavior, IconAction } from "@ax/components";
import { galleryActions } from "@ax/containers/Gallery";
import { formatBytes, getFileExtension, getFormattedDateWithTimezone } from "@ax/helpers";
import { LOCALE } from "@ax/locales";
import type { IGetFolderParams, IImage, IRootState } from "@ax/types";

import * as S from "./style";

const GalleryDetailPanel = (props: IProps) => {
	const { selectedImage, isSaving, isAllowedToEdit, setImage, updateImage, getParams } = props;
	const { title, alt, tags, size, thumb, published, name, width, height } = selectedImage || {};

	const initState: IFormState = { title: title || "", alt: alt || "", tags: tags || [] };
	const [form, setForm] = useState(initState);

	// biome-ignore lint/correctness/useExhaustiveDependencies: TODO: fix this
	useEffect(() => {
		setForm(initState);
	}, [selectedImage]);

	const updateFormField = (field: string, value: string) => setForm((state) => ({ ...state, [field]: value }));

	const handleTitle = (newValue: string) => updateFormField("title", newValue);

	const handleAlt = (newValue: string) => updateFormField("alt", newValue);

	const handleTags = (newValue: string) => updateFormField("tags", newValue);

	const handleSave = async () => {
		const params = getParams();
		selectedImage && (await updateImage(selectedImage.id, form, params));
	};

	const handleSaveAndAdd = async () => {
		const params = getParams();
		selectedImage && (await updateImage(selectedImage.id, form, params));
		setImage(form);
	};

	const handleAdd = () => setImage(form);

	const handleOpenUrl = () => {
		if (selectedImage) {
			const win = window.open(selectedImage.url, "_blank");
			if (win) {
				win.focus();
			}
		}
	};

	const handleCopyUrl = () => selectedImage && navigator.clipboard.writeText(selectedImage.url);

	return (
		<S.DetailPanelWrapper>
			<S.PanelForm>
				<S.InfoWrapper>
					<S.Header>
						<S.ImageWrapper>
							<img src={thumb} alt={alt} />
						</S.ImageWrapper>
						<div>
							<S.ButtonsWrapper>
								<Button type="button" onClick={handleCopyUrl} buttonStyle="line">
									Copy URL
								</Button>
								<IconAction icon="OpenOutside" size="m" onClick={handleOpenUrl} />
							</S.ButtonsWrapper>
						</div>
					</S.Header>
					<S.Name>{name}</S.Name>
					<S.InfoRow>
						<strong>Uploaded:</strong> {published && getFormattedDateWithTimezone(published, "d MMM Y")}
					</S.InfoRow>
					<S.InfoRow>
						<strong>Type:</strong> {name && getFileExtension(name)}
					</S.InfoRow>
					<S.InfoRow>
						<strong>Size:</strong> {size && formatBytes(size)}
					</S.InfoRow>
					<S.InfoRow>
						<strong>Resolution:</strong> {`${width}x${height}px`}
					</S.InfoRow>
				</S.InfoWrapper>
				<S.FormWrapper>
					{isAllowedToEdit ? (
						<>
							<FieldsBehavior
								title="Title"
								name="title"
								value={form.title}
								fieldType="TextField"
								onChange={handleTitle}
							/>
							<FieldsBehavior
								title="Alternative text"
								name="alt"
								value={form.alt}
								fieldType="TextField"
								onChange={handleAlt}
							/>
						</>
					) : (
						<>
							<S.Label>Title</S.Label>
							<S.FieldText>{form.title}</S.FieldText>
							<S.Label>Alternative text</S.Label>
							<S.FieldText>{form.alt}</S.FieldText>
						</>
					)}
					<FieldsBehavior
						title="Tags"
						value={form.tags}
						fieldType="TagsField"
						onChange={handleTags}
						disabled={!isAllowedToEdit}
						helptext={LOCALE.fields.tags.helptext}
					/>
				</S.FormWrapper>
			</S.PanelForm>
			<S.PanelActions>
				{isAllowedToEdit ? (
					<>
						<Button type="button" buttonStyle="line" onClick={handleSave} disabled={isSaving}>
							{isSaving ? `Saving` : `Save`}
						</Button>
						<Button type="button" onClick={handleSaveAndAdd} disabled={isSaving}>
							{isSaving ? `Saving` : `Save & Add`}
						</Button>
					</>
				) : (
					<Button type="button" onClick={handleAdd}>
						Add image
					</Button>
				)}
			</S.PanelActions>
		</S.DetailPanelWrapper>
	);
};

export interface IDetailPanelProps {
	setImage: (fileData: any) => void;
	selectedImage: IImage | null;
	isSaving: boolean;
	isAllowedToEdit: boolean;
	getParams(): IGetFolderParams;
}

interface IFormState {
	alt: string;
	title: string;
	tags: string[];
}

const mapStateToProps = (state: IRootState) => ({
	isSaving: state.app.isSaving,
});

export interface IDispatchProps {
	updateImage(imageID: number, imageData: IFormState, params: IGetFolderParams): Promise<boolean>;
}

const mapDispatchToProps = {
	updateImage: galleryActions.updateImage,
};

type IProps = IDetailPanelProps & IDispatchProps;

export default connect(mapStateToProps, mapDispatchToProps)(memo(GalleryDetailPanel));
