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

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