import React, { useEffect, useRef, useState } from "react";
import { Button, message, Tooltip } from "antd";
import { DownloadOutlined, CopyOutlined, QrcodeOutlined } from "@ant-design/icons";
import { __ } from "@wordpress/i18n";
import * as QRCodeLib from "qrcode";

interface QRCodeProps {
	value: string; // The text/URL to encode in the QR code
	size?: number; // Size of the QR code (default: 200)
	disabled?: boolean; // Whether the QR code is disabled
	className?: string; // Additional CSS classes
}

const QRCode: React.FC<QRCodeProps> = ({
	value,
	size = 200,
	disabled = false,
	className = "",
}) => {
	const canvasRef = useRef<HTMLCanvasElement>(null);
	const [qrCodeDataURL, setQrCodeDataURL] = useState<string>("");

	// Generate QR code when value or size changes
	useEffect(() => {
		if (value && canvasRef.current && !disabled) {
			generateQRCode();
		}
	}, [value, size, disabled]);

	const generateQRCode = async () => {
		if (!canvasRef.current || !value) return;

		try {
			await QRCodeLib.toCanvas(canvasRef.current, value, {
				width: size,
				margin: 2,
				color: {
					dark: "#000000",
					light: "#ffffff",
				},
			});

			// Generate data URL for download/copy operations
			const dataURL = canvasRef.current.toDataURL("image/png");
			setQrCodeDataURL(dataURL);
		} catch (error) {
			console.error("Failed to generate QR code:", error);
			message.error(__("Failed to generate QR code", "swift-coupons-for-woocommerce"));
		}
	};

	const handleDownload = () => {
		if (!qrCodeDataURL) return;

		const link = document.createElement("a");
		link.download = `coupon-qr-code-${Date.now()}.png`;
		link.href = qrCodeDataURL;
		document.body.appendChild(link);
		link.click();
		document.body.removeChild(link);

		message.success(__("QR Code downloaded successfully!", "swift-coupons-for-woocommerce"));
	};

	const handleCopyImage = async () => {
		if (!qrCodeDataURL) return;

		try {
			// Convert data URL to blob
			const response = await fetch(qrCodeDataURL);
			const blob = await response.blob();

			// Copy to clipboard using the Clipboard API
			if (navigator.clipboard && window.ClipboardItem) {
				await navigator.clipboard.write([
					new ClipboardItem({
						[blob.type]: blob,
					}),
				]);
				message.success(__("QR Code copied to clipboard!", "swift-coupons-for-woocommerce"));
			} else {
				// Fallback: copy data URL as text
				await navigator.clipboard.writeText(qrCodeDataURL);
				message.success(__("QR Code data copied to clipboard!", "swift-coupons-for-woocommerce"));
			}
		} catch (error) {
			console.error("Failed to copy QR code:", error);
			message.error(__("Failed to copy QR code", "swift-coupons-for-woocommerce"));
		}
	};

	if (!value || disabled) {
		return (
			<div className={`tw-flex tw-flex-col tw-items-center tw-gap-2 tw-p-4 tw-border tw-border-dashed tw-border-gray-300 tw-rounded ${className}`}>
				<QrcodeOutlined className="tw-text-4xl tw-text-gray-400" />
				<span className="tw-text-sm tw-text-gray-500">
					{disabled
						? __("QR Code disabled", "swift-coupons-for-woocommerce")
						: __("No URL to generate QR code", "swift-coupons-for-woocommerce")
					}
				</span>
			</div>
		);
	}

	return (
		<div className={`tw-flex tw-flex-col tw-items-center tw-gap-3 ${className}`}>
			<div className="tw-border tw-border-gray-200 tw-rounded tw-p-2 tw-bg-white">
				<canvas
					ref={canvasRef}
					className="tw-block"
					style={{ opacity: disabled ? 0.5 : 1 }}
				/>
			</div>

			<div className="tw-flex tw-gap-2">
				<Tooltip title={__("Download QR Code as PNG", "swift-coupons-for-woocommerce")}>
					<Button
						type="default"
						icon={<DownloadOutlined />}
						onClick={handleDownload}
						disabled={!qrCodeDataURL || disabled}
						size="small"
					>
						{__("Download", "swift-coupons-for-woocommerce")}
					</Button>
				</Tooltip>

				<Tooltip title={__("Copy QR Code to Clipboard", "swift-coupons-for-woocommerce")}>
					<Button
						type="default"
						icon={<CopyOutlined />}
						onClick={handleCopyImage}
						disabled={!qrCodeDataURL || disabled}
						size="small"
					>
						{__("Copy", "swift-coupons-for-woocommerce")}
					</Button>
				</Tooltip>
			</div>
		</div>
	);
};

export default QRCode;