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";

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

export const ParticipantModal = ({
	participantForm,
	ref,
}: ParticipantModalProps) => {
	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"
					/>
					<Switch
						form={participantForm}
						name="completetionWorkflowFinished"
						label="Abgeschlossen (E-Mail-Benachrichtigung senden)"
					/>
					<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 as any).timestamp}>
								<p>{s.event}</p>
								<p>{s.user}</p>
								<p>{new Date((s as any).timestamp).toLocaleString()}</p>
							</div>
						))}
					</div>
					<Button type="submit" className="btn btn-primary">
						Speichern
					</Button>
					<Button
						type="button"
						className="btn btn-error btn-outline"
						onSubmit={() => false}
						onClick={() => {
							deleteParticipant(participantForm.watch("id"));
							participantForm.reset();
							ref.current?.close();
						}}
					>
						Löschen
					</Button>
				</form>
			</div>
		</dialog>
	);
};
