import React, {ChangeEvent} from "react";
import {BsUpload, BsDownload, BsTrash, BsArrowRepeat, BsXCircleFill} from "react-icons/bs";
import {FilesStorage} from "@/interfaces/storage.files";
import axios from "axios";

interface Asset {
	file: string | File;
	complete: boolean;
}

const PaymentAssetManager = (props: {
	asset: string | undefined;
	permissions: "read" | "write";
	type: FilesStorage;
	reload: () => void;
	paymentId: string;
}) => {
	const {asset, permissions, type, paymentId} = props;

	const fileInputRef = React.useRef<HTMLInputElement>(null);
	const fileInputReplaceRef = React.useRef<HTMLInputElement>(null);

	const [managingAsset, setManagingAsset] = React.useState<Asset>({
		file: asset || "",
		complete: asset ? true : false,
	});

	const {file, complete} = managingAsset;

	const deleteAsset = () => {
		if (confirm("Are you sure you want to delete this document?")) {
			axios
				.delete(`/api/payments/files/${type}/${paymentId}`)
				.then((response) => {
					if (response.status === 200) {
						console.log("File deleted successfully!");
						setManagingAsset({
							file: "",
							complete: false,
						});
						return;
					}

					console.error("File deletion failed");
				})
				.catch((error) => {
					console.error("Error occurred during file deletion:", error);
				})
				.finally(props.reload);
		}
	};

	const renderFileInput = (onChange: any, ref: React.RefObject<HTMLInputElement>) => (
		<input type="file" ref={ref} style={{display: "none"}} onChange={onChange} multiple={false} accept="application/pdf" />
	);

	const handleFileChange = async (e: Event, method: "post" | "patch") => {
		const newFile = (e.target as HTMLInputElement).files?.[0];
		if (newFile) {
			setManagingAsset({
				file: newFile,
				complete: false,
			});

			const formData = new FormData();
			formData.append("file", newFile);

			axios[method](`/api/payments/files/${type}/${paymentId}`, formData, {
				headers: {
					"Content-Type": "multipart/form-data",
				},
			})
				.then((response) => {
					if (response.status === 200) {
						console.log("File uploaded successfully!");
						console.log("Uploaded File URL:", response.data.ref);
						// Further actions upon successful upload
						setManagingAsset({
							file: response.data.ref,
							complete: true,
						});
						return;
					}

					console.error("File upload failed");
				})
				.catch((error) => {
					console.error("Error occurred during file upload:", error);
				})
				.finally(props.reload);
		}
	};

	const downloadAsset = () => {
		axios
			.get(`/api/payments/files/${type}/${paymentId}`)
			.then((response) => {
				if (response.status === 200) {
					console.log("Uploaded File URL:", response.data.url);
					const link = document.createElement("a");
					link.download = response.data.filename;
					link.href = response.data.url;
					link.click();
					return;
				}

				console.error("Failed to download file");
			})
			.catch((error) => {
				console.error("Error occurred during file upload:", error);
			});
	};

	if (permissions === "read") {
		if (file) return <BsDownload onClick={downloadAsset} />;
		return null;
	}

	if (file) {
		if (complete) {
			return (
				<>
					<BsDownload onClick={downloadAsset} />
					<BsArrowRepeat onClick={() => fileInputReplaceRef.current?.click()} />
					<BsTrash onClick={deleteAsset} />
					{renderFileInput((e: Event) => handleFileChange(e, "patch"), fileInputReplaceRef)}
					{renderFileInput((e: Event) => handleFileChange(e, "post"), fileInputRef)}
				</>
			);
		}

		return <span className="loading loading-infinity w-8" />;
	}

	return permissions === "write" ? (
		<>
			<BsUpload onClick={() => fileInputRef.current?.click()} />
			{renderFileInput((e: Event) => handleFileChange(e, "post"), fileInputRef)}
		</>
	) : (
		<BsXCircleFill />
	);
};

export default PaymentAssetManager;
