"use client";

import { useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import Modal from "@/components/elements/Modal";
import RoundedButton from "@/components/elements/RoundedButton";
import RoundedInput from "@/components/elements/RoundedInput";
import useAxios from "@/hooks/useAxios";
import { filterChipClass } from "@/lib/ui/buttonStyles";
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;

type GiftChatResponse = {
  paidFromWallet: boolean;
  authority?: string;
  paymentUrl?: string;
  gift?: { _id: string; amount: number; message: string | null };
};

type GiftInChatModalProps = {
  open: boolean;
  onClose: () => void;
  receiverId: string;
  returnPath: string;
  onWalletGiftSent: (gift: { _id: string; amount: number; message: string | null }) => void;
};

export default function GiftInChatModal({
  open,
  onClose,
  receiverId,
  returnPath,
  onWalletGiftSent,
}: GiftInChatModalProps) {
  const { t } = useTranslation("common");
  const { request } = useAxios();
  const router = useRouter();

  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);

  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 reset = () => {
    setSelectedAmount(PRESET_AMOUNTS[0]);
    setCustomAmount("");
    setIsCustom(false);
    setMessage("");
  };

  const handleSubmit = async () => {
    if (!canSubmit) return;
    setSubmitting(true);
    try {
      const response = await request<GiftChatResponse>(
        "POST",
        "/gifts/chat/initiate",
        { receiverId, amount: finalAmount, message, return_path: returnPath }
      );
      if (response?.paidFromWallet && response.gift) {
        toast.success(t("chats.gift.sentSuccess"));
        onWalletGiftSent(response.gift);
        reset();
        onClose();
      } else if (response?.paymentUrl) {
        router.push(response.paymentUrl);
      } else {
        toast.error(t("giftPage.paymentInfoError"));
      }
    } catch (err: unknown) {
      const msg =
        (err as { response?: { data?: { message?: string } } })?.response?.data
          ?.message || t("giftPage.paymentStartError");
      toast.error(msg);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Modal
      isOpen={open}
      onClose={onClose}
      height="fit"
      elevated
      panelClassName="!p-0 max-h-[85dvh] w-full overflow-y-auto"
    >
      <div className="px-4 pb-6 pt-5">
        <h3 className="mb-4 text-center text-sm font-bold">
          {t("chats.gift.modalTitle")}
        </h3>

        <div className="mx-auto flex w-full max-w-sm 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-sm">
            <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-4 w-full max-w-sm">
          <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 text-sm font-medium dark:border-border-secondary-dark dark:bg-secondary-dark"
          />
        </div>

        <div className="mt-5 flex justify-center">
          <RoundedButton
            type="button"
            variant="primary"
            className="h-10 w-40"
            disabled={!canSubmit}
            onClick={() => void handleSubmit()}
          >
            {submitting ? t("chats.gift.sending") : t("giftPage.payButton")}
          </RoundedButton>
        </div>
      </div>
    </Modal>
  );
}
