import { useState } from "react";
import {
	Accordion,
	AccordionContent,
	AccordionItem,
	AccordionTrigger,
} from "~/components/ui/accordion";
import { useMediaQuery } from "~/hooks/use-media-query";
import type { UsersId } from "~/schemas/public/Users";
import { api } from "~/utils/api";

export const EmailAccordion = ({ userId }: { userId: UsersId }) => {
	const { data } = api.comunicazioni.getEmails.useQuery({
		userId,
	});

	// Track which accordion item is open
	const [openIndex, setOpenIndex] = useState<string | undefined>(undefined);

	const mobile = useMediaQuery("(max-width: 768px)");
	if (!data || data.length === 0) {
		return <div className="text-center">Nessuna comunicazione trovata</div>;
	}

	return (
		<div className="mx-auto py-4">
			<Accordion
				className="space-y-4"
				collapsible
				onValueChange={setOpenIndex}
				type="single"
				value={openIndex}
			>
				{data.map((email, index) => (
					<AccordionItem
						className="space-y-2 border-none"
						key={email.title}
						value={String(index)}
					>
						<AccordionTrigger className="rounded-md bg-muted px-4 py-2">
							Email &ldquo;{email.title}&rdquo; del{" "}
							{new Date(email.created_at).toLocaleDateString("it-IT", {
								day: "2-digit",
								month: "2-digit",
								year: "numeric",
							})}
						</AccordionTrigger>
						<AccordionContent>
							{openIndex === String(index) && (
								<iframe
									height={mobile ? "600px" : "500px"}
									srcDoc={email.html}
									title="Email Content"
									width="100%"
								/>
							)}
						</AccordionContent>
					</AccordionItem>
				))}
			</Accordion>
		</div>
	);
};
