import { FileGallery, Icon, Modal, TextField } from "@ax/components";
import { VALID_DOCUMENT_FORMATS } from "@ax/constants";
import { formatBytes, getFormattedDateWithTimezone } from "@ax/helpers";
import { useModal } from "@ax/hooks";
import type { ISite } from "@ax/types";

import * as S from "./style";

const FileField = (props: IFileFieldProps): JSX.Element => {
	const { disabled, value, site, onChange, allowedFormats } = props;

	const { isOpen, toggleModal } = useModal(false);

	const hasCustomFormats = !!allowedFormats?.length;

	const handleClick = () => {
		if (!disabled) {
			toggleModal();
		}
	};

	const addFile = (newFile: any) => {
		onChange(newFile);
	};

	const handleOnClickUrl = () => {
		if (value?.url) {
			const win = window.open(value.url, "_blank");
			if (win) {
				win.focus();
			}
		}
	};

	const removeFile = () => {
		onChange(null);
	};

	const replaceFile = () => {
		toggleModal();
	};

	const menuOptions = [
		{
			label: "replace",
			icon: "change",
			action: replaceFile,
			disabled,
		},
		{
			label: "delete",
			icon: "delete",
			action: removeFile,
			disabled,
		},
	];

	const fileName = value?.url ? value.url.split("/").pop() : "File title";
	const fileDate = value?.uploadDate ? getFormattedDateWithTimezone(value.uploadDate, "d MMM Y") : "--";
	const fileSize = value?.sizeBytes ? formatBytes(value.sizeBytes) : "-- KB";

	return (
		<>
			<S.FileDataWrapper data-testid="file-data-wrapper">
				<S.FileName>{fileName}</S.FileName>
				<S.FileData>
					<div>Uploaded: {fileDate}</div>
					<div>{fileSize}</div>
				</S.FileData>
			</S.FileDataWrapper>
			{value?.url && (
				<S.TextFieldWrapper data-testid="text-field-wrapper">
					<TextField
						name="url"
						value={value.url}
						onChange={() => null}
						readonly={true}
						icon="openOutside"
						onClickIcon={handleOnClickUrl}
					/>
				</S.TextFieldWrapper>
			)}
			{!value && (
				<>
					<S.Field onClick={handleClick} data-testid="field-icon-wrapper" disabled={disabled}>
						<S.IconWrapper>
							<Icon name="File" size="24" />
						</S.IconWrapper>
					</S.Field>
					<S.HelpText>
						Valid formats:{" "}
						{hasCustomFormats ? allowedFormats.join(", ") : `${VALID_DOCUMENT_FORMATS.join(", ")} and videos`}. Max.
						size: 50MB
					</S.HelpText>
				</>
			)}
			{value && (
				<S.Component>
					<S.ComponentIconWrapper>
						<Icon name="File" />
					</S.ComponentIconWrapper>
					<S.Label>{fileName}</S.Label>
					<S.StyledActionMenu icon="more" options={menuOptions} tooltip="Actions" />
				</S.Component>
			)}
			<Modal isOpen={isOpen} hide={toggleModal} size="XL" title="Select file">
				{isOpen && (
					<FileGallery customFormats={allowedFormats} addFile={addFile} toggleModal={toggleModal} site={site} />
				)}
			</Modal>
		</>
	);
};

export interface IFileFieldProps {
	value: any;
	onChange: (value: any) => void;
	disabled?: boolean;
	site: ISite | null;
	allowedFormats?: string[];
}

export default FileField;
