import { useCallback, useEffect } from "react";
import { connect } from "react-redux";

import { menuActions } from "@ax/containers/Navigation";
import { sitesActions } from "@ax/containers/Sites";
import type { IGetSitePagesParams, IMenuItem, IRootState } from "@ax/types";

import { useShouldBeSaved } from "./helpers";
import Nav from "./Nav";
import Table from "./Table";

import * as S from "./style";

const List = (props: IMenuList): JSX.Element => {
	const { getMenus, lang, getSitePages, currentSiteID, editorMenu, savedMenu, currentType, setCurrentType } = props;

	if (!currentSiteID) {
		throw new Error(`ERROR: User reached Menu List with null site info`);
	}

	const { isDirty } = useShouldBeSaved(editorMenu, savedMenu, currentType);
	const memoizedGetMenus = useCallback(() => getMenus(), [getMenus]);
	const memoizedGetSitePages = useCallback(
		async (params: IGetSitePagesParams) => {
			await getSitePages(params);
		},
		[getSitePages],
	);

	// biome-ignore lint/correctness/useExhaustiveDependencies: TODO: Fix this
	useEffect(() => {
		const params = {
			siteID: currentSiteID,
			deleted: false,
			page: 1,
			itemsPerPage: 50,
		};
		memoizedGetSitePages(params);
		memoizedGetMenus();
		return () => {
			setCurrentType("");
		};
	}, [memoizedGetMenus, memoizedGetSitePages, setCurrentType, lang.id, currentSiteID]);

	return (
		<S.ListWrapper>
			<Nav isDirty={isDirty} currentType={currentType} setCurrentType={setCurrentType} />
			<S.TableWrapper>
				<Table isDirty={isDirty} />
			</S.TableWrapper>
		</S.ListWrapper>
	);
};

const mapStateToProps = (state: IRootState) => ({
	currentSiteID: state.sites.currentSiteInfo && state.sites.currentSiteInfo.id,
	lang: state.app.lang,
	editorMenu: state.menu.editorMenu?.elements || [],
	savedMenu: state.menu.savedMenu?.elements || [],
	currentType: state.menu.currentType,
});

const mapDispatchToProps = {
	getMenus: menuActions.getMenus,
	getSitePages: sitesActions.getSitePages,
	setCurrentType: menuActions.setCurrentType,
};

interface IStateProps {
	currentSiteID: number | null;
	lang: { locale: string; id: number | null };
	editorMenu: IMenuItem[] | undefined;
	savedMenu: IMenuItem[] | undefined;
	currentType: string;
}

interface IDispatchProps {
	getMenus(): void;
	getSitePages(params: IGetSitePagesParams): Promise<void>;
	setCurrentType(type: string): void;
}

type IMenuList = IStateProps & IDispatchProps;

export default connect(mapStateToProps, mapDispatchToProps)(List);
