/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import Container from "@/components/elements/Container";
import RoundedButton from "@/components/elements/RoundedButton";
import RoundedDiv from "@/components/elements/RoundedDiv";
import { selectionCardClass } from "@/lib/ui/buttonStyles";
import { BASE_URL } from "@/components/main/BaseUrl";
import UserInfo from "@/components/main/UserInfo";
import PageTitle from "@/components/settings/PageTitle";
import useAxios from "@/hooks/useAxios";
import { IOfferType, User } from "@/types/types";
import axios from "axios";
import { useFormik } from "formik";
import Image from "next/image";
import { useRouter } from "next/navigation";
import React, { useState, useEffect, useMemo } from "react";
import toast from "react-hot-toast";
import Cookies from "js-cookie";
import * as Yup from "yup";
import { useTranslation } from "react-i18next";
import { useUser } from "@/hooks/useUser";
type OfferTypeRow = IOfferType & {
  disabled?: boolean;
  unavailableReason?: string | null;
};

interface ITicketChatProps {
  params: Promise<{ id: string; title: string }>;
}

const FALLBACK_TYPES: OfferTypeRow[] = [
  { _id: "normal", name: "normal", price: 50000 },
  { _id: "free", name: "free", price: 0 },
];

function sortOfferTypes(list: OfferTypeRow[]): OfferTypeRow[] {
  const order = ["normal", "special", "highlight", "free"];
  return [...list].sort((a, b) => {
    const ai = order.indexOf(a.name);
    const bi = order.indexOf(b.name);
    return (ai === -1 ? 99 : ai) - (bi === -1 ? 99 : bi);
  });
}

