"use client";

import React, { useState, useRef } from "react";
import { useRouter } from "next/navigation";
import { m } from "framer-motion";
import DOMPurify from "dompurify";
import {
  ArrowDownLeft,
  Wallet,
  AlertCircle,
  CheckCircle2,
  ChevronRight,
  Upload,
  Loader2,
  Search,
  ScrollText,
  ArrowRight,
} from "lucide-react";
import Select from "react-select";
import { SEARCHABLE_SELECT_COMPONENTS } from "@/components/common/SearchableSelectParts";
import { Container } from "@/components/common/Container";
import { Button } from "@/components/common/Button";
import { cn } from "@/lib/utils";
import { notify } from "@/lib/notify";
import {
  useMoneyInData,
  useMoneyInSubmit,
  useMoneyInManualFields,
  useMoneyInManualSubmit,
  useMoneyInConfirm,
  type MoneyInTempData,
} from "@/hooks/queries/useAgentMoneyIn";
import { useAgentTransactions } from "@/hooks/queries/useAgentDashboard";
import { useTranslation } from "@/hooks/useTranslation";
import { useAgentKycGate } from "@/hooks/useAgentKycGate";
import { AgentKycGate } from "@/components/agent/AgentKycGate";
import { useControlledSelectMenu } from "@/hooks/useControlledSelectMenu";

// ─── Animations ────────────────────────────────────────────────────────────────

const containerVariants = {
  hidden: { opacity: 0 },
  visible: {
    opacity: 1,
    transition: { staggerChildren: 0.08, delayChildren: 0.05 },
  },
};

const itemVariants = {
  hidden: { opacity: 0, y: 15 },
  visible: { opacity: 1, y: 0, transition: { type: "spring", stiffness: 300, damping: 24 } },
};

// ─── Select styles ─────────────────────────────────────────────────────────────

const SELECT_CLS = {
  control: ({ menuIsOpen }: { menuIsOpen: boolean }) =>
    cn(
      "h-12 w-full rounded-xl border border-slate-200/80 bg-white px-2 text-sm font-medium text-slate-900 outline-none transition-all hover:border-slate-300 dark:border-slate-700/60 dark:bg-slate-900/80 dark:text-white cursor-pointer !min-h-12 shadow-sm transition-[border-radius] duration-150 [&_input]:border-0 [&_input]:outline-none [&_input]:shadow-none [&_input]:bg-transparent",
      menuIsOpen && "rounded-b-none",
    ),
  menu: () =>
    "select-menu-portal overflow-hidden rounded-b-xl border border-t-0 border-slate-200 bg-white shadow-2xl dark:border-slate-700 dark:bg-slate-900 z-50",
  menuList: () => "max-h-52 overflow-y-auto",
  option: ({ isFocused }: { isFocused: boolean }) =>
    cn(
      "px-3 py-2.5 text-sm cursor-pointer transition-colors",
      isFocused
        ? "bg-brand-50 text-brand-700 dark:bg-brand-500/15 dark:text-brand-300 font-semibold"
        : "text-slate-700 dark:text-slate-300 font-medium",
    ),
  placeholder: () => "text-slate-400 text-sm font-medium",
  singleValue: () => "text-sm font-semibold text-slate-800 dark:text-slate-100",
  input: () => "text-sm font-semibold text-slate-800 dark:text-slate-100",
  valueContainer: () => "px-0",
  dropdownIndicator: () => "cursor-pointer",
};

const SELECT_STYLES = {
  input: (base: object) => ({ ...base, outline: "none", boxShadow: "none", border: "none", caretColor: "transparent" }),
  menuPortal: (base: object) => ({ ...base, zIndex: 9999 }),
};

const INPUT_CLS =
  "h-12 w-full rounded-xl border border-slate-200/80 bg-white px-4 text-sm font-bold text-slate-900 outline-none transition-all hover:border-slate-300 focus:border-brand-500 focus:ring-4 focus:ring-brand-500/10 dark:border-slate-700/60 dark:bg-slate-900/80 dark:text-white dark:focus:border-brand-400 shadow-sm";

// ─── Helpers ───────────────────────────────────────────────────────────────────

