import React, { useContext, useState, useMemo, useEffect } from 'react';
import { SettingsContext } from '../App/SettingsContext';
import ecreIcons from '../../components/core/icons';
import UserProfileCard from '../components/RewardManagement/UserProfileCard';
import ReferralHistory from '../components/RewardManagement/ReferralHistory';
import RewardCoupons from '../components/RewardManagement/RewardCoupons';
import RewardPoints from '../components/RewardManagement/RewardPoints';
import Avatar from '../../images/avatar.png'
import axios from 'axios';
import { translate } from '../../Helper';

const ReferrerDetails = () => {
    const { 
        activeReferrerTab, 
        handleActiveReferrerTab, 
        selectedReferrer,
        setSelectedReferrer,
        referrerDetailsSummary,
        setReferrerDetailsSummary,
        currency
    } = useContext(SettingsContext);

    // Calculate and set summary data
    const calculateSummary = (referrerData) => {
        const conversionRate = referrerData.conversion_rate || 
            (referrerData.total_referrals > 0 
                ? Math.round((referrerData.total_rewards_issued / referrerData.total_referrals) * 100)
                : 0);

        const summaryData = {
            conversion_rate: conversionRate,
            total_referral_sales: referrerData.total_sales || referrerData.salesGenerated || 0,
            total_referrals: referrerData.total_referrals || referrerData.referrals || 0,
            reward_issued: referrerData.total_rewards_issued || 0
        };
        
        setReferrerDetailsSummary(summaryData);
    };

    // Fetch fresh referrer data from server
    const fetchFreshReferrerData = async () => {
        if (!selectedReferrer || !selectedReferrer.user_id) return;

        try {
            const formData = new FormData();
            formData.append('action', 'ecre_fetch_referrer_dashboard');
            formData.append('nonce', ecreAdmin.nonce);
            formData.append('user_id', selectedReferrer.user_id);

            const response = await axios.post(ecreAdmin.ajaxurl, formData);

            if (response.data.success) {
                const freshData = response.data.data;
                setSelectedReferrer(freshData);
                calculateSummary(freshData);
            }
        } catch (error) {
            console.error('Error fetching referrer dashboard:', error);
            // Fallback: use existing data
            calculateSummary(selectedReferrer);
        }
    };

    // Fetch data on component mount
    useEffect(() => {
        fetchFreshReferrerData();
    }, []);

    // Fallback data if no referrer selected
    if (!selectedReferrer) {
        return <div className="ecre-p-8 ecre-text-center">{translate('loading_referrer_details')}</div>;
    }

    return (
        <div className="referrer-details-screen">
            <UserProfileCard
                name={selectedReferrer.name}
                email={selectedReferrer.email}
                avatar={selectedReferrer.avatar || Avatar}
                eligibilityStatus="Active"
                statusColor="green"
                className="ecre-mb-10"
            />
            <div className="referrer-details__summary ecre-mb-8 sm:ecre-mb-10">
                <div className="ecre-grid ecre-grid-cols-1 sm:ecre-grid-cols-2 ecre-gap-4">
                    <div className="summary-card ecre-p-4 ecre-bg-white ecre-rounded-lg ecre-inline-flex ecre-justify-start ecre-items-center ecre-gap-6">
                        <div className="icon-wrap">
                            {ecreIcons.checkBadge}
                        </div>
                        <div className="text-wrapper">
                            <div className="ecre-text-[#111827] ecre-text-sm ecre-font-medium">{translate('conversion_rate')}</div>
                            <div className="ecre-text-[#111827] ecre-text-xl ecre-font-medium">{referrerDetailsSummary.conversion_rate}%</div>
                        </div>
                    </div>
                    <div className="summary-card ecre-p-4 ecre-bg-white ecre-rounded-lg ecre-inline-flex ecre-justify-start ecre-items-center ecre-gap-6">
                        <div className="icon-wrap">
                            {ecreIcons.usdDollar}
                        </div>
                        <div className="text-wrapper">
                            <div className="ecre-text-[#111827] ecre-text-sm ecre-font-medium">{translate('total_referral_sales')}</div>
                            <div className="ecre-text-[#111827] ecre-text-xl ecre-font-medium">{currency}{referrerDetailsSummary.total_referral_sales}</div>
                        </div>
                    </div>
                    <div className="summary-card ecre-p-4 ecre-bg-white ecre-rounded-lg ecre-inline-flex ecre-justify-start ecre-items-center ecre-gap-6">
                        <div className="icon-wrap">
                            {ecreIcons.refferalsManagement}
                        </div>
                        <div className="text-wrapper">
                            <div className="ecre-text-[#111827] ecre-text-sm ecre-font-medium">{translate('total_referral_coupons')}</div>
                            <div className="ecre-text-[#111827] ecre-text-xl ecre-font-medium">{referrerDetailsSummary.total_referrals}</div>
                        </div>
                    </div>
                    <div className="summary-card ecre-p-4 ecre-bg-white ecre-rounded-lg ecre-inline-flex ecre-justify-start ecre-items-center ecre-gap-6">
                        <div className="icon-wrap">
                            {ecreIcons.rewardGift}
                        </div>
                        <div className="text-wrapper">
                            <div className="ecre-text-[#111827] ecre-text-sm ecre-font-medium">{translate('reward_issued')}</div>
                            <div className="ecre-text-[#111827] ecre-text-xl ecre-font-medium">{referrerDetailsSummary.reward_issued}</div>
                        </div>
                    </div>
                </div>
            </div>

            <div className="referrer-details__navbar ecre-mb-6">
                <ul className="referrer-details__navbar-menu ecre-flex ecre-flex-wrap md:ecre-flex-nowrap ecre-gap-4 sm:ecre-gap-6 ecre-pb-2.5 ecre-border-b ecre-border-gray-200">
                    <li className={`ecre-mb-0 ${activeReferrerTab === 'referral-history' ? 'active' : ''}`}>
                        <a onClick={() => handleActiveReferrerTab('referral-history')} className="ecre-cursor-pointer ecre-block ecre-text-center ecre-text-gray-900 ecre-text-xs before:ecre-hidden sm:before:ecre-block lg:ecre-text-sm ecre-font-normal ecre-p-2 sm:ecre-p-3.5 ecre-rounded sm:ecre-rounded-[15px] ecre-bg-gray-200 ecre-transition hover:ecre-bg-[#6A40D5] hover:ecre-text-white">{translate('referral_history')}</a>
                    </li>
                    <li className={`ecre-mb-0 ${activeReferrerTab === 'reward-coupons' ? 'active' : ''}`}>
                        <a onClick={() => handleActiveReferrerTab('reward-coupons')} className="ecre-cursor-pointer ecre-block ecre-text-center ecre-text-gray-900 ecre-text-xs before:ecre-hidden sm:before:ecre-block lg:ecre-text-sm ecre-font-normal ecre-p-2 sm:ecre-p-3.5 ecre-rounded sm:ecre-rounded-[15px] ecre-bg-gray-200 ecre-transition hover:ecre-bg-[#6A40D5] hover:ecre-text-white">{translate('reward_coupons')}</a>
                    </li>
                    <li className={`ecre-mb-0 ${activeReferrerTab === 'reward-points' ? 'active' : ''}`}>
                        <a onClick={() => handleActiveReferrerTab('reward-points')} className="ecre-cursor-pointer ecre-block ecre-text-center ecre-text-gray-900 ecre-text-xs before:ecre-hidden sm:before:ecre-block lg:ecre-text-sm ecre-font-normal ecre-p-2 sm:ecre-p-3.5 ecre-rounded sm:ecre-rounded-[15px] ecre-bg-gray-200 ecre-transition hover:ecre-bg-[#6A40D5] hover:ecre-text-white">{translate('reward_points')}</a>
                    </li>
                </ul>
            </div>

            <div className="referrer-details__tab-content">
                {activeReferrerTab === 'referral-history' ? <ReferralHistory/> : null}
                {activeReferrerTab === 'reward-coupons' ? <RewardCoupons/> : null}
                {activeReferrerTab === 'reward-points' ? <RewardPoints/> : null}
            </div>
        </div>
    );
}

export default ReferrerDetails;