import { Event, Participant } from "@repo/db";
import { EventAppointmentOptionalDefaults } from "@repo/db/zod";
import { CellContext } from "@tanstack/react-table";
import { useSession } from "next-auth/react";
import { RefObject, useRef } from "react";
import { UseFormReturn } from "react-hook-form";
import { PaginatedTable, PaginatedTableRef } from "../../../../_components/PaginatedTable";
import { Button } from "../../../../_components/ui/Button";
import { DateInput } from "../../../../_components/ui/DateInput";
import { upsertParticipant } from "../../../events/actions";
import { deleteAppoinement, upsertAppointment } from "../action";

interface AppointmentModalProps {
	event?: Event;
	ref: RefObject<HTMLDialogElement | null>;
	participantModal: RefObject<HTMLDialogElement | null>;
	appointmentsTableRef: React.RefObject<PaginatedTableRef | null>;
	appointmentForm: UseFormReturn<EventAppointmentOptionalDefaults>;
	participantForm: UseFormReturn<Participant>;
}

export const AppointmentModal = ({
	event,
	ref,
	participantModal,
	appointmentsTableRef,
	appointmentForm,
	participantForm,
}: AppointmentModalProps) => {
	const { data: session } = useSession();

	const participantTableRef = useRef<PaginatedTableRef>(null);

	return (
		<dialog ref={ref} className="modal ">
			<div className="modal-box min-w-[900px]">
				<form method="dialog">
					{/* if there is a button in form, it will close the modal */}
					<button
						className="btn btn-sm btn-circle btn-ghost absolute right-2 top-2"
						onClick={() => ref.current?.close()}
					>
						✕
					</button>
				</form>
				<h3 className="font-bold text-lg">Termin {appointmentForm.watch("id")}</h3>
				<form
					onSubmit={appointmentForm.handleSubmit(async (values) => {
						if (!event) return;
						await upsertAppointment(values);
						ref.current?.close();
						appointmentsTableRef.current?.refresh();
					})}
					className="flex flex-col"
				>
					<DateInput
						control={appointmentForm.control}
						name="appointmentDate"
						showTimeInput
						timeCaption="Uhrzeit"
						showTimeCaption
					/>
					{/* <Input
                                form={appointmentForm}
                                type="datetime-local"
                                label="Datum"
                                name="appointmentDate"
                                formOptions={{
                                    valueAsDate: true,
                                    }}
                                    /> */}
					<div>
						<PaginatedTable
							hide={appointmentForm.watch("id") === undefined}
							ref={participantTableRef}
							columns={[
								{
									accessorKey: "User.firstname",
									header: "Vorname",
								},
								{
									accessorKey: "User.lastname",
									header: "Nachname",
								},
								{
									accessorKey: "enscriptionDate",
									header: "Einschreibedatum",
									cell: ({ row }: CellContext<Participant, any>) => {
										return <span>{new Date(row.original.enscriptionDate).toLocaleString()}</span>;
									},
								},
								{
									header: "Anwesend",
									cell: ({ row }: CellContext<Participant, any>) => {
										if (row.original.attended) {
											return <span className="text-green-500">Ja</span>;
										} else if (row.original.appointmentCancelled) {
											return <span className="text-red-500">Nein (Termin abgesagt)</span>;
										} else {
											return <span>?</span>;
										}
									},
								},
								{
									header: "Aktion",

									cell: ({ row }: CellContext<Participant, any>) => {
										return (
											<div className="space-x-2">
												<button
													onClick={() => {
														participantForm.reset(row.original);
														participantModal.current?.showModal();
													}}
													className="btn btn-outline btn-sm"
												>
													anzeigen
												</button>
												{!row.original.attended && event?.hasPresenceEvents && (
													<button
														type="button"
														onSubmit={() => {}}
														onClick={async () => {
															await upsertParticipant({
																eventId: event!.id,
																userId: row.original.userId,
																attended: true,
																appointmentCancelled: false,
															});
															participantTableRef.current?.refresh();
														}}
														className="btn btn-outline btn-info btn-sm"
													>
														Anwesend
													</button>
												)}
												{!row.original.appointmentCancelled && event?.hasPresenceEvents && (
													<button
														type="button"
														onSubmit={() => {}}
														onClick={async () => {
															await upsertParticipant({
																eventId: event!.id,
																userId: row.original.userId,
																attended: false,
																appointmentCancelled: true,
																statusLog: [
																	...(row.original.statusLog as any),
																	{
																		event: "Gefehlt an Event",
																		timestamp: new Date().toISOString(),
																		user: `${session?.user?.firstname} ${session?.user?.lastname} - ${session?.user?.publicId}`,
																	},
																],
															});
															participantTableRef.current?.refresh();
														}}
														className="btn btn-outline btn-error btn-sm"
													>
														abwesend
													</button>
												)}
											</div>
										);
									},
								},
							]}
							prismaModel={"participant"}
							filter={{
								eventAppointmentId: appointmentForm.watch("id"),
							}}
							include={{ User: true }}
							leftOfPagination={
								<div className="flex gap-2">
									<Button type="submit" className="btn btn-primary">
										Speichern
									</Button>
									{appointmentForm.watch("id") && (
										<Button
											type="button"
											onSubmit={() => {}}
											onClick={async () => {
												await deleteAppoinement(appointmentForm.watch("id")!);
												ref.current?.close();
												appointmentsTableRef.current?.refresh();
											}}
											className="btn btn-error btn-outline"
										>
											Löschen
										</Button>
									)}
								</div>
							}
						/>
					</div>
				</form>
			</div>
		</dialog>
	);
};
