"use client";

import Modal from "@/components/elements/Modal";
import RoundedButton from "@/components/elements/RoundedButton";
import RoundedDiv from "@/components/elements/RoundedDiv";
import UserInfo from "@/components/main/UserInfo";
import { buildStorageUrl } from "@/components/main/BaseUrl";
import useAxios from "@/hooks/useAxios";
import { IProjectRequest } from "@/types/types";
import Image from "next/image";
import { useRouter } from "next/navigation";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import BoldIcon from "@/components/ui/BoldIcon";

function ProjectRequestsAction({
  projectRequests,
  projectId,
  status,
}: {
  projectRequests: IProjectRequest[];
  projectId: string;
  status: string;
}) {
  const { t } = useTranslation("common");
  const { request } = useAxios();
  const router = useRouter();
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [itemToAccept, setItemToAccept] = useState<IProjectRequest>();
  const [viewerUrl, setViewerUrl] = useState<string | null>(null);
  const [viewerType, setViewerType] = useState<"image" | "video">("image");

  const canAccept = ![
    "ongoing",
    "done",
    "cancled",
    "pre_payment",
  ].includes(status);

  const acceptHandler = async () => {
    try {
      const response = await request<{ authority?: string; paymentUrl?: string }>(
        "POST",
        "/projects/payment-request-step-one/web",
        {
          requestId: itemToAccept?._id,
          projectId,
        }
      );
      if (response?.paymentUrl) {
        router.push(response.paymentUrl);
      } else if (response?.authority) {
        router.push(`https://www.zarinpal.com/pg/StartPay/${response.authority}`);
      }
    } catch (error: unknown) {
      console.log(error);
    }
  };

  const openMedia = (path: string, type: "image" | "video") => {
    setViewerUrl(buildStorageUrl(path));
    setViewerType(type);
  };

  return (
    <>
      {projectRequests
        ? projectRequests.map((item: IProjectRequest) => {
            return (
              <div
                key={item?._id}
                className={`my-4 flex w-full max-w-sm cursor-pointer items-center justify-between rounded-3xl p-2 md:max-w-md ${
                  item?.status === "accepted" ? "border border-[#0C8002]" : ""
                }`}
                onClick={() => {
                  setItemToAccept(item);
                  setShowConfirmModal(true);
                }}
              >
                <UserInfo
                  first_name={item?.user?.first_name}
                  is_verified={item?.user?.verify_badge}
                  userId={item?.user?._id}
                  profile_image={item?.user?.profile_image}
                  user_level={item?.user?.user_level}
                  last_name={item?.user?.last_name}
                  user_name={item?.user?.user_name}
                />

                <div className="flex flex-col items-start gap-1.5 text-[10px] sm:text-xs">
                  <span>
                    {t("projects.workroom.offerPrice", {
                      amount: Number(item?.price).toLocaleString(),
                    })}
                  </span>
                  <span>
                    {t("projects.workroom.suggestedTime", { days: item?.time })}
                  </span>
                  {item?.portfolio?.length ? (
                    <span className="text-[#FF107D]">
                      {t("projects.portfolio.count", {
                        count: item.portfolio.length,
                      })}
                    </span>
                  ) : null}
                  <div className="flex gap-3">
                    <div className="flex items-center justify-center gap-0.5">
                      <span>
                        {item?.user?.user_score ? item?.user?.user_score : "0"}
                      </span>
                      <Image
                        width={21}
                        height={21}
                        alt=""
                        src={`/images/icons/medal-star.png`}
                        className="pb-1"
                      />
                    </div>
                    <div className="flex items-center gap-0.5">
                      <span>{item?.user?.rate ? item?.user?.rate : "0"}</span>
                      <Image
                        width={21}
                        height={21}
                        alt=""
                        src={`/images/icons/star1.png`}
                        className="pb-1"
                      />
                    </div>
                  </div>
                </div>
              </div>
            );
          })
        : ""}
      {showConfirmModal && (
        <Modal
          isOpen={showConfirmModal}
          onClose={() => setShowConfirmModal(false)}
          height="fit"
          elevated
          panelClassName="max-h-[90vh] overflow-y-auto"
        >
          {itemToAccept && (
            <div className="mx-auto flex max-w-sm flex-col items-center gap-4 pt-4">
              <UserInfo
                first_name={itemToAccept?.user?.first_name}
                is_verified={itemToAccept?.user?.verify_badge}
                userId={itemToAccept?.user?._id}
                profile_image={itemToAccept?.user?.profile_image}
                user_level={itemToAccept?.user?.user_level}
                last_name={itemToAccept?.user?.last_name}
                user_name={itemToAccept?.user?.user_name}
              />
              <RoundedDiv className="mt-2 w-full p-2 text-xs">
                {t("projects.workroom.offerPrice", {
                  amount: Number(itemToAccept?.price).toLocaleString(),
                })}
              </RoundedDiv>
              <RoundedDiv className="w-full p-2 text-xs">
                {t("projects.workroom.suggestedTime", {
                  days: itemToAccept?.time,
                })}
              </RoundedDiv>

              {itemToAccept.portfolio?.length ? (
                <div className="w-full">
                  <p className="mb-2 text-center text-xs font-semibold">
                    {t("projects.portfolio.uploadTitle")}
                  </p>
                  <div className="flex flex-wrap justify-center gap-2">
                    {itemToAccept.portfolio.map((file, index) => {
                      const url = buildStorageUrl(file.path);
                      return (
                        <button
                          key={`${file.path}-${index}`}
                          type="button"
                          className="relative h-20 w-20 overflow-hidden rounded-lg border"
                          onClick={(e) => {
                            e.stopPropagation();
                            openMedia(file.path, file.type);
                          }}
                        >
                          {file.type === "video" ? (
                            <video
                              src={url}
                              className="h-full w-full object-cover"
                              muted
                            />
                          ) : (
                            // eslint-disable-next-line @next/next/no-img-element
                            <img
                              src={url}
                              alt=""
                              className="h-full w-full object-cover"
                            />
                          )}
                        </button>
                      );
                    })}
                  </div>
                </div>
              ) : null}

              {canAccept ? (
                <RoundedButton
                  onClick={() => {
                    void acceptHandler();
                    setShowConfirmModal(false);
                  }}
                  className="mt-3 w-full p-2 text-sm"
                >
                  {t("projects.workroom.accept")}
                </RoundedButton>
              ) : null}
            </div>
          )}
        </Modal>
      )}

      {viewerUrl ? (
        <div
          className="fixed inset-0 z-[300] flex items-center justify-center bg-black/90"
          onClick={() => setViewerUrl(null)}
        >
          <button
            type="button"
            className="absolute left-4 top-4 z-10 flex h-10 w-10 items-center justify-center rounded-full bg-white/15 text-white"
            onClick={() => setViewerUrl(null)}
            aria-label={t("projects.specialists.close")}
          >
            <BoldIcon name="close-circle" size={24} tinted className="text-white" />
          </button>
          <div
            className="relative max-h-[90vh] max-w-[92vw]"
            onClick={(e) => e.stopPropagation()}
          >
            {viewerType === "video" ? (
              <video
                src={viewerUrl}
                controls
                autoPlay
                className="max-h-[90vh] max-w-[92vw] rounded-xl"
              />
            ) : (
              // eslint-disable-next-line @next/next/no-img-element
              <img
                src={viewerUrl}
                alt=""
                className="max-h-[90vh] max-w-[92vw] rounded-xl object-contain"
              />
            )}
          </div>
        </div>
      ) : null}
    </>
  );
}

export default ProjectRequestsAction;
