import CheckIcon from "@mui/icons-material/Check";
import { Button, Checkbox, FormControlLabel, Typography } from "@mui/material";
import { getLocalizedString, localize } from "@olenbetong/appframe-core";

import { useEffect, useRef, useState } from "react";

import { procApproveDamage } from "../data";

const formatter = new Intl.DateTimeFormat(af.userSession.culture, {
	day: "numeric",
	month: "long",
	year: "numeric",
	hour: "2-digit",
	minute: "2-digit",
	timeZone: "UTC",
});

type RegisterFixType = {
	ID: number;
	RegisteredFixFullName: string | null;
	RegisteredFix: Date | null;
	RegisteredFixBy: string | null;
};

type ApproveDamageProcedureRecord = {
	Table: Array<Required<RegisterFixType>>;
};

type RegisterFixProps = {
	value?: RegisterFixType | null;
	defaultValue?: RegisterFixType | null;
	onFix?: (ID: number) => void;
	edit?: boolean;
};

export function RegisterFix({ value, defaultValue, onFix, edit }: RegisterFixProps) {
	let [loading, setLoading] = useState<boolean>(false);
	let initializedRef = useRef<boolean>(false);

	let [fix, setFix] = useState<RegisterFixType | null>(defaultValue ?? null);
	let fixValue = value === undefined ? fix : value;

	// biome-ignore lint: intentionally skipping "value" dependency as this should never run when "value" changes
	useEffect(() => {
		if (initializedRef.current) {
			return;
		}

		if (value === undefined && defaultValue) {
			setFix(defaultValue);
			initializedRef.current = true;
		}
	}, [defaultValue]);

	async function handleRegisterFix() {
		try {
			if (confirm(getLocalizedString("Are you sure you want to register a fix for this damage?"))) {
				setLoading(true);
				let record = (await procApproveDamage.execute({ ID: fixValue?.ID })) as ApproveDamageProcedureRecord;

				setFix({ ...record.Table[0] });

				setLoading(false);
				onFix?.(fixValue?.ID ?? -1);
			}
		} catch (error) {
			alert((error as Error).message);
		}
	}

	return (
		<>
			{edit ? (
				<Button
					loading={loading}
					loadingPosition="end"
					endIcon={<CheckIcon />}
					onClick={handleRegisterFix}
					disabled={!!fixValue?.RegisteredFix}
					variant="contained"
				>
					{getLocalizedString("Register fix")}
				</Button>
			) : (
				<FormControlLabel
					control={<Checkbox />}
					label={getLocalizedString("Register fixed")}
					name="RegisteredFix"
					id="NewElementDamage_RegisteredFix"
				/>
			)}

			{fixValue?.RegisteredFix && (
				<Typography sx={{ mb: 1.5 }} color="text.secondary">
					{localize`Registered fix by ${fixValue.RegisteredFixFullName ?? fixValue.RegisteredFixBy} on the ${formatter.format(fixValue.RegisteredFix)}`}
				</Typography>
			)}
		</>
	);
}
