import { Button, Text, Skeleton, Loader } from '@bsf/force-ui';
import { __, sprintf } from '@wordpress/i18n';
import { RefreshCw } from 'lucide-react';
import { useState } from '@wordpress/element';
import EmptyState from '@GlobalComponents/empty-state';
import { cn } from '@Functions/utils';

// Separate component for individual generated content items
const GeneratedContentItem = ( { item, onUseThis, globalFixing } ) => {
	const [ isFixing, setIsFixing ] = useState( false );

	const handleUseThis = async ( content ) => {
		if ( isFixing || globalFixing ) {
			return;
		}

		setIsFixing( true );
		try {
			if ( typeof onUseThis === 'function' ) {
				await onUseThis( content );
			}
		} finally {
			setIsFixing( false );
		}
	};

	return (
		<div className="flex flex-row self-stretch gap-1 p-2 bg-white rounded-md shadow-sm">
			{ /* Text Content */ }
			<div className="flex flex-row items-center gap-1 p-1 flex-1">
				<div className="flex flex-row justify-stretch items-stretch gap-2 flex-1">
					<Text
						size={ 14 }
						weight={ 500 }
						color="secondary"
						className="flex-1"
					>
						{ item.text }
					</Text>
				</div>
			</div>

			{ /* Use This Button */ }
			<div className="flex flex-row items-start gap-2">
				<Button
					variant="link"
					size="xs"
					tag="button"
					className="mt-2"
					onClick={ () => handleUseThis( item.text ) }
					disabled={ isFixing || globalFixing }
					icon={ isFixing && <Loader size="sm" /> }
				>
					{ isFixing
						? __( 'Fixing…', 'surerank' )
						: __( 'Use This', 'surerank' ) }
				</Button>
			</div>
		</div>
	);
};

const GenerateContent = ( {
	onUseThis,
	onRegenerate,
	contents = [],
	generating = false,
	fixing = false,
	error = null,
} ) => {
	const handleRegenerate = () => {
		if ( generating ) {
			return;
		}
		if ( typeof onRegenerate !== 'function' ) {
			return;
		}
		onRegenerate();
	};

	const hasAnyContent = contents && contents?.length > 0;
	const hasError = error !== null; // Error handling moved to parent component

	// Determine button text based on state
	const getButtonText = () => {
		if ( ! hasAnyContent && hasError ) {
			return __( 'Retry', 'surerank' );
		}
		if ( generating ) {
			return __( 'Generating…', 'surerank' );
		}
		if ( hasAnyContent ) {
			return __( 'Regenerate', 'surerank' );
		}
		return __( 'Generate', 'surerank' );
	};

	// Determine empty state message
	const getEmptyStateMessage = () => {
		if ( ! hasAnyContent ) {
			return sprintf(
				/* translators: %s: "Retry" button text */
				__(
					'No content generated. Click %s to retry creating AI-powered content suggestions.',
					'surerank'
				),
				`"${ getButtonText() }"`
			);
		}
		return __(
			'No content generated yet. Click "Generate" to create AI-powered content suggestions.',
			'surerank'
		);
	};

	// Determine main content to render
	let mainContent;

	if ( generating ) {
		// Loading skeleton for content items
		const skeletonItems = Array.from( { length: 5 } ).map( ( _, index ) => (
			<div
				key={ index }
				className="flex flex-row self-stretch gap-1 p-2 bg-white rounded-md shadow-sm"
			>
				{ /* Text Content Skeleton */ }
				<div className="flex flex-row items-center gap-1 p-1 flex-1">
					<div className="flex flex-row justify-stretch items-stretch gap-2 flex-1">
						<div className="flex-1 space-y-2">
							<Skeleton
								variant="rectangular"
								className="w-full h-4"
							/>
							<Skeleton
								variant="rectangular"
								className="w-3/4 h-4"
							/>
						</div>
					</div>
				</div>

				{ /* Button Skeleton */ }
				<div className="flex flex-row items-center gap-2">
					<Skeleton
						variant="rectangular"
						className="w-16 h-8 rounded"
					/>
				</div>
			</div>
		) );

		mainContent = skeletonItems;
	} else if ( hasAnyContent ) {
		// Generated content items using the separate component
		const contentItems = contents.map( ( item ) => (
			<GeneratedContentItem
				key={ item.id }
				item={ item }
				onUseThis={ onUseThis }
				globalFixing={ fixing }
			/>
		) );

		mainContent = contentItems;
	} else {
		// Empty state
		mainContent = (
			<div className="flex flex-col self-stretch gap-2">
				<EmptyState
					message={ getEmptyStateMessage() }
					className="m-2 text-center"
				/>
			</div>
		);
	}

	return (
		<div className="flex flex-col self-stretch gap-3">
			{ /* Header Text */ }
			<Text
				size={ 14 }
				weight={ 400 }
				color="primary"
				className="self-stretch"
			>
				{ __(
					"Here are the fixes generated by SureRank AI based on your request. Review and apply the ones you'd like to use.",
					'surerank'
				) }
			</Text>

			{ /* Content Wrapper */ }
			<div className="flex flex-col items-end self-stretch gap-2 p-2 bg-background-secondary rounded-lg">
				{ /* Main Content Area */ }
				{ mainContent }

				{ /* Single Action Button */ }
				<div className="flex flex-row items-center gap-2 p-1">
					<Button
						variant="ghost"
						size="xs"
						onClick={ handleRegenerate }
						disabled={ generating }
						icon={
							<RefreshCw
								className={ cn(
									'w-4 h-4',
									generating && 'animate-spin'
								) }
							/>
						}
						iconPosition="left"
						className="px-1"
					>
						{ getButtonText() }
					</Button>
				</div>
			</div>
		</div>
	);
};

export default GenerateContent;
