import React, { useEffect, useState } 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 { SignupForm } from "@models/Signup";
import SignupApi from "@api/signupApi";

const URL = "/admin/signups";

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 (signup: SignupForm) => {
  if (window.confirm(`Delete: ${signup.id}: ${signup.title_fi}/${signup.title_en}; Are you sure?`) === true) {
    try {
      await SignupApi.deleteForm(signup.id);
      toast.success("Signup 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 = (signupForms: SignupForm[]) => {
  if (!signupForms || signupForms.length === 0) {
    return <div>No signup forms.</div>;
  }

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

const AdminSignupPage: NextPage = () => {
  const [forms, setForms] = useState<SignupForm[]>(null);

  useEffect(() => {
    SignupApi.getForms(true)
      .then((res) => setForms(res));
  }, []);

  return (
    <AdminListCommon>
      <h1>Sign-up forms</h1>
      <AddLink text="Create signup form" to={`${URL}/create`} data-e2e="create-signup" />
      {renderData(forms)}
    </AdminListCommon>
  );
};

export default AdminSignupPage;
