import React, { useEffect } from 'react';
import { useAction } from '../ajax/ajax.hooks';
import { Placement, PlacementAjaxOperation } from './placements.models';
import { LoadingWrapper, Wrapper } from 'dot-design-system';
import SavedPlacementsTable from './SavedPlacementsTable';
import { AjaxState } from '../ajax/ajax.model';
import { ajaxAction, ajaxApi } from '../ajax/ajax.utils';
import { useStoreActions, useStoreState } from '../store/store.hooks';
import { is, pathOr, propEq } from 'ramda';
import store from '../store/store';
import { IframeType } from 'dot-utils';
import { AdminScreen } from '../admin/admin.models';
import { WordpressTaxonomy } from '../models/wp';
import { isAllTaxonomies, triggerResetCache } from './placements.utils';
import EmptyItems from '../elements/EmptyItems';
import { useTimeout } from '../utils/timings';

interface Props {}

function SavedPlacementsContainer({}: Props) {
	const data = useStoreState((state) => state.placements.data);
	const setMessage = useStoreActions((actions) => actions.admin.setMessage);
	const [status, placements, rerun] = useAction('dot_press_placement');

	useEffect(() => {
		setMessage({
			title: 'Tip!',
			content: 'Did you know? You can see your widget performance within the Analytics page',
		});
	}, []);

	const handleDelete = async (placement: Placement) => {
		const result = await ajaxAction({
			action: 'dot_press_placement',
			method: 'post',
			data: {
				operation: PlacementAjaxOperation.DELETE,
				placement_ids: [placement.ID],
			},
		});

		if (result !== AjaxState.Error) {
			triggerResetCache();
			rerun();
		}
	};

	const handleOnEdit = async (placement: Placement) => {
		const res = await ajaxApi(`widget/${placement.meta.widget_id[0]}`);
		const taxonomyType = placement.meta?.taxonomy_type?.[0] || 'category';
		const placementTaxonomyProp = taxonomyType === 'category' ? 'categories' : 'tags';
		const taxonomies = pathOr([], [placementTaxonomyProp], placement).map(
			(item: number | WordpressTaxonomy) => {
				const termId = pathOr(item, ['term_id'], item);
				return data[placementTaxonomyProp].find(propEq('term_id', termId as any));
			}
		);

		if (isAllTaxonomies(placement)) {
			taxonomies.unshift({
				term_id: 'all',
				name: 'All',
				taxonomy: taxonomyType,
			} as WordpressTaxonomy);
		}

		store.dispatch.placements.updatePlacementSelect({
			currentPlacementId: placement.ID,
			selectedAlignment: placement.meta.alignment[0],
			selectedFormat: placement.meta.format[0].split(',') as IframeType[],
			selectedInsertionPoint: placement.meta.insertion_point[0],
			selectedInsertionNumber: Number(placement.meta.insertion_number[0]),
			selectedTaxonomies: taxonomies as WordpressTaxonomy[],
			selectedTaxonomyType: taxonomyType,
			selectedWidget: res,
		});
		store.dispatch.admin.setScreen(AdminScreen.Publish);
	};

	const isNoPlacements = !placements || !placements.length;

	if (status === AjaxState.Loaded && isNoPlacements) {
		return <EmptyItems message={'No Saved Placements'} />;
	}

	const renderTaxonomy = (
		type: 'categories' | 'tags',
		item: string | number | WordpressTaxonomy
	) => {
		if (is(Object, item)) {
			// @ts-ignore
			return item.name;
		}

		const taxonomy = data[type].find(propEq('term_id', Number(item) as any));
		if (taxonomy) {
			return taxonomy.name;
		}

		return String(item);
	};

	return (
		<Wrapper>
			{status === AjaxState.Loading && isNoPlacements && (
				<LoadingWrapper mx={'auto'} width={200} height={200} isLoading={true} />
			)}
			<Wrapper opacity={(status === AjaxState.Loading && 0.3) || 1}>
				<SavedPlacementsTable
					placements={placements || []}
					renderTaxonomy={renderTaxonomy}
					onDelete={handleDelete}
					onEditClick={handleOnEdit}
				/>
			</Wrapper>
		</Wrapper>
	);
}

export default SavedPlacementsContainer;
