import React from "react";
import { Box, Button, FileUploader, Flex, FlexItem, FormGroup } from "@bigcommerce/big-design";

const ACCEPTED_IMAGE_TYPES = "image/jpeg,image/png,image/gif,image/webp";
const ALLOWED_MIME_TYPES = ["image/jpeg", "image/jpg", "image/png", "image/gif", "image/webp"];
const MAX_FILE_SIZE_BYTES = 5 * 1024 * 1024;

type BannerImageUploadFieldProps = {
	label: string;
	file: File | null;
	previewUrl?: string;
	onFileChange: (file: File | null) => void;
	onRemotePreviewClear?: () => void;
	error?: string;
};

export default function BannerImageUploadField({
	label,
	file,
	previewUrl,
	onFileChange,
	onRemotePreviewClear,
	error,
}: BannerImageUploadFieldProps) {
	const showRemotePreview = !!previewUrl && !file;

	return (
		<FormGroup>
			{showRemotePreview ? (
				<Box marginBottom="small">
					<Flex alignItems="center" justifyContent="space-between">
						<FlexItem>
							<img
								src={previewUrl}
								alt={`${label} preview`}
								style={{ maxWidth: "100%", maxHeight: 120, borderRadius: 4 }}
							/>
						</FlexItem>
						{onRemotePreviewClear ? (
							<FlexItem>
								<Button variant="subtle" onClick={onRemotePreviewClear}>
									Remove
								</Button>
							</FlexItem>
						) : null}
					</Flex>
				</Box>
			) : null}
			<FileUploader
				accept={ACCEPTED_IMAGE_TYPES}
				description="Accepts JPG, PNG, GIF, WEBP up to 5 MB"
				dropzoneConfig={{
					label: "Drag and drop image here",
				}}
				error={error}
				files={file ? [file] : []}
				label={label}
				onFilesChange={(files) => onFileChange(files[0] ?? null)}
				validators={[
					{
						type: "file-type",
						validator: (uploadedFile: File) =>
							ALLOWED_MIME_TYPES.includes((uploadedFile.type || "").toLowerCase()),
					},
					{
						type: "file-size",
						validator: (uploadedFile: File) => uploadedFile.size <= MAX_FILE_SIZE_BYTES,
					},
				]}
			/>
		</FormGroup>
	);
}
