"use client";

import Container from "@/components/elements/Container";
import RoundedButton from "@/components/elements/RoundedButton";
import RoundedInput from "@/components/elements/RoundedInput";
import PageTitle from "@/components/settings/PageTitle";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import useAxios from "@/hooks/useAxios";
import { toggleBtnClass } from "@/lib/ui/buttonStyles";
import { cn } from "@/lib/utils";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

const BUCKET_SHOP = "shop";
const BUCKET_GIFT = "gift";
const BUCKET_CHARGED = "charged";
const BUCKET_ACADEMY = "academy";
const BUCKET_PROJECT = "project";
const BUCKET_BOOKING = "booking";

type WalletSummary = {
  shop: { available: number; pending: number };
  gift: { available: number; minWithdrawal: number };
  charged: { available: number };
  academy: { available: number };
  project: { available: number };
  booking: { available: number };
};

export default function WalletSettingsPage() {
  const { t } = useTranslation("common");
  const router = useRouter();
  const searchParams = useSearchParams();
  const { request, loading } = useAxios();

  const [bucket, setBucket] = useState<string>(BUCKET_SHOP);
  const [summary, setSummary] = useState<WalletSummary | null>(null);
  const [withdrawAmount, setWithdrawAmount] = useState("");
  const [chargeAmount, setChargeAmount] = useState("");

  const loadSummary = () => {
    request<WalletSummary>("GET", "/wallet/summary")
      .then((res) => setSummary(res))
      .catch(() => setSummary(null));
  };

  useEffect(() => {
    loadSummary();
    const charge = searchParams.get("charge");
    if (charge === "success") toast.success(t("shops.paymentSuccessTitle"));
    if (charge === "failed") toast.error(t("shops.paymentFailedTitle"));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const totalBalance =
    (summary?.shop.available || 0) +
    (summary?.gift.available || 0) +
    (summary?.charged.available || 0) +
    (summary?.academy.available || 0) +
    (summary?.project.available || 0) +
    (summary?.booking.available || 0);

  const handleWithdraw = async () => {
    const amount = Number(withdrawAmount);
    if (!amount || amount <= 0) return;
    try {
      await request("POST", "/wallet/withdraw", { bucket, amount });
      toast.success(t("shops.withdrawalRequested"));
      setWithdrawAmount("");
      loadSummary();
    } catch (err: unknown) {
      const message =
        (err as { response?: { data?: { message?: string } } })?.response
          ?.data?.message || t("shops.unknownError");
      toast.error(message);
    }
  };

  const handleCharge = async () => {
    const amount = Number(chargeAmount);
    if (!amount || amount <= 0) return;
    try {
      const response = await request<{ authority?: string }>(
        "POST",
        "/wallet/charge/initiate",
        { amount }
      );
      if (response?.authority) {
        router.push(`https://www.zarinpal.com/pg/StartPay/${response.authority}`);
      }
    } catch (err: unknown) {
      const message =
        (err as { response?: { data?: { message?: string } } })?.response
          ?.data?.message || t("shops.unknownError");
      toast.error(message);
    }
  };

  return (
    <LocalePageShell>
      <Container>
        <PageTitle>{t("settings.nav.wallet")}</PageTitle>

        <div className="mx-auto mt-4 max-w-md text-center">
          <p className="text-xs text-neutral-500">{t("shops.totalBalance")}</p>
          <p className="text-2xl font-bold">
            {totalBalance.toLocaleString()} {t("settings.toman")}
          </p>
        </div>

        <div className="mx-auto mt-6 grid w-full max-w-md grid-cols-3 gap-2">
          <RoundedButton
            className={cn(toggleBtnClass(bucket === BUCKET_SHOP), "h-9 text-xs")}
            onClick={() => setBucket(BUCKET_SHOP)}
          >
            {t("shops.walletShopTab")}
          </RoundedButton>
          <RoundedButton
            className={cn(toggleBtnClass(bucket === BUCKET_GIFT), "h-9 text-xs")}
            onClick={() => setBucket(BUCKET_GIFT)}
          >
            {t("shops.walletGiftTab")}
          </RoundedButton>
          <RoundedButton
            className={cn(toggleBtnClass(bucket === BUCKET_CHARGED), "h-9 text-xs")}
            onClick={() => setBucket(BUCKET_CHARGED)}
          >
            {t("shops.walletChargedTab")}
          </RoundedButton>
          <RoundedButton
            className={cn(toggleBtnClass(bucket === BUCKET_ACADEMY), "h-9 text-xs")}
            onClick={() => setBucket(BUCKET_ACADEMY)}
          >
            {t("shops.walletAcademyTab")}
          </RoundedButton>
          <RoundedButton
            className={cn(toggleBtnClass(bucket === BUCKET_PROJECT), "h-9 text-xs")}
            onClick={() => setBucket(BUCKET_PROJECT)}
          >
            {t("shops.walletProjectTab")}
          </RoundedButton>
          <RoundedButton
            className={cn(toggleBtnClass(bucket === BUCKET_BOOKING), "h-9 text-xs")}
            onClick={() => setBucket(BUCKET_BOOKING)}
          >
            {t("shops.walletBookingTab")}
          </RoundedButton>
        </div>

        <div className="mx-auto mt-6 max-w-md text-sm">
          {bucket === BUCKET_SHOP && summary && (
            <>
              <div className="flex justify-between">
                <span>{t("shops.availableToWithdraw")}</span>
                <span className="font-bold">
                  {summary.shop.available.toLocaleString()} {t("settings.toman")}
                </span>
              </div>
              <div className="mt-1 flex justify-between text-neutral-500">
                <span>{t("shops.pendingConfirmation")}</span>
                <span>
                  {summary.shop.pending.toLocaleString()} {t("settings.toman")}
                </span>
              </div>
              <div className="mt-4 flex gap-2">
                <RoundedInput
                  type="number"
                  inputMode="numeric"
                  placeholder={t("shops.withdrawAmountPlaceholder")}
                  value={withdrawAmount}
                  onChange={(e) => setWithdrawAmount(e.target.value)}
                />
                <RoundedButton
                  variant="primary"
                  disabled={loading}
                  onClick={handleWithdraw}
                >
                  {t("shops.requestWithdrawal")}
                </RoundedButton>
              </div>
            </>
          )}

          {bucket === BUCKET_GIFT && summary && (
            <>
              <div className="flex justify-between">
                <span>{t("shops.giftBalance")}</span>
                <span className="font-bold">
                  {summary.gift.available.toLocaleString()} {t("settings.toman")}
                </span>
              </div>
              <p className="mt-1 text-xs text-neutral-500">
                {t("shops.giftMinWithdrawalHint", {
                  amount: summary.gift.minWithdrawal.toLocaleString(),
                })}
              </p>
              <div className="mt-4 flex gap-2">
                <RoundedInput
                  type="number"
                  inputMode="numeric"
                  placeholder={t("shops.withdrawAmountPlaceholder")}
                  value={withdrawAmount}
                  onChange={(e) => setWithdrawAmount(e.target.value)}
                />
                <RoundedButton
                  variant="primary"
                  disabled={loading || summary.gift.available < summary.gift.minWithdrawal}
                  onClick={handleWithdraw}
                >
                  {t("shops.requestWithdrawal")}
                </RoundedButton>
              </div>
            </>
          )}

          {bucket === BUCKET_ACADEMY && summary && (
            <>
              <div className="flex justify-between">
                <span>{t("shops.academyBalance")}</span>
                <span className="font-bold">
                  {summary.academy.available.toLocaleString()} {t("settings.toman")}
                </span>
              </div>
              <div className="mt-4 flex gap-2">
                <RoundedInput
                  type="number"
                  inputMode="numeric"
                  placeholder={t("shops.withdrawAmountPlaceholder")}
                  value={withdrawAmount}
                  onChange={(e) => setWithdrawAmount(e.target.value)}
                />
                <RoundedButton
                  variant="primary"
                  disabled={loading}
                  onClick={handleWithdraw}
                >
                  {t("shops.requestWithdrawal")}
                </RoundedButton>
              </div>
            </>
          )}

          {bucket === BUCKET_PROJECT && summary && (
            <>
              <div className="flex justify-between">
                <span>{t("shops.projectBalance")}</span>
                <span className="font-bold">
                  {summary.project.available.toLocaleString()} {t("settings.toman")}
                </span>
              </div>
              <div className="mt-4 flex gap-2">
                <RoundedInput
                  type="number"
                  inputMode="numeric"
                  placeholder={t("shops.withdrawAmountPlaceholder")}
                  value={withdrawAmount}
                  onChange={(e) => setWithdrawAmount(e.target.value)}
                />
                <RoundedButton
                  variant="primary"
                  disabled={loading}
                  onClick={handleWithdraw}
                >
                  {t("shops.requestWithdrawal")}
                </RoundedButton>
              </div>
            </>
          )}

          {bucket === BUCKET_BOOKING && summary && (
            <>
              <div className="flex justify-between">
                <span>{t("shops.bookingBalance")}</span>
                <span className="font-bold">
                  {summary.booking.available.toLocaleString()} {t("settings.toman")}
                </span>
              </div>
              <div className="mt-4 flex gap-2">
                <RoundedInput
                  type="number"
                  inputMode="numeric"
                  placeholder={t("shops.withdrawAmountPlaceholder")}
                  value={withdrawAmount}
                  onChange={(e) => setWithdrawAmount(e.target.value)}
                />
                <RoundedButton
                  variant="primary"
                  disabled={loading}
                  onClick={handleWithdraw}
                >
                  {t("shops.requestWithdrawal")}
                </RoundedButton>
              </div>
            </>
          )}

          {bucket === BUCKET_CHARGED && summary && (
            <>
              <div className="flex justify-between">
                <span>{t("shops.chargedBalance")}</span>
                <span className="font-bold">
                  {summary.charged.available.toLocaleString()} {t("settings.toman")}
                </span>
              </div>
              <p className="mt-1 text-xs text-neutral-500">{t("shops.chargeBonusHint")}</p>
              <div className="mt-4 flex gap-2">
                <RoundedInput
                  type="number"
                  inputMode="numeric"
                  placeholder={t("shops.chargeAmountPlaceholder")}
                  value={chargeAmount}
                  onChange={(e) => setChargeAmount(e.target.value)}
                />
                <RoundedButton variant="primary" disabled={loading} onClick={handleCharge}>
                  {t("shops.chargeWallet")}
                </RoundedButton>
              </div>
            </>
          )}
        </div>
      </Container>
    </LocalePageShell>
  );
}
