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 JobAd from "@models/JobAd";
import useFetchJobAds from "@hooks/useFetchJobAds";
import JobAdApi from "@api/jobAdApi";

const URL = "/admin/jobads";

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 (jobad: JobAd) => {
  if (window.confirm(`Delete: ${jobad.id}: ${jobad.title_fi}/${jobad.title_en}; Are you sure?`) === true) {
    try {
      await JobAdApi.deleteJobAd(jobad.id);
      toast.success("Job ad 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 = (jobAds: JobAd[]) => {
  if (!jobAds || jobAds.length === 0) {
    return <div>No advertisements.</div>;
  }

  return (
    <table>
      <thead>
        <tr>
          <th>Title</th>
          <th>Description</th>
          <th>Autohide</th>
        </tr>
      </thead>
      <tbody>
        {jobAds.map((ad) => (
          <tr key={ad.id}>
            <td><Link to={`${URL}/${ad.id}`}>{ad.title_fi}</Link></td>
            <td>{ad.description_fi}</td>
            <td>
              {ad.autohide_enabled
                ? formatRelative(new Date(ad.autohide_at), new Date())
                : "Disabled"}
            </td>
            <td>
              <StyledButton $colorOverride="red" buttonStyle="filled" onClick={() => confirmDelete(ad)}>
                Delete
              </StyledButton>
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  );
};

const AdminJobAdPage: NextPage = () => {
  const { data } = useFetchJobAds({ options: { auth: true } });
  return (
    <AdminListCommon>
      <h1>Job advertisements</h1>
      <AddLink text="Create job ad" to={`${URL}/create`} />
      {renderData(data)}
    </AdminListCommon>
  );
};

export default AdminJobAdPage;
