"use client";

import Container from "@/components/elements/Container";
import RoundedButton from "@/components/elements/RoundedButton";
import RoundedInput from "@/components/elements/RoundedInput";
import UserInfo from "@/components/main/UserInfo";
import PageTitle from "@/components/settings/PageTitle";
import useAxios from "@/hooks/useAxios";
import { filterChipClass } from "@/lib/ui/buttonStyles";
import { User } from "@/types/types";
import React, { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

const PRESET_AMOUNTS = [2000, 5000, 10000, 15000, 20000, 50000, 100000];
const CUSTOM_MIN = 5000;
const CUSTOM_MAX = 100000000;

interface GiftPageProps {
  params: Promise<{ userId: string }>;
}

function GiftPage({ params }: GiftPageProps) {
  const { t } = useTranslation("common");
  const { userId } = React.use(params);
  const { request } = useAxios();
  const router = useRouter();

  const [userDetail, setUserDetail] = useState<User>();
  const [selectedAmount, setSelectedAmount] = useState<number | null>(
    PRESET_AMOUNTS[0]
  );
  const [customAmount, setCustomAmount] = useState("");
  const [isCustom, setIsCustom] = useState(false);
  const [message, setMessage] = useState("");
  const [submitting, setSubmitting] = useState(false);

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

  const finalAmount = useMemo(() => {
    if (isCustom) return Number(customAmount) || 0;
    return selectedAmount || 0;
  }, [isCustom, customAmount, selectedAmount]);

  const isCustomValid =
    !isCustom ||
    (Number(customAmount) >= CUSTOM_MIN && Number(customAmount) <= CUSTOM_MAX);

  const canSubmit = finalAmount > 0 && isCustomValid && !submitting;

  const handleSubmit = async () => {
    if (!canSubmit) return;
    setSubmitting(true);
    try {
      const response = await request<{ authority?: string; paymentUrl?: string }>(
        "POST",
        "/gifts/initiate",
        { receiverId: userId, amount: finalAmount, message }
      );
      if (response?.paymentUrl) {
        router.push(response.paymentUrl);
      } else if (response?.authority) {
        router.push(`https://www.zarinpal.com/pg/StartPay/${response.authority}`);
      } else {
        toast.error(t("giftPage.paymentInfoError"));
      }
    } catch (err: unknown) {
      const message2 =
        (err as { response?: { data?: { message?: string } } })?.response
          ?.data?.message || t("giftPage.paymentStartError");
      toast.error(message2);
    } finally {
      setSubmitting(false);
    }
  };

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

        {userDetail ? (
          <div className="mt-4 flex justify-center">
            <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>
        ) : null}

        <div className="mx-auto mt-8 flex w-full max-w-md flex-wrap justify-center gap-2">
          {PRESET_AMOUNTS.map((amount) => (
            <button
              key={amount}
              type="button"
              onClick={() => {
                setIsCustom(false);
                setSelectedAmount(amount);
              }}
              className={filterChipClass(!isCustom && selectedAmount === amount)}
            >
              {amount.toLocaleString()} {t("settings.toman")}
            </button>
          ))}
          <button
            type="button"
            onClick={() => setIsCustom(true)}
            className={filterChipClass(isCustom)}
          >
            {t("giftPage.customAmount")}
          </button>
        </div>

        {isCustom ? (
          <div className="mx-auto mt-4 w-full max-w-md">
            <RoundedInput
              type="number"
              inputMode="numeric"
              placeholder={t("giftPage.customAmountPlaceholder", {
                min: CUSTOM_MIN.toLocaleString(),
                max: CUSTOM_MAX.toLocaleString(),
              })}
              value={customAmount}
              onChange={(e) => setCustomAmount(e.target.value)}
            />
            {!isCustomValid && customAmount ? (
              <p className="mt-2 text-center text-xs text-red-500">
                {t("giftPage.customAmountInvalid", {
                  min: CUSTOM_MIN.toLocaleString(),
                  max: CUSTOM_MAX.toLocaleString(),
                })}
              </p>
            ) : null}
          </div>
        ) : null}

        <div className="mx-auto mt-6 w-full max-w-md">
          <textarea
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            placeholder={t("giftPage.messagePlaceholder")}
            rows={3}
            maxLength={500}
            className="w-full resize-none rounded-3xl border border-border-secondary-light bg-secondary-light p-4 font-medium dark:border-border-secondary-dark dark:bg-secondary-dark"
          />
        </div>

        <div className="mt-8 flex justify-center">
          <RoundedButton
            type="button"
            variant="primary"
            className="px-8 py-2"
            disabled={!canSubmit}
            onClick={() => void handleSubmit()}
          >
            {t("giftPage.payButton")}
          </RoundedButton>
        </div>
      </div>
    </Container>
  );
}

export default GiftPage;