const STATUS_MAP: Record<string, string> = {
  completed: "bg-emerald-50 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-400",
  pending: "bg-amber-50 text-amber-700 dark:bg-amber-500/10 dark:text-amber-400",
  failed: "bg-rose-50 text-rose-700 dark:bg-rose-500/10 dark:text-rose-400",
  cancel: "bg-rose-50 text-rose-700 dark:bg-rose-500/10 dark:text-rose-400",
};

// ─── Components ───────────────────────────────────────────────────────────────

function SummaryRow({ label, value, highlight = false }: { label: string; value: React.ReactNode; highlight?: boolean }) {
  return (
    <div className="flex flex-wrap items-center justify-between gap-2 py-2.5 border-b border-slate-100/80 last:border-0 dark:border-white/5 text-sm">
      <span className={cn("whitespace-nowrap font-medium", highlight ? "text-slate-700 dark:text-slate-200 font-bold" : "text-slate-500 dark:text-slate-400")}>
        {label}
      </span>
      <span className={cn("whitespace-nowrap font-bold tabular-nums", highlight ? "text-slate-900 dark:text-white text-base" : "text-slate-700 dark:text-slate-300")}>
        {value}
      </span>
    </div>
  );
}

// ─── Main Page ────────────────────────────────────────────────────────────────

