import React, {lazy, Suspense, useState} from "react";
import Loader from "../../components/loader";
import {ErrorBoundary} from "react-error-boundary";
import ErrorFallback from "../../components/ErrorFallback";
import type {Settings} from "./types/settings";
import FormNotice from "../../components/form-notice";
import {FieldValues, FormProvider, useForm} from "react-hook-form";
import type {FormProps} from "./types/form-props";

const General = lazy(() => import("./pages/general"));
const Style = lazy(() => import("./pages/style"));

const settings = (window as any).hulk_woo_pdil_settings as Settings;
const savedSettings = settings.saved_settings;

const App = () => {
	const methods = useForm<FormProps>({
		defaultValues: async () => {

			const word_limit = (savedSettings?.word_limit && savedSettings?.word_limit > 0) ? savedSettings?.word_limit : '';

			return {
				enabled_pages: savedSettings?.enabled_pages ?? [],
				description_content: savedSettings?.description_content ?? '',
				description_position: savedSettings?.description_position ?? '',
				word_limit: word_limit as number,
				enable_style: savedSettings?.enable_style ?? false,
				text_align: savedSettings?.text_align ?? 'center',
				font_size: savedSettings?.font_size ?? 16,
				text_color: savedSettings?.text_color ?? '',
			}
		},
	});

	const [notice, setNotice] = useState("");
	const [noticeStatus, setNoticeStatus] = useState("");

	async function onSubmit(data: FieldValues) {
		const requestOptions: RequestInit = {
			method: "POST",
			headers: {
				"Content-Type": "application/json",
				Accept: "application/json",
				"X-WP-Nonce": settings.nonce,
			},
			body: JSON.stringify(data),
			redirect: "follow",
		};
		try {
			setNotice("");
			setNoticeStatus('');
			const res = await fetch(
				`${settings.rest_url}/v1/settings`,
				requestOptions,
			);
			const data = await res.json();
			if (data.success !== true) {
				setNoticeStatus('error');
				setNotice(data.message);
				return;
			}
			setNoticeStatus('success');
			setNotice(data.message);
		} catch (error) {
			const err =
				error instanceof Error ? error : new Error(String(error));
			setNotice(err.message);
			setNoticeStatus('error');
			console.error(err.message);
		}
	}

	return (
		<FormProvider {...methods}>
			<form onSubmit={methods.handleSubmit(onSubmit)}>
				<FormNotice
					status={noticeStatus}
					message={notice}
					onRemove={() => setNotice("")}
				/>
				<ErrorBoundary FallbackComponent={ErrorFallback}>
					{settings.current_tab === "general" && (
						<Suspense fallback={<Loader/>}>
							<General/>
						</Suspense>
					)}
					{settings.current_tab === "style" && (
						<Suspense fallback={<Loader/>}>
							<Style/>
						</Suspense>
					)}
				</ErrorBoundary>
			</form>
		</FormProvider>
	);
};

export default App;
