import React from "react";
import { PaymentOptionItem } from "./components/PaymentOptionItem.tsx";
import { ChannelFromServer } from "./types/models/ChannelFromServer";
import { ChannelsFromServerFactory } from "./types/factories/ChannelsFromServerFactory";
import { ProviderFooter } from "./components/ProviderFooter";
import { getPaymentMethodData } from "@woocommerce/settings";

const data = getPaymentMethodData("simplyin", {});

interface RendererState {
	items: ChannelFromServer[];
	isLoading: boolean;
}

export class Renderer extends React.Component<{}, RendererState> {
	constructor(props: {}) {
		super(props);
		this.state = {
			items: [],
			isLoading: false,
		};
	}

	componentDidMount() {
		this.setupPaymentMethodsCallback();

		if ((window as any).SimplyIn?.getBlocksPaymentMethods) {
			this.triggerPaymentMethodsUpdate();
			return;
		}

		(window as any).SimplyInReadyCallback = () => {
			this.triggerPaymentMethodsUpdate();
		};
	}

	private setupPaymentMethodsCallback = () => {
		(window as any).SimplyinPaymentMethodsCallback =
			this.handlePaymentMethodsUpdate;
	};

	private handlePaymentMethodsUpdate = (paymentMethodsFromServer: any[]) => {
		try {
			const processedChannels =
				ChannelsFromServerFactory.createChannelsFromServer(
					paymentMethodsFromServer,
				);

			this.setState(
				{
					items: processedChannels.items as ChannelFromServer[],
					isLoading: false,
				},
				() => {
					if ((window as any).SimplyIn?.validatePhoneNumber) {
						(window as any).SimplyIn.validatePhoneNumber();
					}
				},
			);
		} catch (error) {
			this.setState({
				items: [],
				isLoading: false,
			});
		}
	};

	public triggerPaymentMethodsUpdate = () => {
		this.setState({ isLoading: true });

		if ((window as any).SimplyIn?.getBlocksPaymentMethods) {
			(window as any).SimplyIn.getBlocksPaymentMethods();
		} else {
			this.setState({ isLoading: false });
		}
	};

	render() {
		const { items } = this.state;

		if (!items || items.length === 0) {
			return null;
		}

		const paymentData = data as any;

		return (
			<>
				<ul className={"simplyin-block-payment"}>
					{items.map((channel: ChannelFromServer, index: number) => (
						<PaymentOptionItem
							key={channel.key}
							simplyinOptionId={channel.simplyinOptionId}
							id={channel.key}
							value={channel.value}
							name={channel.name}
							label={channel.label}
							icon={channel.icon}
							items={channel.items}
							description={channel.description}
							data={channel.data}
							hasParent={false}
						/>
					))}
				</ul>
				{paymentData?.payment_provider &&
					paymentData?.messages?.provider && (
						<ProviderFooter
							providerData={paymentData.payment_provider}
							messages={paymentData.messages}
						/>
					)}
			</>
		);
	}
}
