"use client";

import RoundedInput from "@/components/elements/RoundedInput";
import React from "react";
import useAxios from "@/hooks/useAxios";
import RoundedButton from "@/components/elements/RoundedButton";
import { useRouter } from "next/navigation";
import { useFormik } from "formik";
import * as yup from "yup";
import Cookies from "js-cookie";
import toast from "react-hot-toast";
import { useUser } from "@/hooks/useUser";

const schema = yup.object().shape({
  offerPrice: yup.string().required(" وارد کردن مبلغ پیشنهادی الزامی است"),
  projectTime: yup.string().required(" وارد کردن زمان پیشنهادی الزامی است"),
});

function ProjectRequestForm({
  projectId,
  creatorId,
}: {
  projectId: string;
  creatorId?: string;
}) {
  const router = useRouter();
  const { request } = useAxios();
  const user = useUser();

  const isOwnProject =
    user?._id && creatorId && String(user._id) === String(creatorId);

  const formik = useFormik({
    initialValues: {
      offerPrice: "",
      projectTime: "",
    },
    validationSchema: schema,
    onSubmit: async (values) => {
      if (!Cookies.get("token")) {
        toast.error("لطفا ابتدا وارد شوید.");
        return;
      }
      try {
        await request("POST", "/projects/request", {
          project_id: projectId,
          request_time: values.projectTime,
          offer_price: values.offerPrice,
        });
        router.push("/settings/workroom");
      } catch (err: unknown) {
        console.log("Unhandled error:", err);
      }
    },
  });

  if (isOwnProject) {
    return (
      <p className="my-6 text-center text-sm text-neutral-500">
        این پروژه متعلق به شماست.
      </p>
    );
  }

  return (
    <form
      onSubmit={formik.handleSubmit}
      className="mx-auto my-5 flex w-full max-w-sm flex-col items-center"
    >
      <RoundedInput
        type="number"
        name="projectTime"
        placeholder="زمان پیشنهادی"
        className={`mt-4 ${
          formik.touched.projectTime && formik.errors.projectTime
            ? "border-red-500 dark:border-red-500"
            : "border-gray-300"
        }`}
        value={formik.values.projectTime}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
      />
      {formik.touched.projectTime && formik.errors.projectTime && (
        <small className="mt-1 block text-red-500">
          {formik.errors.projectTime}
        </small>
      )}
      <RoundedInput
        type="number"
        name="offerPrice"
        placeholder="مبلغ پیشنهادی به تومان: 20،000،000 "
        className={`mt-4 ${
          formik.touched.offerPrice && formik.errors.offerPrice
            ? "border-red-500 dark:border-red-500"
            : "border-gray-300"
        }`}
        value={formik.values.offerPrice}
        onChange={formik.handleChange}
        onBlur={formik.handleBlur}
      />
      {formik.touched.offerPrice && formik.errors.offerPrice && (
        <small className="mt-1 block text-red-500">
          {formik.errors.offerPrice}
        </small>
      )}
      <RoundedButton className="mt-4 h-10 w-40" type="submit">
        ارسال درخواست
      </RoundedButton>
    </form>
  );
}

export default ProjectRequestForm;
