import Button from "@/components/Low/Button";
import Input from "@/components/Low/Input";
import {Grading, Step} from "@/interfaces";
import {User} from "@/interfaces/user";
import {CEFR_STEPS, GENERAL_STEPS, IELTS_STEPS, TOFEL_STEPS} from "@/resources/grading";
import axios from "axios";
import {useEffect, useState} from "react";
import {BsPlusCircle, BsTrash} from "react-icons/bs";
import {toast} from "react-toastify";

const areStepsOverlapped = (steps: Step[]) => {
	for (let i = 0; i < steps.length; i++) {
		if (i === 0) continue;

		const step = steps[i];
		const previous = steps[i - 1];

		if (previous.max >= step.min) return true;
	}

	return false;
};

export default function CorporateGradingSystem({user, defaultSteps, mutate}: {user: User; defaultSteps: Step[]; mutate: (steps: Step[]) => void}) {
	const [isLoading, setIsLoading] = useState(false);
	const [steps, setSteps] = useState<Step[]>(defaultSteps || []);

	const saveGradingSystem = () => {
		if (!steps.every((x) => x.min < x.max)) return toast.error("One of your steps has a minimum threshold inferior to its superior threshold.");
		if (areStepsOverlapped(steps)) return toast.error("There seems to be an overlap in one of your steps.");
		if (
			steps.reduce((acc, curr) => {
				return acc - (curr.max - curr.min + 1);
			}, 100) > 0
		)
			return toast.error("There seems to be an open interval in your steps.");

		setIsLoading(true);
		axios
			.post("/api/grading", {user: user.id, steps})
			.then(() => toast.success("Your grading system has been saved!"))
			.then(() => mutate(steps))
			.catch(() => toast.error("Something went wrong, please try again later"))
			.finally(() => setIsLoading(false));
	};

	return (
		<div className="flex flex-col gap-4 border p-4 border-mti-gray-platinum rounded-xl">
			<label className="font-normal text-base text-mti-gray-dim">Grading System</label>

			<label className="font-normal text-base text-mti-gray-dim">Preset Systems</label>
			<div className="grid grid-cols-4 gap-4">
				<Button variant="outline" onClick={() => setSteps(CEFR_STEPS)}>
					CEFR
				</Button>
				<Button variant="outline" onClick={() => setSteps(GENERAL_STEPS)}>
					General English
				</Button>
				<Button variant="outline" onClick={() => setSteps(IELTS_STEPS)}>
					IELTS
				</Button>
				<Button variant="outline" onClick={() => setSteps(TOFEL_STEPS)}>
					TOFEL iBT
				</Button>
			</div>

			{steps.map((step, index) => (
				<>
					<div className="flex items-center gap-4">
						<div className="grid grid-cols-3 gap-4 w-full" key={step.min}>
							<Input
								label="Min. Percentage"
								value={step.min}
								type="number"
								disabled={index === 0 || isLoading}
								onChange={(e) => setSteps((prev) => prev.map((x, i) => (i === index ? {...x, min: parseInt(e)} : x)))}
								name="min"
							/>
							<Input
								label="Grade"
								value={step.label}
								type="text"
								disabled={isLoading}
								onChange={(e) => setSteps((prev) => prev.map((x, i) => (i === index ? {...x, label: e} : x)))}
								name="min"
							/>
							<Input
								label="Max. Percentage"
								value={step.max}
								type="number"
								disabled={index === steps.length - 1 || isLoading}
								onChange={(e) => setSteps((prev) => prev.map((x, i) => (i === index ? {...x, max: parseInt(e)} : x)))}
								name="max"
							/>
						</div>
						{index !== 0 && index !== steps.length - 1 && (
							<button
								disabled={isLoading}
								className="pt-9 text-xl group"
								onClick={() => setSteps((prev) => prev.filter((_, i) => i !== index))}>
								<div className="w-full h-full flex items-center justify-center group-hover:bg-neutral-200 rounded-full p-3 transition ease-in-out duration-300">
									<BsTrash />
								</div>
							</button>
						)}
					</div>

					{index < steps.length - 1 && (
						<Button
							className="w-full flex items-center justify-center"
							disabled={isLoading}
							onClick={() => {
								const item = {min: steps[index === 0 ? 0 : index - 1].max + 1, max: steps[index + 1].min - 1, label: ""};
								setSteps((prev) => [...prev.slice(0, index + 1), item, ...prev.slice(index + 1, steps.length)]);
							}}>
							<BsPlusCircle />
						</Button>
					)}
				</>
			))}

			<Button onClick={saveGradingSystem} isLoading={isLoading} disabled={isLoading} className="mt-8">
				Save Grading System
			</Button>
		</div>
	);
}
