'use client'

import { useQuery } from '@tanstack/react-query';
import { fetchReferralsLevels, fetchReferralUserStats } from '@/app/actions/referralsActions';
import { useEffect } from 'react';

export default function CommissionLevels() {
	const {
		data: referralsLevels,
		isLoading,
		isError,
		error
	} = useQuery({
		queryKey: ['referralsLevels'],
		queryFn: () => {
			return fetchReferralsLevels();
		},
		select: (data) => {
			if (data?.referrals) {
				return data?.referrals
			} else {
				return []
			}
		}
	});

	const {
		data: activeInvites,
		error: activeInvitesError
	} = useQuery({
		queryKey: ['referralUserStats'],
		queryFn: () => {
			return fetchReferralUserStats();
		},
		select: (data) => {
			if (data?.activeInvitee) {
				return data.activeInvitee
			} else {
				return 0
			};
		}
	});

	if (!referralsLevels?.length) {
		return null;
	}

	function getReferralIcon(referral: string) {
		switch (referral) {
			case 'bronze':
				return '🥉'
			case 'silver':
				return '🥈'
			case 'gold':
				return '🥇'
			case 'platinum':
				return '💎'
			default:
				return '🥉'
		}
	}

	function isActiveReferralLevel(activeInvites: number, maxInvites: number, minInvites: number) {
		if (activeInvites <= maxInvites && activeInvites >= minInvites) {
			return true
		} else {
			return false
		}
	}

	return (
		<div className="block-wrapper">
			<h3 className="section-title">
				<span className="icon"></span>
				Уровни комиссии
			</h3>
			<div className="commission-levels">
				{
					referralsLevels.map((item: {
						id: string,
						share: string,
						name: string,
						minInvitee: number,
						maxInvitee: number
					}) => {
						return (
							<div
								className={
									`level-card ${isActiveReferralLevel(activeInvites, item.maxInvitee, item.minInvitee) ? 'active' : ''}`
								}
								key={item.id}
							>
								<div className="level-number">
									{getReferralIcon(item.id)}
								</div>
								<div className="level-commission">{item.share}%</div>
								<div className="level-subscribe">{item.name}</div>
								<div className="level-requirement">{
									item.maxInvitee < 100 ? `${item.minInvitee}-${item.maxInvitee}` : `${item.minInvitee}+`
								} рефералов
								</div>
							</div>
						)
					})
				}
			</div>
		</div>
	)
}