"use client";

import { useMutation } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import {
  PortfolioStatus,
  PortfolioGoal,
  PortfolioRole,
} from "@/app/db/schema/portfolio";
import { useSession } from "next-auth/react";

type CreatePortfolioArgs = {
  userId: bigint;
  portfolioName: string;
  budget: number | undefined;
  goal: (typeof PortfolioGoal)[number];
  status: (typeof PortfolioStatus)[number];
  role: (typeof PortfolioRole)[number];
};

const createPortfolio = async ({
  userId,
  portfolioName,
  budget,
  goal,
  status,
  role,
}: CreatePortfolioArgs) => {
  // We convert the the bigint to a string since big ints are not serialisable and we don't want to loose precision
  const requestBody = JSON.stringify({
    userId: userId.toString(),
    portfolioName: portfolioName,
    budget: budget,
    goal: goal,
    status: status,
    role: role,
  });

  const response = await fetch("/api/portfolio/", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: requestBody,
  });

  if (!response.ok) {
    throw new Error("Network response was not ok");
  }

  return response.json();
};

const ModalSubmit = ({
  buttonDisabled,
  portfolioName,
  budget,
  objective,
}: {
  buttonDisabled: boolean;
  portfolioName: string;
  budget: number | undefined;
  objective: string;
}) => {
  const router = useRouter();

  // This is a client component so we can access the session directly
  const session = useSession();

  const { mutate, isLoading } = useMutation(createPortfolio, {
    onSuccess: (data) => {
      router.push(`/portfolio/${data.portfolioId}`);
    },
    onError: (error) => {
      // handle error
      console.log(error);
    },
  });

  if (!session.data) {
    // The user is not logged in, redirect them to sign in
    router.push("/");
    return null;
  }

  const handleSubmit = () => {
    const userId = session.data.user.dbId;
    const status = "scoping";
    const role = "creator";

    mutate({
      userId,
      portfolioName: portfolioName,
      budget,
      goal: objective,
      status,
      role,
    });
  };

  return (
    <button
      type="button"
      className="inline-flex justify-center rounded-md border border-transparent bg-brandtan px-4 py-2 text-sm font-medium text-grey-900 hover:bg-hovertan focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:bg-gray-300 disabled:opacity-50"
      onClick={handleSubmit}
      disabled={buttonDisabled || isLoading}
    >
      {isLoading ? "Creating..." : "Create"}
    </button>
  );
};

export default ModalSubmit;
