import syncingImg from "../../../assets/syncing.svg";

const SyncingBanner = ({ options, syncData }) => {

	// Check which content types are enabled
	const isProjectsEnabled = options["general-settings"]["project-show"] === "yes";
	const isEmployeesEnabled = options["general-settings"]["employee-show"] === "yes";
	const isTextAssetsEnabled = options["general-settings"]["text-assets-show"] === "yes";

	// Get current sync context
	const currentContext = syncData?.current_sync_context;
	const currentType = currentContext?.type;
	const currentName = currentContext?.name;

	    // Check if current type is actually enabled
    const isCurrentTypeEnabled = (
        (currentType === 'projects' && isProjectsEnabled) ||
        (currentType === 'employees' && isEmployeesEnabled) ||
        (currentType === 'text_assets' && isTextAssetsEnabled) ||
        (currentType === 'maintenance') || // Maintenance sync is always "enabled"
        (currentType === 'none') || // "None" type is always "enabled" (represents no changes needed)
        (currentType === 'preparing') // "Preparing" type is always "enabled"
    );

	// Generate context-aware status text
	let mainText = "Syncing with OpenAsset...";
	let detailText = "";

	// Debug logging for all context changes
	console.log('🎯 SyncingBanner context update:', {
		currentType,
		currentName,
		isCurrentTypeEnabled,
		syncContext: syncData?.current_sync_context,
		totals: syncData?.totals,
		timestamp: syncData?.current_sync_context?.timestamp,
		isInitiating: syncData?.is_initiating
	});
	
	// Additional debug for maintenance sync detection
	if (currentType === 'maintenance') {
		console.log('🧹 SyncingBanner: MAINTENANCE type detected!', {
			currentType,
			currentName,
			isCurrentTypeEnabled,
			syncContext: syncData?.current_sync_context,
			totals: syncData?.totals
		});
	}

	    if (syncData?.is_initiating) {
        // Check if this is a manual full sync
        const isManualFullSync = syncData?.current_sync_context?.is_manual_full_sync;
        if (isManualFullSync) {
            mainText = "Preparing full sync... Processing all data...";
        } else {
            mainText = "Preparing sync... Analyzing what needs updating...";
        }
    } else if (currentType === 'preparing') {
		// Handle preparing context
		const isManualFullSync = syncData?.current_sync_context?.is_manual_full_sync;
		mainText = currentName || "Preparing sync";
		if (isManualFullSync) {
			detailText = "Preparing to sync all data regardless of timestamps...";
		} else {
			detailText = "Initializing sync process...";
		}
    } else if (currentType === 'maintenance') {
		// Handle special maintenance sync context FIRST (before other checks)
		console.log('🧹 SyncingBanner: MAINTENANCE sync detected!', {
			currentType,
			currentName,
			syncContext: syncData?.current_sync_context
		});
		mainText = currentName || "Periodic maintenance sync";
		const currentDetail = syncData?.current_sync_context?.detail;
		if (currentDetail) {
			detailText = currentDetail;
		} else {
			detailText = "Checking for orphaned content and ensuring data integrity";
		}
    } else if (currentType === 'none') { // Explicitly handle 'none' context from backend
        mainText = "No changes needed";
        const totalItemsAvailable = (syncData?.total_available?.projects || 0) + 
                                    (syncData?.total_available?.employees || 0) + 
                                    (syncData?.total_available?.text_assets || 0);
        if (totalItemsAvailable > 0) {
            detailText = `${totalItemsAvailable} items checked, all current`;
        } else {
            detailText = `No items to check`;
        }
    } else if (currentType && isCurrentTypeEnabled && syncData?.totals?.[currentType] > 0) {
		// Show current content type being processed (only if enabled)
		const currentProgress = syncData?.progress?.[currentType] ?? 0;
		const currentTotal = syncData?.totals?.[currentType] ?? 0;
		const currentTotalAvailable = syncData?.total_available?.[currentType] ?? 0;
		
		if (currentTotal > 0) {
			const percentage = Math.round((currentProgress / currentTotal) * 100);
			
			// Use friendly names from options where available
			let displayName = currentName;
			if (currentType === 'projects') {
				displayName = options["general-settings"]["project-name-plural"] || "Projects";
			} else if (currentType === 'employees') {
				displayName = options["general-settings"]["employee-name-plural"] || "Employees";
			} else if (currentType === 'text_assets') {
				displayName = options["general-settings"]["text-assets-name-plural"] || "Text Assets";
			}
			
			mainText = `Processing ${currentProgress} of ${currentTotal} updated ${displayName}`;
			
			if (currentTotalAvailable > currentTotal) {
				detailText = `(${currentTotalAvailable} total available)`;
			}
			
			// Add percentage if in progress
			if (currentProgress > 0 && currentProgress < currentTotal) {
				mainText += ` (${percentage}%)`;
			}
		        }
    } else if (!syncData?.is_initiating && currentType && syncData?.totals?.[currentType] === 0) {
		// Handle case where current type has 0 items to sync - this shouldn't happen if backend logic is correct
		// But if it does, show a clear "no changes needed" message instead of confusing "Processing 0 of 0"
		const currentTotalAvailable = syncData?.total_available?.[currentType] ?? 0;
		
		if (currentTotalAvailable > 0) {
			mainText = `No changes needed`;
			detailText = `${currentTotalAvailable} items checked, all current`;
		} else {
			mainText = `No changes needed`;
			detailText = `No items to check`;
		}
    } else if (!syncData?.is_initiating) {
        // Fallback for when no specific context or disabled types
        const enabledTypes = [];
        if (isProjectsEnabled && syncData?.totals?.projects > 0) enabledTypes.push('projects');
        if (isEmployeesEnabled && syncData?.totals?.employees > 0) enabledTypes.push('employees');
        if (isTextAssetsEnabled && syncData?.totals?.text_assets > 0) enabledTypes.push('text_assets');
        
        // Also include any enabled type that's currently being processed (even with 0 totals)
        if (currentType && isCurrentTypeEnabled && !enabledTypes.includes(currentType)) {
            enabledTypes.push(currentType);
        }
        
        if (enabledTypes.length === 0) {
            mainText = "No changes needed";
        } else {
            mainText = "Processing updates...";
        }
    }

	// Determine if we should show spinning or success icon
	const isActivelyProcessing = syncData?.is_initiating || 
		currentType === 'preparing' ||
		currentType === 'maintenance' ||
		(syncData?.totals && Object.values(syncData.totals).some(count => count > 0));

	return (
		<div
			className='bg-sky-100 border border-sky-400 text-sky-700 px-4 py-3 rounded-lg fixed bottom-4 left-4 right-4 md:left-auto md:right-4 md:max-w-2xl flex items-center gap-4 shadow-lg z-50'
			role='alert'
		>
			{isActivelyProcessing ? (
				<img
					src={syncingImg}
					alt='Syncing Status'
					className='w-6 h-6 animate-spin flex-shrink-0'
				/>
			) : (
				<svg className="w-6 h-6 flex-shrink-0 text-green-600" fill="currentColor" viewBox="0 0 20 20">
					<path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
				</svg>
			)}
			
			<div className="flex-grow">
				<div className="font-medium">{mainText}</div>
				
				{/* Show detail text if available */}
				{detailText && (
					<div className="text-sm opacity-80 mt-1">{detailText}</div>
				)}
				
				{/* Progress bar for current content type */}
				{!syncData?.is_initiating && currentType && syncData?.totals?.[currentType] > 0 && (
					<div className="w-full bg-sky-200 rounded-full h-2 mt-2">
						<div 
							className="bg-sky-600 h-2 rounded-full transition-all duration-300 ease-out"
							style={{ 
								width: `${syncData?.totals?.[currentType] > 0 ? 
									((syncData?.progress?.[currentType] ?? 0) / syncData.totals[currentType]) * 100 : 0}%` 
							}}
						></div>
					</div>
				)}
			</div>
		</div>
	);
};

export default SyncingBanner;
