import { usePannelStore } from "_store/pannelStore";
import { cn } from "_helpers/cn";
import { MissionForm } from "./MissionForm";
import { Rss, Trash2Icon } from "lucide-react";
import { useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { getMissionsAPI } from "_querys/missions";

export const Pannel = () => {
	const { setOpen, setMissionFormValues } = usePannelStore();
	const { isEditingMission, setEditingMission, missionFormValues } = usePannelStore();
	const missions = useQuery({
		queryKey: ["missions"],
		queryFn: () =>
			getMissionsAPI({
				OR: [{ state: "draft" }, { state: "running" }],
			}),
	});

	useEffect(() => {
		if (isEditingMission && missionFormValues) {
			const mission = missions.data?.find((mission) => mission.id === missionFormValues.id);
			if (!mission) {
				setEditingMission(false, null);
				setMissionFormValues({});
				setOpen(false);
			}
		}
	}, [
		isEditingMission,
		missions,
		setMissionFormValues,
		setEditingMission,
		setOpen,
		missionFormValues,
	]);

	return (
		<div className={cn("flex-1 max-w-[600px] z-9999999")}>
			<div className="bg-base-100 min-h-screen h-full max-h-screen w-full overflow-auto">
				<div className="flex flex-row justify-between items-center p-4">
					<h1 className="text-xl font-bold flex items-center gap-2">
						<Rss /> {isEditingMission ? "Einsatz bearbeiten" : "Neuer Einsatz"}
					</h1>
					<div>
						<button
							className="btn btn-ghost btn-sm mr-2 btn-warning"
							onClick={() => {
								setMissionFormValues({});
								setEditingMission(false, null);
							}}
						>
							<Trash2Icon size={18} />
						</button>
						<button
							className="btn"
							onClick={() => {
								setOpen(false);
								setEditingMission(false, null);
								setMissionFormValues({});
							}}
						>
							Abbrechen
						</button>
					</div>
				</div>
				<div className="divider m-0" />
				<div className="p-4">
					<MissionForm />
				</div>
			</div>
		</div>
	);
};
