"use client";

import Container from "@/components/elements/Container";
import { IProjectType, Project } from "@/types/types";
import useAxios from "@/hooks/useAxios";
import React, { useEffect, useState } from "react";
import MainProjectCard from "@/components/projects/MainProjectCard";
import RoundedDiv from "@/components/elements/RoundedDiv";
import RoundedButton from "@/components/elements/RoundedButton";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import { useTranslation } from "react-i18next";
import toast from "react-hot-toast";
import { AxiosError } from "axios";

interface ProjectPaymentProps {
  params: Promise<{ id: string }>;
}

function ProjectPaymentPage({ params }: ProjectPaymentProps) {
  const { t } = useTranslation("common");
  const resolvedParams = React.use(params);
  const { request, loading } = useAxios();
  const { id } = resolvedParams;
  const [project, setProject] = useState<Project>();
  const [typeList, setTypeList] = useState<IProjectType[] | null>(null);
  const [price, setPrice] = useState("");
  const [paying, setPaying] = useState(false);

  const getDisplayTypeLabel = (projectType?: string) => {
    if (projectType === "normal" || projectType === "free") {
      return t("projects.newProject.displaySimple");
    }
    if (projectType === "force") {
      return t("projects.newProject.displayUrgent");
    }
    return t("projects.newProject.displayHighlight");
  };

  useEffect(() => {
    const fetchProject = async () => {
      try {
        const response = await request<{ project: Project }>(
          "GET",
          `/projects/get/web/${id}`
        );
        setProject(response?.project);
      } catch {
        toast.error(t("projects.notFound"));
      }
    };
    const fetchTypes = async () => {
      try {
        const response = await request<{ projectTypes: IProjectType[] }>(
          "GET",
          "/projects/types"
        );
        setTypeList(response?.projectTypes || null);
      } catch (err) {
        console.log(err);
      }
    };
    void fetchProject();
    void fetchTypes();
  }, [id, request, t]);

  useEffect(() => {
    if (project?.project_type && typeList) {
      const foundType = typeList.find(
        (item) => item.name === project.project_type
      );
      if (foundType) setPrice(String(foundType.price));
    }
  }, [project, typeList]);

  const payHandler = async () => {
    if (paying || !project?._id) return;
    setPaying(true);
    try {
      const itemName = project.project_type || "normal";
      const response = await request<{
        authority?: string;
        type?: string;
        message?: string;
      }>(
        "POST",
        "/projects/initiate-payment-web",
        {
          item_name: itemName,
          projectId: id,
        },
        { noToast: true }
      );

      if (response?.type === "free" || itemName === "free") {
        window.location.href = `/projects/payment/success?projectId=${id}`;
        return;
      }

      const authority = response?.authority;
      if (authority) {
        // لینک خارجی — router.push ممکن است در سافاری/نکست کار نکند
        window.location.href = `https://www.zarinpal.com/pg/StartPay/${authority}`;
        return;
      }

      toast.error(response?.message || t("projects.payment.initFailed"));
    } catch (error: unknown) {
      const axiosErr = error as AxiosError<{ message?: string }>;
      const serverMsg = axiosErr?.response?.data?.message;
      console.log(error);
      toast.error(serverMsg || t("projects.payment.initFailed"));
    } finally {
      setPaying(false);
    }
  };

  return (
    <LocalePageShell>
      <Container>
        <h6 className="mb-4 mt-2 line-clamp-2 text-center text-lg font-bold text-text-blue-light dark:text-text-blue-dark md:text-xl">
          {t("projects.payment.title")}
        </h6>
        <div className="mt-10 w-full px-4 text-sm font-semibold md:text-base">
          {project && <MainProjectCard project={project} />}
          <div className="mt-4 flex flex-col items-center gap-4">
            <RoundedDiv className="w-full p-2">
              {getDisplayTypeLabel(project?.project_type)}:{" "}
              {Number(price || 0).toLocaleString()} {t("settings.toman")}
            </RoundedDiv>
            <RoundedDiv className="w-full p-2">
              {t("projects.payment.payableAmount", {
                amount: Number(price || 0).toLocaleString(),
              })}
            </RoundedDiv>
            <RoundedButton
              type="button"
              variant="primary"
              onClick={() => void payHandler()}
              disabled={paying || loading || !project}
              className="h-9 w-32"
            >
              {paying
                ? t("common.loading")
                : t("projects.payment.title")}
            </RoundedButton>
          </div>
        </div>
      </Container>
    </LocalePageShell>
  );
}

export default ProjectPaymentPage;
