import React, { useEffect, useState } from "react";
import { NextPage } from "next";
import { useRouter } from "next/router";
import { toast } from "react-toastify";
import { Signup, SignupForm } from "@models/Signup";
import SignupApi from "@api/signupApi";
import SignUpPageView from "@views/SignUpPage/SignUpPageView";
import PageWrapper from "@views/common/PageWrapper";
import noop from "@utils/noop";

interface QueryParams {
  id?: string;
  uuid?: string;
}

const parseQueryParams = (query: QueryParams) => {
  const { id, uuid } = query;
  return {
    signupId: id ? Number(id) : undefined,
    uuid,
  };
};

const useFetchSignup = (signupId: number, uuid: string) => {
  const [form, setForm] = useState(null);
  const [formData, setFormData] = useState({});

  useEffect(() => {
    const fetchSignUpForm = async (id: number): Promise<SignupForm> => {
      const signupForm = await SignupApi.getForm(id);
      setForm(signupForm);
      return signupForm;
    };

    const fetchSignUp = async (id: number, uniqueId: string): Promise<Signup> => {
      const signup = await SignupApi.getSignupUUID(id, uniqueId);
      setFormData(signup.answer);
      return signup;
    };

    if (signupId) {
      fetchSignUp(signupId, uuid).then((s) => fetchSignUpForm(s.signupForm_id));
    }
  }, [signupId, uuid]);

  return [form, formData];
};

const EditSignUpPage: NextPage = () => {
  const router = useRouter();
  const { signupId, uuid } = parseQueryParams(router.query);
  const [form, formData] = useFetchSignup(signupId, uuid);

  const onSubmit = async (data) => {
    const payload: Signup = {
      id: Number(signupId),
      signupForm_id: form.id,
      answer: data.formData,
    };

    try {
      await SignupApi.updateSignup(payload, uuid);
      // TODO: Update signup list, so user sees possible changes in the list
      toast.success("Sign-up updated successfully 😎");
    } catch (error) {
      console.error(error);
      toast.error("Uh oh! Updating sign-up failed! 😟");
    }
  };

  return (
    <PageWrapper>
      <SignUpPageView
        signUpForm={form}
        formData={formData}
        onChange={noop}
        onSubmit={onSubmit}
      />
    </PageWrapper>
  );
};

export default EditSignUpPage;
