import PrimaryButton from "@/components/button/PrimaryButton";
import SecondaryButton from "@/components/button/SecondaryButton";
import DateInput from "@/components/input/DateInput";
import NumberInput from "@/components/input/NumberInput";
import TextInput from "@/components/input/TextInput";
import RaidBuilderModal from "@/components/modal/RaidBuilderModal";
import { useCreateRaidInstance, useUpdateRaidInstance } from "@/hooks/RaidInstanceHooks";
import { RaidGroup } from "@/interface/RaidGroup";
import { RaidInstance } from "@/interface/RaidInstance";
import { useTimedModal } from "@/providers/TimedModalProvider";
import moment from "moment";
import { useEffect, useState } from "react";


export default function RaidInstanceModal({
	display,
	close,
	raidInstance,
	raidGroup
}:{
	display: boolean;
	close: () => void;
	raidInstance?: RaidInstance;
	raidGroup: RaidGroup;
}){
	const [raidInstanceName, setRaidInstanceName] = useState("");
	const [raidStartDate, setRaidStartDate] = useState(new Date());
	const [raidEndDate, setRaidEndDate] = useState(new Date());
	const [raidSize, setRaidSize] = useState(3);
	const [numberRuns, setNumberRuns] = useState(1);
	const modalId = crypto.randomUUID().replaceAll("-", "");

	const createRaidInstanceMutate = useCreateRaidInstance(raidGroup.raidGroupId ?? "");
	const updateRaidInstanceMutate = useUpdateRaidInstance(raidGroup.raidGroupId ?? "");
	const { addSuccessMessage, addErrorMessage } = useTimedModal();

	useEffect(() => {
		if(raidInstance){
			setRaidInstanceName(raidInstance.raidInstanceName ?? "");
			setRaidStartDate(raidInstance.raidStartDate);
			setRaidEndDate(raidInstance.raidEndDate);
			setRaidSize(raidInstance.raidSize ?? 0);
			setNumberRuns(raidInstance.numberRuns);
		}
		else{
			const currentDate = new Date();
			const futureDate = new Date();
			futureDate.setHours(futureDate.getHours() + 1);
			setRaidInstanceName("");
			setRaidStartDate(currentDate);
			setRaidEndDate(futureDate);
			setRaidSize(3);
			setNumberRuns(1);
		}
	}, [ display, raidInstance ]);

	useEffect(() => {
		if(createRaidInstanceMutate.status === "success"){
			createRaidInstanceMutate.reset();
			addSuccessMessage("Raid Instance Created");
			close();
		}
		else if(createRaidInstanceMutate.status === "error"){
			createRaidInstanceMutate.reset();
			addErrorMessage(`Error creating raid instance ${raidInstanceName}: ${createRaidInstanceMutate.error.message}`);
			console.log(createRaidInstanceMutate.error);
		}
		else if(updateRaidInstanceMutate.status === "success"){
			updateRaidInstanceMutate.reset();
			addSuccessMessage("Raid Instance Updated");
			close();
		}
		else if(updateRaidInstanceMutate.status === "error"){
			updateRaidInstanceMutate.reset();
			addErrorMessage(`Error updating raid instance ${raidInstanceName}: ${updateRaidInstanceMutate.error.message}`);
			console.log(updateRaidInstanceMutate.error);
		}
	});

	const createRaidInstance = () => {
		if(!raidInstanceName || raidInstanceName.trim().length <= 0){
			addErrorMessage("Error creating raid instance: Raid instance name must contain at least 1 letter");
			return;
		}
		else if(raidSize <= 0){
			addErrorMessage("Error creating raid instance: Raid size must be greater than 0");
			return;
		}
		else if(numberRuns <= 0){
			addErrorMessage("Error creating raid instance: Number of runs must be greater than 0");
			return;
		}
		else if(!raidGroup?.raidGroupId || raidGroup?.raidGroupId.trim() === ""){
			addErrorMessage("Error creating raid instance: Raid group is required");
			return;
		}
		else if(raidStartDate > raidEndDate){
			addErrorMessage("Error creating raid instance: Raid start date must be before raid end date");
			return;
		}
		else if(raidStartDate < new Date()){
			addErrorMessage("Error creating raid instance: Raid start date must be in the future");
			return;
		}


		createRaidInstanceMutate.mutate({
			raidInstanceName,
			raidStartDate,
			raidEndDate,
			raidSize,
			numberRuns,
			raidGroupId: raidGroup.raidGroupId ?? ""
		});
	}

	const updateRaidInstance = () => {
		if(!raidInstance?.raidInstanceId || raidInstance?.raidInstanceId.trim() === ""){
			addErrorMessage("Raid Instance ID is required");
			return;
		}
		else if(!raidInstanceName || raidInstanceName.trim().length <= 0){
			addErrorMessage("Error creating raid instance: Raid instance name must contain at least 1 letter");
			return;
		}
		else if(raidSize <= 0){
			addErrorMessage("Error creating raid instance: Raid size must be greater than 0");
			return;
		}
		else if(numberRuns <= 0){
			addErrorMessage("Error creating raid instance: Number of runs must be greater than 0");
			return;
		}
		else if(!raidGroup?.raidGroupId || raidGroup?.raidGroupId.trim() === ""){
			addErrorMessage("Error creating raid instance: Raid group is required");
			return;
		}
		else if(raidStartDate > raidEndDate){
			addErrorMessage("Error creating raid instance: Raid start date must be before raid end date");
			return;
		}
		else if(raidStartDate < new Date()){
			addErrorMessage("Error creating raid instance: Raid start date must be in the future");
			return;
		}


		updateRaidInstanceMutate.mutate({
			raidInstanceId: raidInstance?.raidInstanceId,
			raidInstanceName,
			raidStartDate,
			raidEndDate,
			raidSize,
			numberRuns,
			raidGroupId: raidGroup.raidGroupId ?? ""
		});
	}


	return (
		<RaidBuilderModal
			display={display}
			close={close}
			modalHeader={raidInstance ? "Update Raid Instance" : "Create Raid Instance"}
			modalBody={
				<div
					className="flex flex-col items-center justify-center gap-4"
				>
					<TextInput
						id={`raidInstanceName${modalId}`}
						placeholder="Raid Instance Name"
						value={raidInstanceName}
						onChange={(e) => setRaidInstanceName(e.target.value)}
					/>
					<div
						className="flex flex-row items-center justify-center gap-4"
					>
						<NumberInput
							id="raidSizeInput"
							label="Size"
							min={1}
							max={100}
							value={raidSize}
							onChange={setRaidSize}
						/>
						<NumberInput
							id="numberRunsInput"
							label="Runs"
							min={1}
							max={100}
							value={numberRuns}
							onChange={setNumberRuns}
						/>
					</div>
					<DateInput
						id="raidStartDateInput"
						value={moment(raidStartDate).format("YYYY-MM-DDTHH:mm")}
						onChange={(e) => setRaidStartDate(moment(e.target.value).toDate())}
					/>
					<DateInput
						id="raidEndDateInput"
						value={moment(raidEndDate).format("YYYY-MM-DDTHH:mm")}
						onChange={(e) => setRaidEndDate(moment(e.target.value).toDate())}
					/>
				</div>
			}
			modalFooter={
				<>
					<PrimaryButton
						onClick={raidInstance ? updateRaidInstance : createRaidInstance}
					>
						{raidInstance ? "Update" : "Create"}
					</PrimaryButton>
					<SecondaryButton
						onClick={close}
					>
						Cancel
					</SecondaryButton>
				</>
			}
		/>
	);
}
