import React from "react";
import { NextPage } from "next";
import { formatRelative } from "date-fns";
import { toast } from "react-toastify";
import styled from "styled-components";
import AdminListCommon from "@views/admin/AdminListCommon";
import { Button, Link } from "@components/index";
import AddLink from "@components/AddLink";
import Event from "@models/Event";
import EventApi from "@api/eventApi";
import useFetchEvents from "@hooks/useFetchEvents";

const URL = "/admin/events";

const StyledButton = styled(Button) <{ $colorOverride: "red" }>`
  background-color: ${(p) => p.$colorOverride};
  border-radius: 8px;
  color: white;
  font-size: 13px;
  font-weight: bold;
`;

const confirmDelete = async (event: Event) => {
  if (window.confirm(`Delete: ${event.id}: ${event.title_fi}/${event.title_en}; Are you sure?`) === true) {
    try {
      await EventApi.deleteEvent(event.id);
      toast.success("Event removed successfully 😎");
      window.location.reload(); // TODO: Fetch/update event list, so user sees the signup in the list
    } catch (err) {
      toast.error("Uh oh! Something went wrong! Try again later. 😟");
    }
  }
};

const renderData = (events: Event[]) => {
  if (!events || events.length === 0) {
    return <div>No events.</div>;
  }

  return (
    <table>
      <thead>
        <tr>
          <th>Title</th>
          <th>Start time</th>
          <th>End time</th>
        </tr>
      </thead>
      <tbody>
        {events.map((event) => (
          <tr key={event.id}>
            <td><Link to={`${URL}/${event.id}`}>{event.title_fi}</Link></td>
            <td>{formatRelative(new Date(event.start_time), new Date())}</td>
            <td>{formatRelative(new Date(event.end_time), new Date())}</td>
            <td>
              <StyledButton $colorOverride="red" buttonStyle="filled" onClick={() => confirmDelete(event)}>
                Delete
              </StyledButton>
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  );
};

const AdminEventPage: NextPage = () => {
  const { data } = useFetchEvents({ options: { auth: true } });
  return (
    <AdminListCommon>
      <h1>Events</h1>
      <AddLink text="Create event" to={`${URL}/create`} data-e2e="create-event" />
      {renderData(data)}
    </AdminListCommon>
  );
};

export default AdminEventPage;
