import { useState } from "react";

import { useTranslation } from "next-i18next";

import { Button, Group, Modal, Table } from "@mantine/core";

import { gql, useMutation } from "@apollo/client";

const sendReminderMutation = gql`
  mutation sendReminder($id: Int) {
    sendReminder(id: $id)
  }
`;

export default function SignUpsModal({ open, close, event }) {
  const { t } = useTranslation("common");
  const [sendReminder] = useMutation(sendReminderMutation);
  const [loading, setLoading] = useState(false);

  const copyMailAddresses = () => {
    const addresses = event.signUps
      .map((signUp) => signUp.user.email)
      .join(", ");
    navigator.clipboard.writeText(addresses);
  };

  const sendRem = async () => {
    setLoading(true);
    await sendReminder({
      variables: {
        id: event.id,
      },
    });
    setLoading(false);
  };

  if (!event) return <></>;

  return (
    <Modal opened={open} onClose={close} size="xl">
      <h2>{t("participants")}</h2>
      <Table striped highlightOnHover>
        <thead>
          <tr>
            <th>Name</th>
            <th>Email</th>
          </tr>
        </thead>
        <tbody>
          {event.signUps.map((signUp, i) => (
            <tr key={i}>
              <td>{signUp.user.name}</td>
              <td>{signUp.user.email}</td>
            </tr>
          ))}
        </tbody>
      </Table>

      <Group grow mt="md">
        <Button onClick={copyMailAddresses}>{t("copyMailAddresses")}</Button>
        <Button onClick={sendRem} loading={loading}>
          {t("sendReminder")}
        </Button>
      </Group>
    </Modal>
  );
}