import React, { Fragment, useEffect } from 'react';
import { useApi } from '../ajax/ajax.hooks';
import { useStoreActions } from '../store/store.hooks';
import { PlacementTabKey } from './placements.models';
import { IWidget, WidgetStatus } from 'dot-utils';
import {
	baseSpacing,
	GridWidget,
	LoadingWrapper,
	WidgetsFilter,
	WidgetsGrid,
} from 'dot-design-system';
import WidgetStatsTease from 'dot-design-system/build/blocks/WidgetStatsTease';
import { AjaxState } from '../ajax/ajax.model';
import CircleIconButton from '../elements/CircleIconButton';
import EmptyItems from '../elements/EmptyItems';

interface Props {}

function PlacementWidgetSelectContainer({}: Props) {
	const [state, result] = useApi('widget/get', {
		data: {
			status: WidgetStatus.Published,
		},
	});
	const hasWidgets = state === AjaxState.Loaded && result?.length > 0;
	const setSelectedWidget = useStoreActions((actions) => actions.placements.setSelectedWidget);
	const setStep = useStoreActions((actions) => actions.placements.setStep);
	const setMessage = useStoreActions((actions) => actions.admin.setMessage);

	useEffect(() => {
		setMessage({
			title: 'Notice!',
			content:
				'Create your widgets at portal.dotaudiences.com. Your saved widgets will then appear below automatically.',
		});
	}, []);

	const handleCreateWidgetClick = (e: any) => {
		e.preventDefault();
		const anchor = e.target.closest('a');

		if (anchor) {
			window.open(anchor.href);
		}
	};

	const onSelect = (widget: IWidget) => {
		setSelectedWidget(widget);
		setStep(PlacementTabKey.SelectPlacement);
	};

	const renderWidgetStats = (widget: IWidget) => {
		const [viewState, viewResult] = useApi(`widget-analytics/stat`, {
			method: 'get',
			data: {
				stat: 'impressionsCount',
				widgetId: widget.id,
			},
		});
		const [engagementState, engagementResult] = useApi('widget-analytics/stat', {
			method: 'get',
			data: {
				stat: 'engagementTime',
				widgetId: widget.id,
			},
		});
		const views = viewResult?.count || 0;
		const engagement = engagementResult?.duration || 0;
		const opacity = ([viewState, engagementState].includes(AjaxState.Loading) && 0.5) || 1;
		return <WidgetStatsTease views={views} engagement={engagement} opacity={opacity} />;
	};

	return (
		<Fragment>
			<CircleIconButton
				component={'a'}
				href={`${process.env.APP_URL}/widget/create`}
				onClick={handleCreateWidgetClick}
				my={baseSpacing * 2}
			>
				Create Widget (Opens New Tab)
			</CircleIconButton>
			{state === AjaxState.Loading && (
				<LoadingWrapper isLoading={true} width={200} height={200} mx={'auto'} />
			)}
			{state === AjaxState.Loaded && !hasWidgets && <EmptyItems />}
			{hasWidgets && (
				<WidgetsFilter
					mx={'auto'}
					mt={baseSpacing * 2}
					widgets={result || []}
					render={(filteredWidgets) => {
						return (
							<WidgetsGrid
								mx={'auto'}
								widgets={filteredWidgets}
								renderWidget={(widget, height) => (
									<GridWidget
										widget={widget}
										height={height}
										onClick={onSelect}
										canDelete={false}
										canEdit={false}
										renderAfterContent={renderWidgetStats}
									/>
								)}
							/>
						);
					}}
					css={`
						max-width: 650px;
					`}
				/>
			)}
		</Fragment>
	);
}

export default PlacementWidgetSelectContainer;
