/**
 * Media AI Image Generation Component
 */
import { useState, useEffect, useRef } from 'react';
import jQuery from 'jquery';

const $ = jQuery;

const MediaGenerate = () => {
	const [description, setDescription] = useState('');
	const [statusMessage, setStatusMessage] = useState('');
	const [imagePreview, setImagePreview] = useState('');
	const [isGenerating, setIsGenerating] = useState(false);
	const [showAddButton, setShowAddButton] = useState(false);
	const [showTryAgain, setShowTryAgain] = useState(false);
	const pollingIntervalRef = useRef(null);
	const conversationIdRef = useRef(null);

	useEffect(() => {
		return () => {
			// Cleanup polling on unmount
			if (pollingIntervalRef.current) {
				clearInterval(pollingIntervalRef.current);
			}
		};
	}, []);

	const showStatus = (message, isError = false) => {
		setStatusMessage(message);
	};

	const startPolling = (conversationId) => {
		let pollCount = 0;
		const maxPolls = 60; // Poll for up to 5 minutes (60 * 5 seconds)

		pollingIntervalRef.current = setInterval(() => {
			pollCount++;

			if (pollCount > maxPolls) {
				clearInterval(pollingIntervalRef.current);
				pollingIntervalRef.current = null;
				showStatus('Image generation timed out. Please try again.', true);
				setIsGenerating(false);
				setShowTryAgain(true);
				return;
			}

			// Make AJAX request to check status
			$.ajax({
				url: window.samurAiAdmin.ajaxUrl,
				type: 'POST',
				data: {
					action: 'websamurai_poll_image',
					nonce: window.samurAiAdmin.nonce,
					conversation_id: conversationId
				},
				success: (response) => {
					if (response.success && response.data.conversation) {
						const conversation = response.data.conversation;

						// Check if DoneResponse is true
						if (conversation.DoneResponse === true || conversation.DoneResponse === 'true') {
							// Stop polling
							clearInterval(pollingIntervalRef.current);
							pollingIntervalRef.current = null;

							// Extract image URL from Prompt.prompts array
							let imageUrl = null;

							if (conversation.Prompt && conversation.Prompt.prompts && Array.isArray(conversation.Prompt.prompts)) {
								// Look for assistant role with content object containing image URL
								for (let i = 0; i < conversation.Prompt.prompts.length; i++) {
									const prompt = conversation.Prompt.prompts[i];
									if (prompt.role === 'assistant' && prompt.content && typeof prompt.content === 'object') {
										if (prompt.content.url) {
											// Found the relative URL, prepend the base URL
											const relativeUrl = prompt.content.url;
											imageUrl = window.samurAiAdmin.oauthBaseUrl + relativeUrl;
											break;
										}
									}
								}
							}

							if (imageUrl) {
								showStatus('Image generated successfully!');
								setImagePreview(imageUrl);
								setIsGenerating(false);
								setShowAddButton(true);
								setShowTryAgain(true);
							} else {
								showStatus('Image generation completed but no image URL was returned.', true);
								setIsGenerating(false);
								setShowTryAgain(true);
							}
						} else {
							// Update status message
							showStatus('Generating image... (' + pollCount + ')');
						}
					}
				},
				error: () => {
					// Continue polling even if there's an error
				}
			});
		}, 5000); // Poll every 5 seconds
	};

	const handleGenerate = () => {
		if (description.trim() === '') {
			alert('Please enter a description for the image.');
			return;
		}

		setIsGenerating(true);
		setShowAddButton(false);
		setShowTryAgain(false);
		setImagePreview('');
		showStatus('Starting image generation...');

		// Make AJAX request to generate image
		$.ajax({
			url: window.samurAiAdmin.ajaxUrl,
			type: 'POST',
			data: {
				action: 'websamurai_generate_image',
				nonce: window.samurAiAdmin.nonce,
				description: description
			},
			success: (response) => {
				if (response.success && response.data.conversation) {
					conversationIdRef.current = response.data.conversation.id;
					showStatus('Image generation started. Please wait...');

					// Start polling for completion
					startPolling(response.data.conversation.id);
				} else {
					showStatus(response.data.message || 'Failed to start image generation.', true);
					setIsGenerating(false);
					setShowTryAgain(true);
				}
			},
			error: (xhr, status, error) => {
				showStatus('Error: ' + error, true);
				setIsGenerating(false);
				setShowTryAgain(true);
			}
		});
	};

	const handleAddToLibrary = () => {
		if (!imagePreview) {
			alert('No image to add.');
			return;
		}

		showStatus('Adding image to media library...');
		setShowAddButton(false);
		setShowTryAgain(false);

		// Make AJAX request to add image to library
		$.ajax({
			url: window.samurAiAdmin.ajaxUrl,
			type: 'POST',
			data: {
				action: 'websamurai_add_image_to_media',
				nonce: window.samurAiAdmin.nonce,
				image_url: imagePreview,
				description: description
			},
			success: (response) => {
				if (response.success) {
					showStatus('Image added to media library successfully!');

					// Reset after 2 seconds
					setTimeout(() => {
						handleReset();
					}, 2000);
				} else {
					showStatus(response.data.message || 'Failed to add image to library.', true);
					setShowAddButton(true);
					setShowTryAgain(true);
				}
			},
			error: (xhr, status, error) => {
				showStatus('Error: ' + error, true);
				setShowAddButton(true);
				setShowTryAgain(true);
			}
		});
	};

	const handleReset = () => {
		setDescription('');
		setStatusMessage('');
		setImagePreview('');
		setIsGenerating(false);
		setShowAddButton(false);
		setShowTryAgain(false);
		if (pollingIntervalRef.current) {
			clearInterval(pollingIntervalRef.current);
			pollingIntervalRef.current = null;
		}
		conversationIdRef.current = null;
	};

	return (
		<div className="websamurai-generate-container">
			<div className="websamurai-generate-header">
				<h2>Generate Image with AI</h2>
				<p>Describe the image you want to create and our AI will generate it for you.</p>
			</div>

			<div className="websamurai-generate-body">
				<div className="websamurai-input-group">
					<label htmlFor="websamurai-description">Image Description:</label>
					<textarea
						id="websamurai-description"
						className="websamurai-textarea"
						placeholder="e.g., A serene landscape with mountains and a lake at sunset"
						rows="4"
						value={description}
						onChange={(e) => setDescription(e.target.value)}
						disabled={isGenerating}
					/>
				</div>

				{statusMessage && (
					<div className="websamurai-status">
						<p>{statusMessage}</p>
					</div>
				)}

				{imagePreview && (
					<div className="websamurai-preview">
						<img src={imagePreview} alt="Generated" />
					</div>
				)}

				<div className="websamurai-actions">
					{!isGenerating && !showAddButton && (
						<button
							type="button"
							className="button button-primary button-large websamurai-generate-btn"
							onClick={handleGenerate}
						>
							Generate Image
						</button>
					)}

					{isGenerating && (
						<button
							type="button"
							className="button button-primary button-large websamurai-generate-btn"
							disabled
						>
							Generating...
						</button>
					)}

					{showAddButton && (
						<button
							type="button"
							className="button button-primary button-large websamurai-add-btn"
							onClick={handleAddToLibrary}
						>
							Add to Library
						</button>
					)}

					{showTryAgain && (
						<button
							type="button"
							className="button button-large websamurai-retry-btn"
							onClick={handleReset}
						>
							Try Again
						</button>
					)}
				</div>
			</div>
		</div>
	);
};

export default MediaGenerate;
