import React, { useEffect, useState } from "react";
import { NextPage } from "next";
import { useRouter } from "next/router";
import { toast } from "react-toastify";
import styled from "styled-components";
import { CSVLink } from "react-csv";
import AdminListCommon from "@views/admin/AdminListCommon";
import { Signup, SignupForm } from "@models/Signup";
import SignupApi from "@api/signupApi";
import { Button } from "@components/index";
import noop from "@utils/noop";

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

const SignupEmailPage: NextPage = () => {
  const [signupForm, setSignupForm] = useState<SignupForm>(null);
  const [signups, setSignups] = useState<Signup[]>([]);

  const router = useRouter();
  const { id } = router.query;

  useEffect(() => {
    const formId = Number(id);
    SignupApi.getForm(formId, true)
      .then((res) => setSignupForm(res));

    SignupApi.getSignups(formId).then((res) => setSignups(res));
  }, [id]);

  const confirmDelete = async (signup: Signup, question: any) => {
    if (window.confirm(`Delete: ${signup.id}: ${signup.answer[question.id]}; Are you sure?`) === true) {
      try {
        await SignupApi.deleteSignup(signup.id);
        setSignups(signups.filter((s) => s.id !== signup.id));
        toast.success("Signup removed successfully 😎");
      } catch (err) {
        toast.error("Uh oh! Something went wrong! Try again later. 😟");
      }
    }
  };

  const title = signupForm ? signupForm.title_fi : "Loading...";

  const questions = signupForm ? signupForm.questions.map((q) => ({
    title: q.name,
    id: q.id,
  })) : [];

  // Generate 2-dimensional array where rows are signups and columns are answers to questions.
  const CSVData = signups.map((s) => questions.map((q) => s.answer[q.id]));
  // Add reserve signup "header"
  if (signupForm?.quota) {
    CSVData.splice(signupForm.quota, 0, ["RESERVE-SIGNUPS"]);
  }

  return (
    <AdminListCommon>
      <h1>{title}: Sign-ups</h1>
      <table>
        <thead>
          <tr>
            {questions.map((q) => (
              <th key={q.id}>{q.title}</th>
            ))}
            <th>
              <CSVLink data={CSVData} headers={questions.map((q) => q.title)} separator=";">
                <StyledButton $colorOverride="green" buttonStyle="filled" onClick={noop}>
                  Download CSV
                </StyledButton>
              </CSVLink>
            </th>
          </tr>
        </thead>

        <tbody>
          {signups.map((s) => (
            <tr key={s.id}>
              {questions.map((q) => (
                <td key={`${s.id} - ${q.id}`}>
                  {s.answer[q.id]}
                </td>
              ))}
              <td>
                <StyledButton $colorOverride="red" buttonStyle="filled" onClick={() => confirmDelete(s, questions[0])}>
                  Delete
                </StyledButton>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </AdminListCommon>
  );
};

export default SignupEmailPage;