export default function AgentMoneyInPage() {
  const { t } = useTranslation();
  const kycGateStatus = useAgentKycGate();
  const router = useRouter();
  const { data: initData, isLoading: initLoading } = useMoneyInData();
  const { data: txData } = useAgentTransactions();

  const submitInit = useMoneyInSubmit();
  const submitManual = useMoneyInManualSubmit();
  const confirmAuto = useMoneyInConfirm();

  const [step, setStep] = useState<1 | 2>(1);
  const [amount, setAmount] = useState("");
  const [gateway, setGateway] = useState("");
  const [gatewaySearch, setGatewaySearch] = useState("");
  const gatewayRef = useRef<HTMLDivElement>(null);
  const gatewayMenu = useControlledSelectMenu(gatewayRef, "select-menu-portal");
  const [tempData, setTempData] = useState<MoneyInTempData | null>(null);
  const [success, setSuccess] = useState(false);

  const STEPS = [t("agent.moneyIn.stepAmountGateway"), t("agent.moneyIn.stepConfirmPay")];
  const stepNum = step;

  const isManual = tempData?.temporary_data?.data?.payment_gateway?.alias?.includes("manual");
  // Authorize USD is the only automatic gateway with its own card-capture page —
  // every other automatic gateway (Stripe, etc.) redirects to a hosted checkout URL
  // instead. Dispatch on the selected gateway itself, not on response shape (mirrors
  // send/page.tsx's isAuthorizeGateway check).
  const isAuthorizeGateway = /authorize/i.test(tempData?.temporary_data?.data?.payment_gateway?.alias ?? "");
  // Tatum ETH (and any other crypto gateway) settles off-platform on-chain — the agent
  // pastes the transaction hash on a dedicated page instead of a hosted checkout redirect.
  const isCryptoGateway = /tatum/i.test(tempData?.temporary_data?.data?.payment_gateway?.alias ?? "");
  const { data: manualData, isLoading: manualLoading } = useMoneyInManualFields(
    isManual ? tempData?.temporary_data?.data?.payment_gateway?.alias : undefined
  );
  const [manualForm, setManualForm] = useState<Record<string, string | File>>({});

  const limits = initData?.limits_data;
  const [search, setSearch] = useState("");
  const moneyInLogs = txData?.money_in ?? [];
  const filteredLogs = moneyInLogs.filter(
    (tx) =>
      tx.transaction_id.toLowerCase().includes(search.toLowerCase()) ||
      tx.payment_method.toLowerCase().includes(search.toLowerCase())
  );

  // ─── Handlers ─────────────────────────────────────────────────────────────────

  async function handleNext() {
    if (!amount || !gateway) return;
    try {
      const res = await submitInit.mutateAsync({ amount, payment_gateway: gateway });
      setTempData(res);
      setSuccess(false);
      setStep(2);
      if (res.temporary_data.data.payment_gateway.alias !== gateway) {
        setManualForm({});
      }
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Something went wrong";
      notify(msg, "error");
    }
  }

  async function handleConfirm() {
    if (!tempData) return;
    const identifier = tempData.temporary_data.identifier;
    try {
      if (isManual) {
        const input = { identifier, ...manualForm } as Record<string, unknown>;
        await submitManual.mutateAsync(input as unknown as Parameters<typeof submitManual.mutateAsync>[0]);
        setSuccess(true);
      } else {
        const origin = window.location.origin;
        // success_url: the completed top-up shows up here — the SPA's in-memory
        // success state can't survive the full external redirect back from the
        // hosted gateway page. cancel_url: back to this same page to retry.
        const res = await confirmAuto.mutateAsync({
          identifier,
          success_url: `${origin}/agent/transactions`,
          cancel_url: `${origin}/agent/money-in`,
        });
        // Backend sends whichever field doesn't apply as `[]`, not absent — a plain
        // truthy check passes for both, so every gateway fell into the identifier
        // branch below. Require a genuine non-empty string once inside it.
        if (isAuthorizeGateway) {
          const authorizeIdentifier = typeof res.identifier === "string" ? res.identifier : identifier;
          router.push(`/agent/money-in/authorize?identifier=${encodeURIComponent(authorizeIdentifier)}`);
        } else if (isCryptoGateway) {
          const cryptoIdentifier = typeof res.identifier === "string" ? res.identifier : identifier;
          router.push(`/agent/money-in/crypto?identifier=${encodeURIComponent(cryptoIdentifier)}`);
        } else if (typeof res.redirect_url === "string" && res.redirect_url) {
          window.location.href = res.redirect_url;
        } else {
          setSuccess(true);
        }
      }
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : "Payment failed";
      notify(msg, "error");
    }
  }

  function handleReset() {
    setStep(1);
    setAmount("");
    setGateway("");
    setTempData(null);
    setSuccess(false);
    setManualForm({});
  }

  // ─── Render ───────────────────────────────────────────────────────────────────

  if (kycGateStatus) {
    return <AgentKycGate status={kycGateStatus} />;
  }

  return (
    <Container className="max-w-full space-y-4 lg:space-y-6">
      <m.div
        variants={containerVariants}
        initial="hidden"
        animate="visible"
        className="flex flex-col gap-4 lg:gap-6"
      >
        {/* Page header */}
        <m.div variants={itemVariants}>
          <header className="flex items-center gap-4">
            <div className="icon-box-md grid place-items-center rounded-2xl bg-gradient-to-br from-emerald-500 to-brand-500 text-white shadow-lg">
              <ArrowDownLeft className="icon-xl rtl:-scale-x-100" />
            </div>
            <div>
              <h1 className="text-2xl font-bold tracking-tight text-slate-900 dark:text-white">{t("agent.moneyIn.title")}</h1>
              <p className="mt-1 text-sm text-slate-500 dark:text-slate-400">
                {t("agent.moneyIn.subtitle")}
              </p>
            </div>
          </header>
        </m.div>

        {/* Step indicator — outside card */}
        {!success && (
          <m.div variants={itemVariants}>
            <div className="flex w-full items-start justify-center overflow-x-auto py-2">
              {STEPS.flatMap((label, i) => {
                const isActive = i + 1 === stepNum;
                const isCompleted = i + 1 < stepNum;
                const isLast = i === STEPS.length - 1;
                return [
                  <div key={`step-${i}`} className="flex w-auto min-w-[7.5rem] sm:min-w-[10rem] flex-col items-center gap-1.5 px-2">
                    <div className={cn(
                      "grid h-7 w-7 shrink-0 place-items-center rounded-full text-xs font-black transition-all duration-500",
                      isActive
                        ? "bg-gradient-to-br from-brand-500 to-purple-600 text-white shadow-md shadow-brand-500/25 ring-2 ring-brand-500/20"
                        : isCompleted
                          ? "bg-brand-500 text-white shadow-sm"
                          : "bg-slate-100 text-slate-400 dark:bg-slate-800 dark:text-slate-500",
                    )}>
                      {isCompleted ? <CheckCircle2 className="h-3.5 w-3.5" /> : i + 1}
                    </div>
                    <span className={cn(
                      "whitespace-nowrap text-center text-sm font-medium capitalize tracking-wider transition-colors duration-300",
                      isActive ? "text-brand-600 dark:text-brand-400" : "text-slate-400 dark:text-slate-600",
                    )}>
                      {label}
                    </span>
                  </div>,
                  ...(!isLast ? [
                    <div key={`conn-${i}`} className="relative mx-2 mt-3 h-0.5 w-12 sm:w-20 shrink-0 overflow-hidden rounded-full bg-slate-200 dark:bg-slate-700/60">
                      <div className={cn(
                        "absolute inset-y-0 start-0 rounded-full bg-gradient-to-r from-brand-500 to-purple-500 transition-all duration-700 ease-out",
                        isCompleted ? "w-full" : "w-0",
                      )} />
                    </div>,
                  ] : []),
                ];
              })}
            </div>
          </m.div>
        )}

        {/* ── Main Form Card ───────────────────────────────────────────────────── */}
        <m.div variants={itemVariants} className="overflow-hidden rounded-3xl border border-slate-200/60 bg-white shadow-sm backdrop-blur-md dark:border-slate-800/60 dark:bg-slate-900/40">
          {false && null /* stepper moved outside */}

          {success ? (
            <div className="flex flex-col items-center justify-center p-12 text-center">
              <div className="relative mb-6">
                <div className="absolute inset-0 animate-ping rounded-full bg-emerald-400/20" />
                <div className="relative grid h-20 w-20 place-items-center rounded-full bg-gradient-to-br from-emerald-400 to-emerald-600 shadow-lg shadow-emerald-500/30">
                  <CheckCircle2 className="h-10 w-10 text-white" />
                </div>
              </div>
              <h2 className="text-2xl font-black tracking-tight text-slate-900 dark:text-white">
                {isManual ? t("agent.moneyIn.requestSubmittedTitle") : t("agent.moneyIn.paymentInitiatedTitle")}
              </h2>
              <p className="mt-2 max-w-sm text-sm text-slate-500 dark:text-slate-400">
                {isManual
                  ? t("agent.moneyIn.manualSubmittedDesc")
                  : t("agent.moneyIn.paymentSubmittedDesc")}
              </p>
              <Button
                onClick={handleReset}
                size="lg"
                className="mt-8 bg-gradient-to-r from-emerald-600 to-emerald-500 text-white font-bold shadow-lg shadow-emerald-500/25 hover:-translate-y-0.5 transition-all"
              >
                {t("agent.moneyIn.addMoreFunds")}
                <ArrowRight className="ms-2 h-4 w-4 rtl:-scale-x-100" />
              </Button>
            </div>
          ) : step === 1 ? (
            <div className="divide-y divide-slate-100/80 dark:divide-white/5">

              {initLoading ? (
                <div className="p-4 sm:p-6">
                  <div className="h-40 animate-pulse rounded-xl bg-slate-200 dark:bg-slate-800" />
                </div>
              ) : (
                <>
                  {/* Card header */}
                  <div className="flex flex-col gap-4 p-4 sm:flex-row sm:items-center sm:justify-between sm:p-6">
                    <div>
                      <h2 className="text-[length:var(--text-lg-fixed)] font-bold text-slate-900 dark:text-white">
                        {t("agent.moneyIn.stepAmountGateway")}
                      </h2>
                      <p className="mt-1 text-[length:var(--text-sm)] font-medium text-slate-500 dark:text-slate-400">
                        {t("agent.moneyIn.detailsDesc")}
                      </p>
                    </div>
                    {limits && (
                      <div className="rounded-xl border border-brand-200/60 bg-brand-50/40 px-4 py-2.5 dark:border-brand-500/20 dark:bg-brand-500/10">
                        <p className="text-[length:var(--text-sm)] font-medium capitalize tracking-widest text-brand-500/70 dark:text-brand-400/70">
                          {t("agent.moneyIn.availableLimits")}
                        </p>
                        <p className="mt-0.5 text-[length:var(--text-sm)] font-black tabular-nums text-slate-900 dark:text-white">
                          <span dir="ltr" className="inline-flex items-baseline gap-1.5">
                            {limits.min_limit}
                            <span className="text-slate-400">–</span>
                            {limits.max_limit}
                            <span className="text-brand-500 dark:text-brand-400">{initData?.base_currency}</span>
                          </span>
                        </p>
                      </div>
                    )}
                  </div>

                  {/* Gateway */}
                  <div className="flex flex-col gap-1.5 p-4 sm:p-6">
                    <label className="block text-[length:var(--text-sm)] font-medium capitalize tracking-wider text-slate-500 dark:text-slate-400">
                      {t("agent.moneyIn.gatewayLabel")} <span className="text-rose-500">*</span>
                    </label>
                    <div ref={gatewayRef}>
                      <Select
                        instanceId="gateway-select"
                        isSearchable
                        unstyled
                        inputValue={gatewaySearch}
                        onInputChange={(val, { action }) => { if (action === "input-change") setGatewaySearch(val); }}
                        menuIsOpen={gatewayMenu.menuIsOpen}
                        onMenuOpen={gatewayMenu.onMenuOpen}
                        onMenuClose={() => { gatewayMenu.onMenuClose(); setGatewaySearch(""); }}
                        components={SEARCHABLE_SELECT_COMPONENTS}
                        classNames={SELECT_CLS}
                        styles={SELECT_STYLES}
                        menuPortalTarget={typeof document !== "undefined" ? document.body : undefined}
                        options={initData?.payment_gateway.map((g) => ({ value: g.alias, label: g.name }))}
                        value={gateway ? { value: gateway, label: initData?.payment_gateway.find((g) => g.alias === gateway)?.name } : null}
                        onChange={(opt) => setGateway(opt?.value ?? "")}
                        placeholder={t("agent.moneyIn.gatewayPlaceholder")}
                      />
                    </div>
                  </div>

                  {/* Amount */}
                  <div className="flex flex-col gap-1.5 p-4 sm:p-6">
                    <label className="block text-[length:var(--text-sm)] font-medium capitalize tracking-wider text-slate-500 dark:text-slate-400">
                      {t("agent.moneyIn.amountLabel")} <span className="text-rose-500">*</span>
                    </label>
                    <div className="flex items-stretch overflow-hidden rounded-xl border border-slate-200/80 bg-slate-50/50 transition-all hover:border-slate-300 focus-within:border-brand-500 focus-within:ring-4 focus-within:ring-brand-500/10 dark:border-slate-700/60 dark:bg-slate-900/50 dark:hover:border-slate-600">
                      <span className="flex shrink-0 items-center bg-slate-100 px-4 text-[length:var(--text-sm)] font-black text-slate-800 dark:bg-slate-800 dark:text-slate-100">
                        {initData?.base_currency}
                      </span>
                      <div className="w-px self-stretch bg-slate-200/80 dark:bg-slate-700/60" />
                      <div className="relative flex-1">
                        <input
                          type="number"
                          min={limits?.min_limit}
                          max={limits?.max_limit}
                          step="0.01"
                          value={amount}
                          onChange={(e) => setAmount(e.target.value)}
                          placeholder="0.00"
                          required
                          className="h-12 w-full bg-transparent px-4 text-[length:var(--text-lg)] font-bold tracking-tight text-slate-900 outline-none focus:outline-none focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:font-normal placeholder:text-slate-300 dark:text-white dark:placeholder:text-slate-600"
                        />
                        {limits && (
                          <div className="pointer-events-none absolute inset-y-0 end-0 flex items-center pe-4">
                            <span className="whitespace-nowrap text-[length:var(--text-xs)] font-semibold text-slate-400">
                              {t("agent.moneyIn.minLimit").replace("{n}", String(limits.min_limit))}
                            </span>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>

                  {/* CTA */}
                  <div className="p-4 sm:p-6">
                    <Button
                      size="lg"
                      onClick={handleNext}
                      disabled={!amount || !gateway || submitInit.isPending}
                      className={cn(
                        "w-full whitespace-nowrap font-bold tracking-wide transition-all duration-300",
                        amount && gateway
                          ? "bg-gradient-to-r from-emerald-600 to-emerald-500 text-white shadow-lg shadow-emerald-500/25 hover:from-emerald-500 hover:to-emerald-400 hover:-translate-y-0.5"
                          : "opacity-60",
                      )}
                    >
                      {submitInit.isPending ? (
                        <Loader2 className="me-2 h-5 w-5 animate-spin" />
                      ) : (
                        <>
                          {t("agent.moneyIn.nextStep")}
                          <ChevronRight className="ms-2 h-5 w-5 rtl:rotate-180" />
                        </>
                      )}
                    </Button>
                  </div>
                </>
              )}
            </div>
          ) : (
            <div className="divide-y divide-slate-100/80 dark:divide-white/5">
              {/* Back link */}
              <div className="flex items-center justify-end px-6 pb-1 pt-0 sm:px-8">
                <button
                  onClick={() => setStep(1)}
                  className="text-xs font-semibold text-slate-400 transition-colors hover:text-brand-600 dark:hover:text-brand-400"
                >
                  {t("agent.moneyIn.back")}
                </button>
              </div>

              {/* Summary */}
              {tempData && (
                <div className="p-4 sm:p-6 space-y-1">
                  <p className="mb-3 text-sm font-medium capitalize tracking-wider text-slate-500 dark:text-slate-400">
                    {t("agent.moneyIn.transactionSummary")}
                  </p>
                  <SummaryRow
                    label={t("agent.moneyIn.enterAmountRow")}
                    value={`${Number(tempData.temporary_data.data.amount).toFixed(2)} ${tempData.temporary_data.data.base_currency.currency}`}
                  />
                  <SummaryRow
                    label={t("agent.moneyIn.exchangeRateRow")}
                    value={`1 ${tempData.temporary_data.data.base_currency.currency} = ${Number(tempData.temporary_data.data.exchange_rate).toFixed(2)} ${tempData.temporary_data.data.payment_gateway.currency}`}
                  />
                  <SummaryRow
                    label={t("agent.moneyIn.totalFeesRow")}
                    value={`${Number(tempData.temporary_data.data.total_charge).toFixed(2)} ${tempData.temporary_data.data.base_currency.currency}`}
                  />
                  <SummaryRow
                    label={t("agent.moneyIn.receiveAmountRow")}
                    value={`${Number(tempData.temporary_data.data.receive_amount).toFixed(2)} ${tempData.temporary_data.data.base_currency.currency}`}
                    highlight
                  />
                  <div className="pt-1">
                    <div className="flex flex-wrap items-center justify-between gap-4 rounded-xl bg-gradient-to-r from-emerald-50 to-brand-50 p-4 dark:from-emerald-500/10 dark:to-brand-500/10">
                      <span className="whitespace-nowrap text-sm font-medium capitalize tracking-wider text-emerald-600/80 dark:text-emerald-400/80">
                        {t("agent.moneyIn.totalPayable")}
                      </span>
                      <span className="whitespace-nowrap text-xl font-black tabular-nums text-emerald-700 dark:text-emerald-300">
                        {Number(tempData.temporary_data.data.payable_amount).toFixed(2)} {tempData.temporary_data.data.payment_gateway.currency}
                      </span>
                    </div>
                  </div>
                </div>
              )}

              {/* Manual or Auto gateway */}
              {isManual ? (
                <div className="p-4 sm:p-6 space-y-5">
                  {manualLoading ? (
                    <div className="h-32 animate-pulse rounded-xl bg-slate-200 dark:bg-slate-800" />
                  ) : (
                    <>
                      {manualData?.gateway?.desc && (
                        <div className="rounded-xl border border-amber-200/60 bg-amber-50/50 p-5 dark:border-amber-500/20 dark:bg-amber-500/5">
                          <h3 className="mb-3 flex items-center gap-2 text-sm font-bold text-amber-800 dark:text-amber-400">
                            <AlertCircle className="icon-md" />
                            {t("agent.moneyIn.paymentInstructions")}
                          </h3>
                          <div
                            className="prose prose-sm prose-amber dark:prose-invert max-w-none text-slate-700 dark:text-slate-300 [&>p]:mb-2 [&>ol]:mb-2 [&>ol]:ps-4"
                            dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(manualData.gateway.desc) }}
                          />
                        </div>
                      )}

                      <div className="grid gap-5 sm:grid-cols-2">
                        {manualData?.input_fields.map((field) => (
                          <div key={field.name} className={cn("flex flex-col gap-1.5", field.type === "file" && "sm:col-span-2")}>
                            <label className="block text-sm font-medium capitalize tracking-wider text-slate-500 dark:text-slate-400">
                              {field.label} {field.required && <span className="text-rose-500">*</span>}
                            </label>
                            {field.type === "file" ? (
                              <div className="relative group">
                                <input
                                  type="file"
                                  required={field.required}
                                  accept={field.validation?.mimes?.map((m) => `.${m.trim()}`).join(",")}
                                  onChange={(e) => {
                                    if (e.target.files?.[0]) {
                                      setManualForm((prev) => ({ ...prev, [field.name]: e.target.files![0] }));
                                    }
                                  }}
                                  className="absolute inset-0 z-10 h-full w-full cursor-pointer opacity-0"
                                />
                                <div className="flex flex-col items-center justify-center rounded-xl border-2 border-dashed border-slate-300 bg-slate-50/50 px-6 py-8 text-center transition-all group-hover:border-brand-400 group-hover:bg-brand-50/50 dark:border-slate-700 dark:bg-slate-800/50 dark:group-hover:border-brand-500/50 dark:group-hover:bg-brand-500/5">
                                  <Upload className="mb-3 h-8 w-8 text-slate-400 transition-colors group-hover:text-brand-500" />
                                  <p className="text-sm font-semibold text-slate-600 dark:text-slate-300">
                                    {manualForm[field.name] ? (manualForm[field.name] as File).name : "Click or drag file to upload"}
                                  </p>
                                  <p className="mt-1 text-xs text-slate-400">
                                    {field.validation?.mimes?.join(", ")} up to 10MB
                                  </p>
                                </div>
                              </div>
                            ) : (
                              <input
                                type={field.type}
                                required={field.required}
                                value={(manualForm[field.name] as string) || ""}
                                onChange={(e) => setManualForm((prev) => ({ ...prev, [field.name]: e.target.value }))}
                                className={INPUT_CLS}
                                placeholder={`Enter ${field.label.toLowerCase()}`}
                              />
                            )}
                          </div>
                        ))}
                      </div>
                    </>
                  )}
                </div>
              ) : (
                <div className="p-4 sm:p-6">
                  <div className="flex flex-col items-center rounded-xl border border-slate-200/60 bg-slate-50/50 p-6 text-center dark:border-slate-700/60 dark:bg-slate-800/50">
                    <Wallet className="mb-4 h-10 w-10 text-brand-500" />
                    <h3 className="text-lg font-bold text-slate-900 dark:text-white">{t("agent.moneyIn.proceedToPayment")}</h3>
                    <p className="mt-1 text-sm text-slate-500 dark:text-slate-400">
                      {t("agent.moneyIn.proceedDesc")}
                    </p>
                  </div>
                </div>
              )}

              {/* CTA */}
              <div className="p-4 sm:p-6">
                <Button
                  size="lg"
                  onClick={handleConfirm}
                  disabled={submitManual.isPending || confirmAuto.isPending}
                  className="w-full bg-gradient-to-r from-emerald-600 to-emerald-500 font-bold text-white shadow-lg shadow-emerald-500/25 hover:from-emerald-500 hover:to-emerald-400 hover:-translate-y-0.5 transition-all duration-300"
                >
                  {(submitManual.isPending || confirmAuto.isPending) ? (
                    <Loader2 className="me-2 h-5 w-5 animate-spin" />
                  ) : (
                    <>
                      <CheckCircle2 className="me-2 h-5 w-5" />
                      {t("agent.moneyIn.confirmPayment")}
                    </>
                  )}
                </Button>
              </div>
            </div>
          )}
        </m.div>

        {/* ── Transaction Log ──────────────────────────────────────────────────── */}
        <m.div variants={itemVariants} className="overflow-hidden rounded-3xl border border-slate-200/60 bg-white shadow-sm backdrop-blur-md dark:border-slate-800/60 dark:bg-slate-900/40">
          <div className="flex flex-col gap-6 border-b border-slate-100 bg-slate-50/50 p-6 sm:flex-row sm:items-center sm:justify-between sm:gap-3 sm:p-6 dark:border-slate-800/60 dark:bg-slate-800/40">
            <div className="flex items-center gap-4">
              <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-emerald-500 to-emerald-700 text-white shadow-md">
                <ScrollText className="icon-lg" />
              </div>
              <div>
                <h2 className="text-lg font-bold tracking-tight text-slate-900 dark:text-white">{t("agent.moneyIn.recentTopUps")}</h2>
                <p className="text-sm font-medium text-slate-500 dark:text-slate-400">
                  {moneyInLogs.length === 1
                    ? t("agent.moneyIn.transactionCountOne")
                    : t("agent.moneyIn.transactionCountOther").replace("{count}", String(moneyInLogs.length))}
                </p>
              </div>
            </div>

            {moneyInLogs.length > 0 && (
              <div className="relative sm:w-64">
                <Search className="pointer-events-none absolute start-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
                <input
                  type="text"
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  placeholder={t("agent.moneyIn.searchPlaceholder")}
                  className="h-10 w-full rounded-xl border border-slate-200/80 bg-white ps-9 pe-3 text-sm font-medium text-slate-900 outline-none transition-all focus:border-brand-500 focus:ring-4 focus:ring-brand-500/10 dark:border-slate-700 dark:bg-slate-900 dark:text-white shadow-sm"
                />
              </div>
            )}
          </div>

          {moneyInLogs.length === 0 ? (
            <div className="flex flex-col items-center gap-3 py-16 text-center">
              <div className="grid h-12 w-12 place-items-center rounded-xl bg-slate-100 dark:bg-slate-800">
                <Wallet className="h-6 w-6 text-slate-400" />
              </div>
              <div>
                <p className="text-sm font-bold text-slate-600 dark:text-slate-300">{t("agent.moneyIn.noTopUps")}</p>
                <p className="mt-0.5 text-xs text-slate-400">{t("agent.moneyIn.noTopUpsDesc")}</p>
              </div>
            </div>
          ) : filteredLogs.length === 0 ? (
            <div className="flex flex-col items-center gap-3 py-16 text-center">
              <div className="grid h-12 w-12 place-items-center rounded-xl bg-slate-100 dark:bg-slate-800">
                <Search className="h-6 w-6 text-slate-400" />
              </div>
              <div>
                <p className="text-sm font-bold text-slate-600 dark:text-slate-300">{t("agent.moneyIn.noResults").replace("{search}", search)}</p>
                <button onClick={() => setSearch("")} className="mt-1 text-xs font-bold text-brand-600 hover:underline dark:text-brand-400">
                  {t("agent.moneyIn.clearSearch")}
                </button>
              </div>
            </div>
          ) : (
            <div className="w-full overflow-x-auto">
              <div className="min-w-[700px]">
                <div className="grid grid-cols-5 gap-4 border-b border-slate-100/60 bg-slate-50/60 px-6 py-3 dark:border-white/5 dark:bg-slate-800/30 sm:px-7">
                  {[t("agent.moneyIn.colTransaction"), t("agent.moneyIn.colMethod"), t("agent.moneyIn.colAmount"), t("agent.moneyIn.colDate"), t("agent.moneyIn.colStatus")].map((h) => (
                    <span key={h} className="text-sm font-medium capitalize tracking-widest text-slate-400">
                      {h}
                    </span>
                  ))}
                </div>
                <div className="divide-y divide-slate-100/60 dark:divide-white/5">
                  {filteredLogs.map((tx) => (
                    <div key={tx.transaction_id} className="grid grid-cols-5 items-center gap-4 px-6 py-4 transition-colors hover:bg-slate-50/50 dark:hover:bg-slate-800/20 sm:px-7">
                      <div>
                        <p className="text-sm font-bold text-brand-600 dark:text-brand-400">#{tx.transaction_id}</p>
                        <p className="mt-0.5 text-xs text-slate-400">{new Date(tx.created_at).toLocaleDateString()}</p>
                      </div>
                      <div>
                        <p className="text-sm font-medium text-slate-600 dark:text-slate-300">{tx.payment_method}</p>
                      </div>
                      <div>
                        <p className="text-sm font-black tabular-nums text-emerald-600 dark:text-emerald-400">
                          {Number(tx.request_amount).toFixed(2)}{" "}
                          <span className="text-2xs font-semibold text-slate-400">{tx.sender_currency}</span>
                        </p>
                      </div>
                      <div>
                        <p className="text-xs font-semibold text-slate-600 dark:text-slate-300">
                          {new Date(tx.created_at).toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" })}
                        </p>
                        <p className="mt-0.5 text-xs text-slate-400">
                          {new Date(tx.created_at).toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" })}
                        </p>
                      </div>
                      <div>
                        <span className={cn("badge capitalize", STATUS_MAP[tx.status.toLowerCase()] || STATUS_MAP.pending)}>
                          {tx.status}
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}
        </m.div>
      </m.div>
    </Container>
  );
}
