import { Button, Icon, UserRolesAndSites } from "@ax/components";
import type { IRole, ISite, ISiteRoles } from "@ax/types";

import { getMostFrequentRole } from "../utils";
import { LEARN_ITEMS } from "./constants";

import * as S from "./style";

const FinalStep = (props: IFinalStepProps) => {
	const { isSuperAdmin, userRoles, roles, sites, onClose, onViewProfile } = props;

	const showRows =
		isSuperAdmin || (!!userRoles.find((ur) => ur.siteId === "all") && !userRoles.find((ur) => ur.siteId === "global"));

	const mostFrequentRoleId = getMostFrequentRole(userRoles);
	const mostFrequentRole = mostFrequentRoleId ? roles.find((r) => r.id === mostFrequentRoleId) : null;
	const mostFrequentRoleName = isSuperAdmin ? "Administrator" : mostFrequentRole?.name;

	let filteredLearnItems = mostFrequentRoleName
		? LEARN_ITEMS.filter((item) => item.roles.includes(mostFrequentRoleName))
		: [];

	if (filteredLearnItems.length === 0) {
		filteredLearnItems = LEARN_ITEMS.filter((item) => item.roles.includes("Editor"));
	}

	return (
		<S.Wrapper isRow={!showRows}>
			<S.RolesWrapper>
				<S.SectionTitle>You have these permissions</S.SectionTitle>
				<S.Text>
					Build and publish all your websites, landing pages and events easily
					<br />
					from a single platform.
				</S.Text>
				<UserRolesAndSites isSuperAdmin={isSuperAdmin} userRoles={userRoles} sites={sites} roles={roles} />
			</S.RolesWrapper>
			<S.LearnWrapper>
				<S.LearnTitle>Learn how to use</S.LearnTitle>
				<S.ItemsWrapper>
					{filteredLearnItems.map(({ icon, title, description, url }) => (
						<S.LearnItem key={title}>
							<S.LearnHeader>
								<S.IconWrapper>
									<Icon name={icon} />
								</S.IconWrapper>
								<S.ItemTitle>{title}</S.ItemTitle>
							</S.LearnHeader>
							<S.Description>{description}</S.Description>
							<Button type="button" buttonStyle="minimal" icon="openOutside" onClick={() => window.open(url, "_blank")}>
								view
							</Button>
						</S.LearnItem>
					))}
				</S.ItemsWrapper>
				<S.Actions>
					<Button type="button" buttonStyle="text" onClick={onViewProfile}>
						View profile
					</Button>
					<Button type="button" onClick={onClose}>
						Start Using Griddo
					</Button>
				</S.Actions>
			</S.LearnWrapper>
		</S.Wrapper>
	);
};

interface IFinalStepProps {
	isSuperAdmin: boolean;
	userRoles: ISiteRoles[];
	roles: IRole[];
	sites: ISite[];
	onClose: () => void;
	onViewProfile: () => void;
}

export default FinalStep;
