//
// Refactor: Migrado de connect() HOC a hooks de Redux
//
// ANTES: Patrón connect() HOC
// ├─ interface IProps {
// │  ├─ isSaving, socialInfo (state)
// │  └─ saveSocial, getSocial, setHistoryPush (dispatch)
// │
// ├─ mapStateToProps: Selectores del estado
// ├─ mapDispatchToProps: Acciones despachadas
// └─ export default connect(mapStateToProps, mapDispatchToProps)(Social)
//    └─ El HOC inyecta props automáticamente
//
// AHORA: Hooks de Redux
// ├─ interface IProps { navItems, currentNavItem } (solo props propias)
// ├─ useDispatch() → acceso directo al dispatch
// ├─ useSelector() → selectores granulares dentro del componente
// │  ├─ state.app.isSaving
// │  └─ state.social
// └─ export default Social (sin HOC)
//
// CAMBIOS ESPECÍFICOS:
// • Removida toda la lógica de mapeo de props Redux
// • dispatch() llamado directamente en setRoute() y handleMenuClick()
// • Mejor legibilidad: el estado necesario está cerca de donde se usa
// • Menor acoplamiento: el componente no depende de una estructura de props fija
//

import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";

import { ErrorToast, FieldsBehavior, MainWrapper, Nav } from "@ax/components";
import { appActions } from "@ax/containers/App";
import { socialActions } from "@ax/containers/Settings/Social";
import { RouteLeavingGuard } from "@ax/guards";
import { capitalize } from "@ax/helpers";
import { useIsDirty } from "@ax/hooks";
import type { INavItem, IRootState } from "@ax/types";

import { config } from "components";
import type { AnyAction } from "redux";
import type { ThunkDispatch } from "redux-thunk";

import * as S from "./style";

interface IProps {
	navItems: INavItem[];
	currentNavItem: INavItem;
}

const instanceSocials: string[] = config.schemas.config.socials || [];
const hardcodedSocials = [
	{ name: "instagram", title: "Instagram URL" },
	{ name: "linkedIn", title: "LinkedIn URL" },
	{ name: "facebook", title: "Facebook URL" },
	{ name: "twitter", title: "X/Twitter URL" },
	{ name: "youtube", title: "YouTube URL" },
	{ name: "flickr", title: "Flickr URL" },
	{ name: "tiktok", title: "Tiktok URL" },
	{ name: "snapchat", title: "Snapchat URL" },
	{ name: "newsletter", title: "Newsletter URL" },
	{ name: "podcast", title: "Podcast URL" },
];

const Social = (props: IProps): JSX.Element => {
	const { navItems, currentNavItem } = props;
	const dispatch = useDispatch<ThunkDispatch<IRootState, undefined, AnyAction>>();
	const isSaving = useSelector((state: IRootState) => state.app.isSaving);
	const socialInfo = useSelector((state: IRootState) => state.social);
	const [socialForm, setSocialForm] = useState<Record<string, string>>({});
	const [serverFields, setServerFields] = useState<Set<string>>(new Set());
	const { isDirty, resetDirty, setIsDirty } = useIsDirty(socialForm);

	const socialFields = [
		...instanceSocials.map((name) => ({ name, title: `${capitalize(name)} URL` })),
		...hardcodedSocials.filter(
			(s) => !instanceSocials.includes(s.name) && (serverFields.has(s.name) || !!socialForm[s.name]),
		),
	];

	const changeSocialForm = (field: string, value: string) => {
		setSocialForm((state) => ({ ...state, [field]: value }));
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: Can't add resetDirty to dependencies because it causes an infinite loop
	useEffect(() => {
		dispatch(socialActions.getSocial());
		resetDirty();
	}, [dispatch]);

	useEffect(() => {
		setSocialForm({ ...socialInfo });
		setServerFields(new Set(Object.keys(socialInfo).filter((k) => !!socialInfo[k])));
		setIsDirty(false);
	}, [socialInfo, setIsDirty]);

	const saveForm = async () => {
		const isSaved = await dispatch(socialActions.saveSocial(socialForm));
		if (isSaved) resetDirty();
	};

	const rightButtonProps = {
		label: isSaving ? "Saving" : isDirty ? "Save" : "Saved",
		disabled: isSaving || !isDirty,
		action: saveForm,
	};

	const setRoute = (path: string) => {
		dispatch(appActions.setHistoryPush(path));
	};

	const modalText = (
		<>
			Some settings <strong>are not saved</strong>.{" "}
		</>
	);

	const handleMenuClick = (path: string) => {
		dispatch(appActions.setHistoryPush(path));
	};

	return (
		<>
			<RouteLeavingGuard when={isDirty} action={setRoute} text={modalText} />
			<MainWrapper backLink={false} title="Social" rightButton={rightButtonProps}>
				<S.Wrapper>
					<Nav current={currentNavItem} items={navItems} onClick={handleMenuClick} />
					<S.ContentWrapper>
						<ErrorToast />
						<S.FormWrapper>
							{socialFields.map((field, idx) => (
								<FieldsBehavior
									key={idx}
									title={field.title}
									name={field.name}
									fieldType="TextField"
									value={socialForm[field.name] || ""}
									onChange={(value: string) => changeSocialForm(field.name, value)}
								/>
							))}
						</S.FormWrapper>
					</S.ContentWrapper>
				</S.Wrapper>
			</MainWrapper>
		</>
	);
};

export default Social;
