import { Switch } from "../../../../_components/ui/Switch";
import { Button } from "../../../../_components/ui/Button";
import { Participant, ParticipantLog, Prisma } from "@repo/db";
import { UseFormReturn } from "react-hook-form";
import { upsertParticipant } from "../../../events/actions";
import { RefObject } from "react";
import { deleteParticipant } from "../action";
import { checkMoodleResults, handleParticipantFinished } from "../../../../../helper/events";
import { AxiosError } from "axios";
import toast from "react-hot-toast";
import { useRouter } from "next/navigation";

interface ParticipantModalProps {
	participantForm: UseFormReturn<Participant>;
	ref: RefObject<HTMLDialogElement | null>;
}

export const ParticipantModal = ({ participantForm, ref }: ParticipantModalProps) => {
	const router = useRouter();
	return (
		<dialog className="modal" ref={ref}>
			<div className="modal-box">
				<form method="dialog">
					<button className="btn btn-sm btn-circle btn-ghost absolute right-2 top-2">✕</button>
				</form>
				<h1 className="text-2xl">Teilnehmer bearbeiten</h1>

				<form
					onSubmit={participantForm.handleSubmit(async (data) => {
						await upsertParticipant({
							...data,
							statusLog: data.statusLog as Prisma.InputJsonValue[],
						});
						participantForm.reset();
						ref.current?.close();
					})}
					className="space-y-1"
				>
					<Switch form={participantForm} name="attended" label="Termin Teilgenommen" />
					<Switch form={participantForm} name="appointmentCancelled" label="Termin abgesagt" />
					<Switch
						form={participantForm}
						name="finisherMoodleCurseCompleted"
						label="Abschluss-Moodle-Kurs abgeschlossen"
					/>
					<div>
						<div>
							<h3 className="text-xl">Debug</h3>
							<p className="text-gray-500 text-sm">
								Diese Aktionen Versenden u.A. Mail! Aktivitäts-log für Teilnhemer aktualisiert nicht
								nach ausfühlen
							</p>
						</div>
						<div className="flex gap-3">
							<Button
								className="btn-sm"
								onClick={async () => {
									try {
										if (!participantForm.watch("id")) return;

										const participant = participantForm.getValues();
										await handleParticipantFinished(participant.id.toString()).catch(() => {});

										toast.success("Workflow erfolgreich ausgeführt");
										router.refresh();
									} catch (error) {
										const e = error as AxiosError;
										if (
											e.response?.data &&
											typeof e.response.data === "object" &&
											"error" in e.response.data
										) {
											toast.error(`Fehler: ${e.response.data.error}`);
										} else {
											toast.error("Unbekannter Fehler beim ausführen des Workflows");
										}
									}
								}}
							>
								Event-abgeschlossen Workflow ausführen
							</Button>
							<Button
								className="btn-sm"
								onClick={async () => {
									if (!participantForm.watch("id")) return;

									const participant = participantForm.getValues();
									const result = await checkMoodleResults(participant.id.toString()).catch((e) => {
										const error = e as AxiosError;
										if (
											error.response?.data &&
											typeof error.response.data === "object" &&
											"error" in error.response.data
										) {
											toast.error(`Fehler: ${error.response.data.error}`);
										} else {
											toast.error("Unbekannter Fehler beim ausführen des Workflows");
										}
									});
									if (!result) return;
									toast(result.data.message);
									router.refresh();
								}}
							>
								Moodle-Kurs Status prüfen
							</Button>
						</div>
					</div>
					<div className="w-full">
						<h3 className="text-xl">Termine</h3>

						<p className="w-full flex justify-between">
							<span>Termin ausgewählt am</span>
							<span>{new Date(participantForm.watch("enscriptionDate")).toLocaleString()}</span>
						</p>
					</div>
					<div className="flex flex-col">
						<h3 className="text-xl">Verlauf</h3>
						{(participantForm.watch("statusLog") as unknown as ParticipantLog[])?.map((s) => (
							<div className="flex justify-between" key={s.timestamp.toString()}>
								<p>{s.event}</p>
								<p>{s.user}</p>
								<p>{new Date(s.timestamp).toLocaleString()}</p>
							</div>
						))}
					</div>
					<div className="flex gap-2 w-full justify-center">
						<Button type="submit" className="btn btn-primary">
							Speichern
						</Button>
						<Button
							type="button"
							className="btn btn-error btn-outline"
							onSubmit={() => false}
							onClick={async () => {
								await deleteParticipant(participantForm.watch("id"));
								participantForm.reset();
								ref.current?.close();
							}}
						>
							Löschen
						</Button>
					</div>
				</form>
			</div>
		</dialog>
	);
};
