import type { ReactNode } from 'react';
import { useState } from '@wordpress/element';
import { Notice, Spinner } from '@wordpress/components';
import { PluginSidebar, PluginSidebarMoreMenuItem } from '@wordpress/editor';
import { __ } from '@wordpress/i18n';
import { useAccessCheck } from '../hooks/useAccessCheck';
import { useDocumentReview } from '../hooks/useDocumentReview';
import { useDocumentStatus } from '../hooks/useDocumentStatus';
import { usePostContent } from '../hooks/usePostContent';
import { DefaultView } from './views/DefaultView';
import { AnalyzingView } from './views/AnalyzingView';
import { InReviewView } from './views/InReviewView';
import { CompletedView } from './views/CompletedView';
import { ResubmitConfirmView } from './views/ResubmitConfirmView';
import { RestrictedView } from './views/RestrictedView';
import { PluginIcon } from './PluginIcon';
import {
	SIDEBAR_NAME,
	CSS_SIDEBAR,
	CSS_SPINNER_WRAP,
} from '../shared/constants';

export const Sidebar = () => {
	const { isAllowed, isLoading: isAccessLoading } = useAccessCheck();
	const { postId, postType, title, content, hasContent, savedSubmission } =
		usePostContent();
	const {
		isSubmitting,
		error: submitError,
		results,
		submit,
		reset,
	} = useDocumentReview(postId, postType, savedSubmission);

	// Derive documentId: prefer just-submitted results over saved meta
	const documentId = results?.id ?? savedSubmission?.documentId ?? null;

	const {
		status,
		issueCount,
		reportUrl,
		isPolling,
		error: pollError,
		pollFailure,
		cancelPolling,
	} = useDocumentStatus(isAllowed ? documentId : null, postId);

	const [isConfirmingResubmit, setIsConfirmingResubmit] = useState(false);

	// Derive user-facing error message
	let displayError: string | null = null;
	if (status === 'FAILED') {
		displayError = __('Analysis failed. Please try again.', 'cleardraft');
	} else if (pollFailure?.reason === 'max-retries') {
		displayError = __(
			'Unable to reach the server. Please check your connection and try again.',
			'cleardraft',
		);
	} else if (submitError) {
		displayError = submitError;
	} else if (pollError && !isPolling) {
		displayError = pollError;
	}

	// State derivation
	type ViewName =
		| 'default'
		| 'analyzing'
		| 'in-review'
		| 'complete'
		| 'resubmit-confirm';
	let activeView: ViewName;

	if (isConfirmingResubmit) {
		activeView = 'resubmit-confirm';
	} else if (isSubmitting || (isPolling && status !== 'TO_REVIEW')) {
		activeView = 'analyzing';
	} else if (status === 'TO_REVIEW') {
		activeView = 'in-review';
	} else if (status === 'COMPLETED') {
		activeView = 'complete';
	} else {
		activeView = 'default';
	}

	const handleSubmit = () => {
		submit(title, content);
	};

	const handleNewAnalysis = () => {
		setIsConfirmingResubmit(true);
	};

	const handleCancelResubmit = () => {
		setIsConfirmingResubmit(false); // Returns to complete state
	};

	const handleResubmit = () => {
		setIsConfirmingResubmit(false);
		reset(); // Clears results -> documentId becomes null -> polling stops
		submit(title, content); // Starts new submission -> new documentId -> new polling
	};

	const handleCancelAnalysis = () => {
		cancelPolling();
	};

	let view: ReactNode;
	if (activeView === 'resubmit-confirm') {
		view = (
			<ResubmitConfirmView
				onResubmit={handleResubmit}
				onCancel={handleCancelResubmit}
			/>
		);
	} else if (activeView === 'analyzing') {
		view = <AnalyzingView onCancel={handleCancelAnalysis} />;
	} else if (activeView === 'in-review') {
		view = (
			<InReviewView
				title={results?.title ?? ''}
				submittedAt={results?.createdAt ?? ''}
				onNewAnalysis={handleNewAnalysis}
			/>
		);
	} else if (activeView === 'complete') {
		view = (
			<CompletedView
				issueCount={issueCount}
				reportUrl={reportUrl}
				title={results?.title ?? ''}
				submittedAt={results?.createdAt ?? ''}
				onNewAnalysis={handleNewAnalysis}
			/>
		);
	} else {
		view = (
			<DefaultView
				onSubmit={handleSubmit}
				disabled={!hasContent || !postId || isSubmitting}
			/>
		);
	}

	return (
		<>
			<PluginSidebarMoreMenuItem target={SIDEBAR_NAME}>
				{__('ClearDraft Review', 'cleardraft')}
			</PluginSidebarMoreMenuItem>

			<PluginSidebar
				name={SIDEBAR_NAME}
				title={__('ClearDraft Review', 'cleardraft')}
				icon={<PluginIcon />}
			>
				<div className={CSS_SIDEBAR}>
					{isAccessLoading && (
						<div className={CSS_SPINNER_WRAP}>
							<Spinner />
						</div>
					)}
					{!isAccessLoading && !isAllowed && <RestrictedView />}
					{!isAccessLoading && isAllowed && (
						<>
							{displayError && activeView === 'default' && (
								<Notice status="error" isDismissible={false}>
									{displayError}
								</Notice>
							)}
							{view}
						</>
					)}
				</div>
			</PluginSidebar>
		</>
	);
};
