"use client";

import RoundedInput from "@/components/elements/RoundedInput";
import React, { useMemo, useState } 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";
import { useTranslation } from "react-i18next";
import { ProjectRole } from "@/types/types";

function ProjectRequestForm({
  projectId,
  creatorId,
  selectedRole,
  portfolioRequired,
}: {
  projectId: string;
  creatorId?: string;
  selectedRole?: ProjectRole | null;
  portfolioRequired?: boolean;
}) {
  const { t } = useTranslation("common");
  const router = useRouter();
  const { request } = useAxios();
  const user = useUser();
  const [portfolio, setPortfolio] = useState<
    { data: string; type: "image" | "video" }[]
  >([]);

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

  const schema = useMemo(
    () =>
      yup.object().shape({
        offerPrice: yup
          .string()
          .required(t("projects.validation.offerPriceRequired")),
        projectTime: yup
          .string()
          .required(t("projects.validation.projectTimeRequired")),
      }),
    [t]
  );

  const handlePortfolioUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (!event.target.files) return;
    const files = Array.from(event.target.files);
    if (portfolio.length + files.length > 5) {
      toast.error(t("projects.portfolio.maxFiles"));
      return;
    }

    files.forEach((file) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        if (typeof reader.result === "string") {
          setPortfolio((prev) => [
            ...prev,
            {
              data: reader.result as string,
              type: file.type.startsWith("video/") ? "video" : "image",
            },
          ]);
        }
      };
    });
  };

  const formik = useFormik({
    initialValues: {
      offerPrice: "",
      projectTime: "",
    },
    validationSchema: schema,
    onSubmit: async (values) => {
      if (!Cookies.get("token")) {
        toast.error(t("projects.loginRequired"));
        return;
      }
      if (portfolioRequired && portfolio.length < 1) {
        toast.error(t("projects.portfolio.required"));
        return;
      }
      try {
        await request("POST", "/projects/request", {
          project_id: projectId,
          request_time: values.projectTime,
          offer_price: values.offerPrice,
          role_id: selectedRole?._id || null,
          portfolio,
        });
        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">
        {t("projects.ownProject")}
      </p>
    );
  }

  return (
    <form
      onSubmit={formik.handleSubmit}
      className="mx-auto my-5 flex w-full max-w-sm flex-col items-center"
    >
      {selectedRole ? (
        <div className="mb-3 w-full rounded-2xl border border-border-secondary-light p-3 text-xs dark:border-border-secondary-dark">
          <p className="font-bold">{selectedRole.expertise}</p>
          {selectedRole.sub_expertise?.length ? (
            <p className="mt-1 text-neutral-500">
              {selectedRole.sub_expertise.join(" _ ")}
            </p>
          ) : null}
          <p className="mt-1">
            {t("projects.newProject.fields.headcount")}:{" "}
            {selectedRole.number_of_person || 1}
          </p>
          {selectedRole.portfolio_required ? (
            <p className="mt-1 text-[#FF107D]">
              {t("projects.portfolio.requiredHint")}
            </p>
          ) : null}
        </div>
      ) : null}

      {(portfolioRequired || selectedRole?.portfolio_required) && (
        <div className="mb-3 w-full">
          <p className="mb-2 text-center text-xs font-semibold">
            {t("projects.portfolio.uploadTitle")}
          </p>
          <div className="flex flex-wrap gap-2">
            {portfolio.map((item, index) => (
              <div
                key={`${item.type}-${index}`}
                className="relative h-20 w-20 overflow-hidden rounded-lg border"
              >
                {item.type === "video" ? (
                  <video src={item.data} className="h-full w-full object-cover" />
                ) : (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img
                    src={item.data}
                    alt=""
                    className="h-full w-full object-cover"
                  />
                )}
                <button
                  type="button"
                  className="absolute right-1 top-1 rounded-full bg-black/50 px-1.5 text-xs text-white"
                  onClick={() =>
                    setPortfolio((prev) => prev.filter((_, i) => i !== index))
                  }
                >
                  ×
                </button>
              </div>
            ))}
            {portfolio.length < 5 && (
              <label className="flex h-20 w-20 cursor-pointer items-center justify-center rounded-lg border-2 border-dashed text-xl">
                <input
                  type="file"
                  multiple
                  accept="image/*,video/*"
                  className="hidden"
                  onChange={handlePortfolioUpload}
                />
                +
              </label>
            )}
          </div>
          <p className="mt-1 text-center text-[11px] text-neutral-500">
            {t("projects.portfolio.limits")}
          </p>
        </div>
      )}

      <RoundedInput
        type="number"
        name="projectTime"
        placeholder={t("projects.suggestedTimePlaceholder")}
        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={t("projects.offerPricePlaceholder")}
        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 type="submit" variant="primary" className="mt-6 px-8 py-2">
        {t("projects.submitRequest")}
      </RoundedButton>
    </form>
  );
}

export default ProjectRequestForm;