function TicketChat({ params }: ITicketChatProps) {
  const { t } = useTranslation("common");
  const resolvedParams = React.use(params);
  const { request } = useAxios();
  const { id } = resolvedParams;
  const router = useRouter();
  const me = useUser();

  const validationSchema = Yup.object({
    selectedType: Yup.string().required(t("offerPage.typeRequired")),
  });

  const [userDetail, setUserDetail] = useState<User>();
  const [selectedType, setSelectedType] = useState("normal");
  const [typeList, setTypeList] = useState<OfferTypeRow[] | null>(null);
  const [hasUsedFreeOffer, setHasUsedFreeOffer] = useState(false);

  useEffect(() => {
    const fetchUser = async () => {
      const response = await request<{ user: User }>(
        "GET",
        `/users/get?user_id=${id}`
      );
      setUserDetail(response?.user);
    };
    void fetchUser();
  }, [id, request]);

  useEffect(() => {
    const monthly = Number(me?.monthly_free_offer ?? 1);
    setHasUsedFreeOffer(monthly <= 0);
  }, [me]);

  const fetchOfferTypes = async () => {
    try {
      const response = await request<{
        offerTypes: OfferTypeRow[];
        monthly_free_offer?: number;
      }>("GET", "/offers/types");
      const list = sortOfferTypes(
        response?.offerTypes?.length ? response.offerTypes : FALLBACK_TYPES
      );
      setTypeList(list);
      if (typeof response?.monthly_free_offer === "number") {
        setHasUsedFreeOffer(response.monthly_free_offer <= 0);
      }
      // همیشه پیش‌فرض روی پولی (normal)
      const paid =
        list.find((item) => item.name === "normal" && !item.disabled) ||
        list.find((item) => item.name !== "free" && !item.disabled);
      setSelectedType(paid?.name || "normal");
    } catch (err) {
      console.log(err);
      setTypeList(FALLBACK_TYPES);
      setSelectedType("normal");
    }
  };

  useEffect(() => {
    void fetchOfferTypes();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const formik = useFormik({
    initialValues: {
      selectedType: "normal",
    },
    validationSchema,
    enableReinitialize: true,
    onSubmit: async (values, { setSubmitting }) => {
      const chosen = typeList?.find((t) => t.name === values.selectedType);
      if (
        chosen?.disabled ||
        (values.selectedType === "free" && hasUsedFreeOffer)
      ) {
        toast.error(
          chosen?.unavailableReason || t("offerPage.freeAlreadyUsed")
        );
        return;
      }

      const getToken = (): string => {
        if (typeof window !== "undefined") {
          const token = Cookies.get("token");
          return token ? `Bearer ${token}` : "";
        }
        return "";
      };

      try {
        const response = await axios.post(
          `${BASE_URL}/offers/initiate-payment-web`,
          {
            offerType: values.selectedType,
            receiverId: id,
          },
          {
            headers: {
              Authorization: getToken(),
              "Content-Type": "application/json",
            },
          }
        );

        const data: {
          authority?: string;
          paymentUrl?: string;
          type?: string;
        } = response.data;

        if (values.selectedType === "free" || data.type === "free") {
          toast.success(t("offerPage.freeSuccess"));
          setHasUsedFreeOffer(true);
          router.push(`/offer/payment/success?userId=${id}`);
        } else if (data.paymentUrl) {
          window.open(data.paymentUrl, "_blank", "noopener,noreferrer");
        } else if (data.authority) {
          window.open(
            `https://www.zarinpal.com/pg/StartPay/${data.authority}`,
            "_blank",
            "noopener,noreferrer"
          );
        } else {
          toast.error(t("offerPage.paymentInfoError"));
        }
      } catch (err: any) {
        console.error("Payment initiation error:", err);
        toast.error(
          err?.response?.data?.error ||
            err?.response?.data?.message ||
            t("offerPage.paymentStartError")
        );
      } finally {
        setSubmitting(false);
      }
    },
  });

  useEffect(() => {
    void formik.setFieldValue("selectedType", selectedType);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedType]);

  const displayTypes = useMemo(
    () => sortOfferTypes(typeList || FALLBACK_TYPES),
    [typeList]
  );

  const typeLabel = (name: string) => {
    if (name === "normal") return t("offerPage.types.normal");
    if (name === "free") return t("offerPage.types.free");
    if (name === "special") return t("offerPage.types.special");
    return t("offerPage.types.highlight");
  };

  const userHeader = userDetail ? (
    <div className="flex w-full items-end justify-between">
      <UserInfo
        first_name={userDetail?.first_name}
        is_verified={userDetail?.verify_badge}
        userId={userDetail?._id}
        profile_image={userDetail?.profile_image}
        user_level={userDetail?.user_level}
        last_name={userDetail?.last_name}
        user_name={userDetail?.user_name}
        noLink
      />
      <div className="flex items-center justify-center gap-0.5">
        <span>{userDetail?.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>{userDetail?.rate || "0"}</span>
        <Image
          width={21}
          height={21}
          alt=""
          src={`/images/icons/star1.png`}
          className="pb-1"
        />
      </div>
    </div>
  ) : null;

  return (
    <Container>
      <div className="mx-3 mb-10">
        <PageTitle>{t("offerPage.paymentTitle")}</PageTitle>

        <form
          className="flex w-full flex-col items-center gap-2 text-sm"
          onSubmit={formik.handleSubmit}
        >
          {displayTypes.map((item) => {
            const isFree = item.name === "free";
            const isDisabled =
              Boolean(item.disabled) || (isFree && hasUsedFreeOffer);

            return (
              <div
                key={item?._id || item.name}
                className="mt-8 flex w-full max-w-md cursor-pointer flex-col items-center gap-4"
                onClick={() => {
                  if (isDisabled) return;
                  setSelectedType(item.name);
                  void formik.setFieldValue("selectedType", item.name);
                }}
              >
                {userHeader}
                <RoundedDiv
                  className={`${selectionCardClass(selectedType === item?.name)} ${
                    isDisabled ? "cursor-not-allowed opacity-50" : ""
                  }`}
                >
                  {typeLabel(item.name)}
                  {Number(item.price) !== 0
                    ? ": " +
                      Number(item.price).toLocaleString() +
                      t("offerPage.currencySuffix")
                    : ""}
                </RoundedDiv>
                {isDisabled && item.unavailableReason ? (
                  <p className="text-center text-[11px] text-red-500">
                    {item.unavailableReason}
                  </p>
                ) : null}
              </div>
            );
          })}

          <RoundedButton
            type="submit"
            variant="primary"
            className="mt-4 px-8 py-2"
            disabled={formik.isSubmitting}
          >
            {t("offerPage.submitRequest")}
          </RoundedButton>
        </form>
      </div>
    </Container>
  );
}

export default TicketChat;
