import React, { useState, useEffect } from "react";
import { NextPage } from "next";
import useSWR from "swr";
import { formatRelative, formatISO } 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 { fetcher, APIPath, API } from "@api/backend";
import { StyledSelect, SelectWrapper } from "@components/Select";

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 Renderer: React.FC = () => {
  const api: API = { path: APIPath.EVENTS, authenticated: true };
  const { data: events, error } = useSWR<Event[]>(api, fetcher);

  const [sort, setSort] = useState<string>("start_time");
  const [order, setOrder] = useState<string>("descending");
  const [filter, setFilter] = useState<string>("all");

  const eventSort = (a, b) => {
    let result = 0;
    if (order === "descending") {
      if (["start_time", "end_time"].includes(sort)) {
        result = new Date(b[sort]).getTime() - new Date(a[sort]).getTime();
      } else if (sort === "id") {
        result = b[sort] - a[sort];
      }
    } else if (order === "ascending") {
      if (["start_time", "end_time"].includes(sort)) {
        result = new Date(a[sort]).getTime() - new Date(b[sort]).getTime();
      } else if (sort === "id") {
        result = a[sort] - b[sort];
      }
    }
    return result;
  };

  const dateFilter = (a) => {
    let result = true;

    if (filter === "upcoming") {
      result = new Date(a.end_time).getTime() > Date.now();
    } else if (filter === "past") {
      result = new Date(a.end_time).getTime() < Date.now();
    }
    return result;
  };

  useEffect(() => {
  }, [sort, order, filter, events]);

  if (error) {
    console.error(error);
    return (
      <div>
        Failed loading events.
      </div>
    );
  }

  if (!events?.length) {
    return <div>No events.</div>;
  }

  return (
    <div>
      <SelectWrapper>
        Sort by:
        <StyledSelect name="" onChange={(e) => setSort(e.target.value)}>
          <option value="start_time">Start time</option>
          <option value="end_time">End time</option>
          <option value="id">Creation order</option>
        </StyledSelect>
        Order:
        <StyledSelect name="" onChange={(e) => setOrder(e.target.value)}>
          <option value="descending">Descending</option>
          <option value="ascending">Ascending</option>
        </StyledSelect>
        Filter:
        <StyledSelect name="" onChange={(e) => setFilter(e.target.value)}>
          <option value="all">All</option>
          <option value="upcoming">Upcoming</option>
          <option value="past">Past</option>
        </StyledSelect>
      </SelectWrapper>
      <table>
        <thead>
          <tr>
            <th>Title</th>
            <th>Start time</th>
            <th>End time</th>
          </tr>
        </thead>
        <tbody>
          {events.sort(eventSort).filter(dateFilter).map((event) => (
            <tr key={event.id}>
              <td><Link to={`${URL}/${event.id}`}>{event.title_fi}</Link></td>
              <td>{formatISO(new Date(event.start_time), { representation: "date" })}</td>
              <td>{formatISO(new Date(event.end_time), { representation: "date" })}</td>
              <td>
                <StyledButton $colorOverride="red" buttonStyle="filled" onClick={() => confirmDelete(event)}>
                  Delete
                </StyledButton>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

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

export default AdminEventPage;
