'use client'

import { fetchTokensBundle } from '@/app/actions/action';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { convertBytes } from '@/app/lib/convertBytes';
import { useTranslations } from 'next-intl';
import { yooKasaCreatePayment } from '@/app/actions/yooKassa';
import { useState } from 'react';
import ModalWindow from '@/app/components/ModalWindow';
import YooMoneyWidget from '@/app/components/YooMoneyWidget';
import { YooMoneyCheckoutWidgetConfig, YooMoneyErrorCallbackResult } from 'types-yoomoneycheckoutwidget';

interface Tariff {
	id: number;
	type: string;
	name: string;
	price: number;
	tokens: number;
	maxFilesCount: number;
	diskSize: number;
	maxUsers: number;
}

export default function PaymentTubBuyTokens() {
	const t = useTranslations('Global');
	const {
		data: tokensPaymentData,
		isLoading,
		isError,
		error
	} = useQuery({
		queryKey: ['tokensPaymentData'],
		queryFn: () => {
			return fetchTokensBundle();
		},
		select: (data: Tariff[] | null): Tariff[] => {
			if (data) {
				return data.sort((a, b) => a.price - b.price);
			} else {
				return []
			}
		}
	});

	const [openWindow, setOpenWindow] = useState<boolean>(false);
	const [errorMessage, setErrorMessage] = useState<string | null>(null);
	const [selectedTokensBundle, setselectedTokensBundle] = useState<{
		value: number;
		tokensBundle: string;
		tokens: number;
		tokensBundleID: number
	} | null>(null);
	const [isProcessing, setIsProcessing] = useState<boolean>(false);
	const [showWidget, setShowWidget] = useState<boolean>(false);
	const [yooMoneyConfig, setYooMoneyConfig] = useState<YooMoneyCheckoutWidgetConfig | null>(null);
	const queryClient = useQueryClient();
	const [selectedTokenPackage, setSelectedTokenPackage] = useState<Tariff | null>(null);

	async function createPayment(value: number, tokensBundle: number) {
		if (isProcessing) return;

		setIsProcessing(true);
		setErrorMessage(null);

		try {
			const response = await yooKasaCreatePayment(value, tokensBundle, 'TOKEN');
			if (response) {
				setShowWidget(true)

				const config: YooMoneyCheckoutWidgetConfig = {
					confirmation_token: response,
					error_callback: (result: YooMoneyErrorCallbackResult) => {
						console.error('error_callback', result.error);
					},
					customization: {
						modal: true
					}
				}

				setYooMoneyConfig(config);
				closeModal(false);
			} else {
				setErrorMessage('payment-error');
			}
		} catch (error) {
			setErrorMessage('payment-error');
		} finally {
			setIsProcessing(false);
		}
	}

	function openPaymentWindow(value: number, tokensBundle: string, tokens: number, tokensBundleID: number) {
		setselectedTokensBundle({ value, tokensBundle, tokens, tokensBundleID });
		setIsProcessing(false);
		setOpenWindow(true);
	}

	function closeModal(isWindowOpen: boolean) {
		if (!isWindowOpen) {
			setOpenWindow(false);
			setselectedTokensBundle(null);
			setIsProcessing(false);
			setErrorMessage(null);
		}

	}

	function PaymentConfirmationModal() {
		if (!selectedTokensBundle) return null;

		const handleConfirm = () => {
			createPayment(selectedTokensBundle.value, selectedTokensBundle.tokensBundleID);
		};

		const handleCancel = () => {
			closeModal(false);
		};

		return (
			<div className="modal-window-confirm-payment">
				<h3 className="modal-window-confirm-payment-title">
					Подтверждение оплаты
				</h3>
				<h4 className="modal-window-confirm-payment-tariff">
					Купить: {selectedTokensBundle.tokens} токенов
				</h4>
				<div className="modal-window-confirm-payment-price">
					<div>{selectedTokensBundle.value}₽</div>
					<div></div>
				</div>

				<div className="flex justify-center gap-4">
					<button
						className="btn-primary btn-cancel"
						onClick={handleCancel}
						disabled={isProcessing}
					>
						{t('no')}
					</button>
					<button
						className={`btn-primary btn-confirm ${isProcessing ? 'btn-loading' : ''}`}
						onClick={handleConfirm}
						disabled={isProcessing}
					>
						{isProcessing ? 'Обработка...' : t('yes')}
					</button>
				</div>
				{
					errorMessage && (
						<div
							className="error-message"
						>
							<p
								className="error-message-text"
							>
								{t(errorMessage)}
							</p>
						</div>
					)
				}
			</div>
		);
	}

	const onComplete = () => {
		setYooMoneyConfig(null);
		setShowWidget(false);
		const timer = setTimeout(() => {
			queryClient.invalidateQueries({ queryKey: ['userData'] });
		}, 2000);

		return () => clearTimeout(timer);
	};
	const onModalClose = () => {
		setYooMoneyConfig(null);
		setShowWidget(false);
	}

	function selectHandler(item: Tariff) {
		console.log(item);
		setSelectedTokenPackage(item);
		console.log(selectedTokenPackage);
	}

	return (
		<>
			<ModalWindow state={openWindow} callBack={closeModal}>
				<PaymentConfirmationModal />
			</ModalWindow>
			<div className="tab-content block-wrapper">
				<div className="subscription-grid">
					{tokensPaymentData?.map((item: Tariff) => (
						<div
							className={`token-package ${selectedTokenPackage?.id === item.id ? 'selected' : ''}`}
							key={item.id}
							onClick={(() => {
								selectHandler(item);
							})}
						>
							<div
								className="token-package-amount"
							>
								{item.tokens ?? 0}
							</div>
							<div
								className="token-package-text"
							>
								{t('tokens')}
							</div>
							<div className="token-package-price">{item.price ?? 0} ₽</div>
							<div className="token-package-detail">
								~{Math.ceil((item.price / item.tokens) * 10) / 10 }₽ за токен
							</div>
						</div>
					))}
				</div>

				<div>
					<button
						className="plan-button btn-primary"
						onClick={() => {
							if (selectedTokenPackage) {
								openPaymentWindow(selectedTokenPackage.price, selectedTokenPackage.name, selectedTokenPackage.tokens, selectedTokenPackage.id)
							}
						}}
						disabled={selectedTokenPackage ? false : true}
					>
						{selectedTokenPackage ? `Купить за ${selectedTokenPackage.price}₽` : t('select-a-token-package')}
					</button>
					{selectedTokenPackage && (
						<div
							className="selected-token-info"
						>
							{t('package-selected-tokens-price', {
								tokens: selectedTokenPackage.tokens,
								price: selectedTokenPackage.price
							})}
						</div>
					)}
				</div>

			</div>

			{/* Модальное окно с виджетом */}
			{showWidget && yooMoneyConfig && (
				<YooMoneyWidget config={yooMoneyConfig} onComplete={onComplete} onModalClose={onModalClose} />
			)}
		</>

	)
}