'use client'

import { fetchTariffs } from '@/app/actions/action';
import { useQuery } from '@tanstack/react-query';
import { convertBytes } from '@/app/lib/convertBytes';
import { useTranslations } from 'next-intl';
import { yooKasaCreatePayment } from '@/app/actions/yooKassa';
import { useState, ReactNode } from 'react';
import ModalWindow from '@/app/components/ModalWindow';

export default function PaymentTabTariffs() {
	const t = useTranslations('Global');
	const {
		data: userData,
		isLoading,
		isError,
		error
	} = useQuery({
		queryKey: ['tariffData'],
		queryFn: () => {
			return fetchTariffs();
		}
	});

	const [openWindow, setOpenWindow] = useState<boolean>(false);
	const [selectedTariff, setSelectedTariff] = useState<{
		value: number;
		tariff: string;
		tokens: number;
	} | null>(null);
	const [isProcessing, setIsProcessing] = useState<boolean>(false);

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

		setIsProcessing(true);

		try {
			const response = await yooKasaCreatePayment(value, tariff);
			console.log(response);
			if (response) {
				window.open(response, '_blank', 'noopener,noreferrer');
			}
		} catch (error) {
			console.error('Payment error:', error);
		} finally {
			setIsProcessing(false);
		}
	}

	function openPaymentWindow(value: number, tariff: string, tokens: number) {
		setSelectedTariff({ value, tariff, tokens });
		setIsProcessing(false);
		setOpenWindow(true);
	}

	function closeModal() {
		setOpenWindow(false);
		setSelectedTariff(null);
		setIsProcessing(false);
	}

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

		const handleConfirm = () => {
			createPayment(selectedTariff.value, selectedTariff.tariff);
		};

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

		return (
			<div className="modal-window-confirm-payment">
				<h3 className="modal-window-confirm-payment-title">
					Подтверждение оплаты
				</h3>
				<h4 className="modal-window-confirm-payment-tariff">
					Подписка: {selectedTariff.tariff}
				</h4>
				<div className="modal-window-confirm-payment-description">
					Месячная подписка будет автоматически продлеваться
					<br />
					<strong>Включено {selectedTariff.tokens} токенов!</strong>
				</div>

				<div className="modal-window-confirm-payment-price">
					<div>{selectedTariff.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>
			</div>
		);
	}

	return (
		<>
			<ModalWindow state={openWindow} callBack={setOpenWindow}>
				<PaymentConfirmationModal />
			</ModalWindow>

			<div className="tab-content">
				<div className="billing-toggle" style={{ display: 'none' }}>
					<div>
						<button className="billing-btn active">💳 Помесячно</button>
						<button className="billing-btn">
							🔥 Годовая
							<span>ВЫГОДНО</span>
						</button>
					</div>
				</div>
				<div className="subscription-grid">
					{userData?.map((item: {
						id: number;
						name: string;
						price: number;
						tokens: number;
						maxFilesCount: number;
						diskSize: number;
					}) => (
						<div className="plan-card animate-card" key={item.id}>
							<div className="plan-header">
								<div className="plan-icon">🚀</div>
								<h3 className="plan-name">
									{t.has(item.name) ? t(item.name) : item.name}
								</h3>
								<div className="plan-price">{item.price}</div>
								<div className="plan-period">в месяц</div>
								<div className="plan-tokens">{item.tokens} токенов включено</div>
							</div>
							<ul className="plan-features">
								<li className="plan-feature">
									<span className="feature-icon">✓</span>
									{item.maxFilesCount} файлов в месяц
								</li>
								<li className="plan-feature">
									<span className="feature-icon">✓</span>
									{item.diskSize ? convertBytes(item.diskSize) : 0} хранилища
								</li>
								<li className="plan-feature">
									<span className="feature-icon">✓</span>
									Базовые модули защиты
								</li>
								<li className="plan-feature">
									<span className="feature-icon">✓</span>
									Поддержка 24/7
								</li>
								<li className="plan-feature">
									<span className="feature-icon not">✗</span>
									API доступ
								</li>
							</ul>
							<div className="flex justify-center">
								<button
									className="btn btn-primary"
									onClick={() => openPaymentWindow(item.price, item.name, item.tokens)}
								>
									Выбрать план
								</button>
							</div>
						</div>
					))}
				</div>
			</div>
		</>
	);
}