"use client";

import RoundedButton from "@/components/elements/RoundedButton";
import useAxios from "@/hooks/useAxios";
import Link from "next/link";
import { useRouter } from "next/navigation";
import React from "react";
import ProjectWorkroomRate from "./ProjectWorkroomRate";
import { SelectedUser } from "@/types/types";

function ProjectWorkroomActions({
  projectId,
  type,
  status,
  selected_user,
}: {
  projectId: string;
  type: string;
  status: string;
  selected_user: string | null | SelectedUser;
}) {
  const router = useRouter();
  const { request } = useAxios();

  const payHandler = async () => {
    try {
      const response = await request<{ authority?: string; type?: string }>(
        "POST",
        "/projects/initiate-payment-web",
        {
          item_name: type,
          projectId: projectId,
        }
      );
      if (response.type === "free") {
        router.push("/settings/workroom");
      } else {
        const authority = response.authority; // Get the payment authority
        const paymentUrl = `https://www.zarinpal.com/pg/StartPay/${authority}`; // Construct payment URL
        router.push(paymentUrl);
      }
    } catch (error: unknown) {
      console.log(error);
    }
  };

  return (
    <div className="w-full">
      <div className="flex justify-center max-w-sm mx-auto items-center w-full gap-5">
        {(status == "pre_payment" || status == "paid") && (
          <Link
            className="w-full flex justify-center "
            href={`/settings/workroom/edit/${projectId}`}
          >
            <RoundedButton className="w-full max-w-48 h-9 !border-[#0C8002] text-[#0C8002]">
              ویرایش
            </RoundedButton>
          </Link>
        )}
        {status == "ongoing" && selected_user && (
          <ProjectWorkroomRate
            projectId={projectId}
            selected_user={selected_user}
          />
        )}
        {status == "pre_payment" && (
          <RoundedButton
            onClick={payHandler}
            className="w-full max-w-48 h-9 !border-[#0C8002] text-[#0C8002]"
          >
            پرداخت
          </RoundedButton>
        )}
      </div>
    </div>
  );
}

export default ProjectWorkroomActions;
