"use client";

import { useState, useMemo, useRef } from "react";
import Link from "next/link";
import { m } from "framer-motion";
import {
  CheckCircle2,
  Loader2,
  Send,
  ArrowUpDown,
  Clock,
  AlertCircle,
  TrendingUp,
  UserPlus,
  Users,
  ArrowRight,
  ScrollText,
  ChevronLeft,
  ChevronRight,
  Wallet,
} from "lucide-react";
import Select from "react-select";

import { Button } from "@/components/common/Button";
import { Container } from "@/components/common/Container";
import { SEARCHABLE_SELECT_COMPONENTS } from "@/components/common/SearchableSelectParts";
import { AgentKycGate } from "@/components/agent/AgentKycGate";
import { AgentSendRemittanceSkeleton } from "@/components/skeletons/AgentSendRemittanceSkeleton";
import { notify } from "@/lib/notify";
import { cn } from "@/lib/utils";
import {
  useAgentSendRemittanceIndex,
  useAgentRemittanceRecipients,
  useAgentRemittanceConfirm,
  type AgentTransactionType,
} from "@/hooks/queries/useAgentSendRemittance";
import {
  useAgentTransactions,
  type SendRemittanceTx,
} from "@/hooks/queries/useAgentDashboard";
import { useCurrencyInfo } from "@/hooks/queries/useSettings";
import { useTranslation } from "@/hooks/useTranslation";
import { useAgentKycGate } from "@/hooks/useAgentKycGate";
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 ─────────────────────────────────────────────────────────────

// Menu attaches flush to the control (no gap, square-off shared corners) so
// opening reads as the control expanding downward rather than a floating menu.
const SELECT_CLS = {
  control: ({ menuIsOpen }: { menuIsOpen: boolean }) =>
    cn(
      "h-12 w-full border border-slate-200/80 bg-white px-2 text-sm font-medium text-slate-900 transition-[border-radius] duration-150 hover:border-slate-300 dark:border-slate-700/60 dark:bg-slate-900/80 dark:text-white cursor-pointer !min-h-12 shadow-sm",
      menuIsOpen ? "rounded-t-xl rounded-b-none" : "rounded-xl",
    ),
  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",
  valueContainer: () => "px-0",
  dropdownIndicator: () =>
    "text-slate-400 hover:text-slate-600 dark:text-slate-500 dark:hover:text-slate-300",
  indicatorSeparator: () => "hidden",
};

// Portal every menu to <body> so it's never clipped/under-stacked by the
// backdrop-blur/overflow-hidden card it lives in (or a sibling card in the
// 2-col grid) — same fix as the shared gateway-select pattern.
const MENU_PORTAL_PROPS = {
  menuPortalTarget: typeof document !== "undefined" ? document.body : undefined,
  menuPosition: "fixed" as const,
  styles: { menuPortal: (base: object) => ({ ...base, zIndex: 9999 }) },
};

// ─── Helpers ───────────────────────────────────────────────────────────────────

interface CurrencyOpt {
  value: number;
  label: string;
  name: string;
  flag: string;
}

function computeCharge(amount: number, txType: AgentTransactionType | undefined) {
  if (!txType || !amount) return { fixed: 0, percent: 0, total: 0 };
  const interval = txType.intervals.find(
    (iv) => amount >= iv.min_limit && amount <= iv.max_limit,
  );
  const fixed = interval ? interval.fixed : Number(txType.fixed_charge);
  const percent = interval
    ? (amount * interval.percent) / 100
    : (amount * Number(txType.percent_charge)) / 100;
  return { fixed, percent, total: fixed + percent };
}

// ─── Status Badge ──────────────────────────────────────────────────────────────

function StatusBadge({ status }: { status: string }) {
  const { t } = useTranslation();
  const s = status.toLowerCase();
  let label = status;
  let cls = "bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300";
  if (s === "pending") {
    label = t("agent.sendRemittance.statusPending");
    cls = "bg-amber-50 text-amber-700 dark:bg-amber-500/10 dark:text-amber-400";
  } else if (s === "complete" || s === "completed") {
    label = t("agent.sendRemittance.statusComplete");
    cls = "bg-emerald-50 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-400";
  } else if (s === "success") {
    label = t("agent.sendRemittance.statusSuccess");
    cls = "bg-emerald-50 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-400";
  } else if (s === "cancel" || s === "cancelled" || s === "canceled") {
    label = t("agent.sendRemittance.statusCancelled");
    cls = "bg-rose-50 text-rose-700 dark:bg-rose-500/10 dark:text-rose-400";
  } else if (s === "failed") {
    label = t("agent.sendRemittance.statusFailed");
    cls = "bg-rose-50 text-rose-700 dark:bg-rose-500/10 dark:text-rose-400";
  } else if (s === "hold" || s === "on_hold") {
    label = t("agent.sendRemittance.statusOnHold");
    cls = "bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300";
  }
  return (
    <span className={cn("badge capitalize text-[length:var(--text-sm-fixed)]", cls)}>
      {label}
    </span>
  );
}

// ─── Summary Row ───────────────────────────────────────────────────────────────

function SummaryRow({
  icon: Icon,
  label,
  value,
  highlight,
}: {
  icon: React.ElementType;
  label: string;
  value: string;
  highlight?: boolean;
}) {
  const { dir } = useTranslation();
  return (
    <div className="flex items-center justify-between px-6 py-3.5 border-b border-slate-100/80 last:border-0 dark:border-white/5 sm:px-7">
      <div className="flex items-center gap-2.5">
        <span className="grid h-7 w-7 shrink-0 place-items-center rounded-lg bg-slate-100 dark:bg-slate-800">
          <Icon className={cn("h-3.5 w-3.5 text-slate-500 dark:text-slate-400", (Icon === Send || Icon === TrendingUp) && dir === "rtl" && "[transform:scaleX(-1)]")} />
        </span>
        <span className="text-sm font-medium text-slate-500 dark:text-slate-400">{label}</span>
      </div>
      <span
        className={cn(
          "text-sm font-bold tabular-nums",
          value === "—"
            ? "text-slate-400 dark:text-slate-500"
            : highlight
              ? "text-brand-600 dark:text-brand-400"
              : "text-slate-800 dark:text-slate-200",
        )}
      >
        {value}
      </span>
    </div>
  );
}

// ─── Transaction Log Row ───────────────────────────────────────────────────────

function LogRow({ tx, index }: { tx: SendRemittanceTx; index: number }) {
  return (
    <div
      className={cn(
        "grid grid-cols-6 items-center gap-6 px-6 py-4 transition-colors",
        index % 2 === 0 ? "bg-transparent" : "bg-slate-50/40 dark:bg-slate-800/10",
        "hover:bg-brand-50/20 dark:hover:bg-brand-500/5",
      )}
    >
      <div className="min-w-0">
        <p className="truncate text-sm font-bold text-slate-800 dark:text-slate-100">
          #{tx.transaction_id}
        </p>
        <p className="mt-0.5 text-xs font-medium text-slate-500 dark:text-slate-400">
          {tx.transactin_type} · {tx.sender_name}
        </p>
      </div>
      <div>
        <p className="text-sm font-bold tabular-nums text-slate-900 dark:text-white">
          {Number(tx.request_amount).toFixed(2)}{" "}
          <span className="text-xs font-semibold text-slate-400">{tx.sender_currency}</span>
        </p>
      </div>
      <div>
        <p className="text-sm font-bold tabular-nums text-emerald-600 dark:text-emerald-400">
          {Number(tx.will_get_amount).toFixed(2)}{" "}
          <span className="text-xs font-semibold text-slate-400">{tx.receiver_currency}</span>
        </p>
      </div>
      <div>
        <p className="text-[length:var(--text-sm)] font-medium text-slate-600 dark:text-slate-300">
          {new Date(tx.created_at).toLocaleDateString(undefined, {
            month: "short",
            day: "numeric",
            year: "numeric",
          })}
        </p>
      </div>
      <div>
        <p className="text-[length:var(--text-sm)] font-medium text-slate-600 dark:text-slate-300">
          {new Date(tx.created_at).toLocaleTimeString(undefined, {
            hour: "2-digit",
            minute: "2-digit",
          })}
        </p>
      </div>
      <div>
        <StatusBadge status={tx.status} />
      </div>
    </div>
  );
}

// ─── Transaction Log Section ───────────────────────────────────────────────────

const PAGE_SIZE = 10;

function RemittanceLog() {
  const { data, isLoading, isError, refetch } = useAgentTransactions();
  const logs: SendRemittanceTx[] = data?.send_remittance ?? [];
  const [page, setPage] = useState(1);
  const { t, dir } = useTranslation();

  const totalPages = Math.max(1, Math.ceil(logs.length / PAGE_SIZE));
  const safePage = Math.min(page, totalPages);
  const pageItems = logs.slice((safePage - 1) * PAGE_SIZE, safePage * PAGE_SIZE);

  return (
    <div 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">
      {/* Header */}
      <div className="flex items-center justify-between gap-4 border-b border-slate-100 bg-slate-50/50 p-6 sm:p-7 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-brand-500 to-purple-600 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.sendRemittance.logTitle")}
            </h2>
            <p className="text-sm font-medium text-slate-500 dark:text-slate-400">
              {isLoading
                ? t("agent.sendRemittance.loading")
                : t("agent.sendRemittance.transfersCount").replace("{count}", String(logs.length))}
            </p>
          </div>
        </div>
      </div>

      {/* Content */}
      {isLoading ? (
        <div className="divide-y divide-slate-100/60 dark:divide-white/5">
          {Array.from({ length: 5 }).map((_, i) => (
            <div key={i} className="flex items-center gap-6 px-6 py-5 sm:px-7">
              <div className="h-4 w-32 animate-pulse rounded-lg bg-slate-200 dark:bg-slate-700 sm:w-40" />
              <div className="ml-auto h-4 w-20 animate-pulse rounded-lg bg-slate-200 dark:bg-slate-700 sm:w-24" />
              <div className="hidden h-4 w-20 animate-pulse rounded-lg bg-slate-200 dark:bg-slate-700 sm:block sm:w-24" />
              <div className="hidden h-4 w-20 animate-pulse rounded-lg bg-slate-200 dark:bg-slate-700 sm:block" />
              <div className="hidden h-4 w-16 animate-pulse rounded-lg bg-slate-200 dark:bg-slate-700 sm:block" />
              <div className="h-6 w-16 animate-pulse rounded-full bg-slate-200 dark:bg-slate-700 sm:w-20" />
            </div>
          ))}
        </div>
      ) : isError ? (
        <div className="flex flex-col items-center gap-3 py-14 text-center">
          <AlertCircle className="h-8 w-8 text-rose-400" />
          <p className="text-sm font-bold text-slate-700 dark:text-slate-200">{t("agent.sendRemittance.failedToLoadLogs")}</p>
          <button onClick={() => refetch()} className="text-xs font-bold text-brand-600 hover:underline dark:text-brand-400">
            {t("agent.sendRemittance.tryAgain")}
          </button>
        </div>
      ) : logs.length === 0 ? (
        <div className="flex flex-col items-center gap-3 py-14 text-center">
          <div className="grid h-12 w-12 place-items-center rounded-xl bg-slate-100 dark:bg-slate-800">
            <Clock 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.sendRemittance.noTransfers")}</p>
            <p className="mt-0.5 text-xs text-slate-400">{t("agent.sendRemittance.noTransfersDesc")}</p>
          </div>
        </div>
      ) : (
        <>
          <div className="w-full overflow-x-auto">
            <div className="min-w-[860px]">
              <div className="grid grid-cols-6 gap-6 border-b border-slate-100/60 bg-slate-50/60 px-6 py-3 dark:border-white/5 dark:bg-slate-800/30">
                {[t("agent.sendRemittance.colTransaction"), t("agent.sendRemittance.colAmount"), t("agent.sendRemittance.colRecipientGets"), t("agent.sendRemittance.colDate"), t("agent.sendRemittance.colTime"), t("agent.sendRemittance.colStatus")].map((h) => (
                  <span key={h} className="text-[length:var(--text-sm)] font-semibold capitalize text-slate-600 dark:text-slate-300">
                    {h}
                  </span>
                ))}
              </div>
              <div className="divide-y divide-slate-100/60 dark:divide-white/5">
                {pageItems.map((tx, i) => (
                  <LogRow key={tx.transaction_id} tx={tx} index={i} />
                ))}
              </div>
            </div>
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center justify-between border-t border-slate-100 px-6 py-4 sm:px-7 dark:border-slate-800/60">
              <p className="text-xs font-semibold text-slate-500 dark:text-slate-400">
                {t("agent.sendRemittance.pageSummary")
                  .replace("{page}", String(safePage))
                  .replace("{total}", String(totalPages))
                  .replace("{count}", String(logs.length))}
              </p>
              <div className="flex items-center gap-1">
                <button
                  type="button"
                  onClick={() => setPage((p) => Math.max(1, p - 1))}
                  disabled={safePage === 1}
                  className="btn-icon-sm rounded-full border border-slate-200 text-slate-600 transition hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-40 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
                >
                  {dir === "rtl" ? <ChevronRight className="icon-md" /> : <ChevronLeft className="icon-md" />}
                </button>
                {Array.from({ length: totalPages }, (_, i) => i + 1)
                  .filter((p) => p === 1 || p === totalPages || Math.abs(p - safePage) <= 1)
                  .reduce<(number | "…")[]>((acc, p, idx, arr) => {
                    if (idx > 0 && p - (arr[idx - 1] as number) > 1) acc.push("…");
                    acc.push(p);
                    return acc;
                  }, [])
                  .map((item, idx) =>
                    item === "…" ? (
                      <span key={`ellipsis-${idx}`} className="px-1 text-xs text-slate-400">…</span>
                    ) : (
                      <button
                        key={item}
                        type="button"
                        onClick={() => setPage(item as number)}
                        className={cn(
                          "btn-icon-sm rounded-full text-xs font-bold transition",
                          safePage === item
                            ? "bg-brand-600 text-white shadow-sm"
                            : "border border-slate-200 text-slate-600 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800",
                        )}
                      >
                        {item}
                      </button>
                    )
                  )}
                <button
                  type="button"
                  onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                  disabled={safePage === totalPages}
                  className="btn-icon-sm rounded-full border border-slate-200 text-slate-600 transition hover:bg-slate-50 disabled:cursor-not-allowed disabled:opacity-40 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
                >
                  {dir === "rtl" ? <ChevronLeft className="icon-md" /> : <ChevronRight className="icon-md" />}
                </button>
              </div>
            </div>
          )}
        </>
      )}
    </div>
  );
}

// ─── Main Page ─────────────────────────────────────────────────────────────────

export default function AgentSendRemittancePage() {
  const { t, dir } = useTranslation();
  const kycGateStatus = useAgentKycGate();
  const [senderSlug, setSenderSlug] = useState("");
  const [recipientSlug, setRecipientSlug] = useState("");
  const [txTypeId, setTxTypeId] = useState<number | null>(null);
  const [txTypeName, setTxTypeName] = useState("");
  const [receiverCurrencyId, setReceiverCurrencyId] = useState<number | null>(null);
  const [amount, setAmount] = useState("");
  const [submitted, setSubmitted] = useState(false);
  const [currencySearch, setCurrencySearch] = useState("");
  const [senderSearch, setSenderSearch] = useState("");
  const [recipientSearch, setRecipientSearch] = useState("");

  const currencyRef = useRef<HTMLDivElement>(null);
  const currencyMenu = useControlledSelectMenu(currencyRef, "select-menu-portal");
  const senderRef = useRef<HTMLDivElement>(null);
  const senderMenu = useControlledSelectMenu(senderRef, "select-menu-portal");
  const recipientRef = useRef<HTMLDivElement>(null);
  const recipientMenu = useControlledSelectMenu(recipientRef, "select-menu-portal");

  const { data: indexData, isLoading: indexLoading } = useAgentSendRemittanceIndex();
  const { data: currencyInfoData } = useCurrencyInfo();
  const { data: recipientsData, isLoading: recipientsLoading } =
    useAgentRemittanceRecipients(txTypeName);
  const { mutate: confirm, isPending } = useAgentRemittanceConfirm();

  const base = indexData?.base_currency ?? "USD";
  const senders = indexData?.sender ?? [];
  const txTypes = indexData?.transaction_types ?? [];
  const receiverCurrencies = currencyInfoData?.receiver_currency ?? [];
  const currencyImagePaths = currencyInfoData?.image_paths;
  const buildFlagUrl = (flag: string) =>
    currencyImagePaths ? `${currencyImagePaths.base_url}${currencyImagePaths.path_location}/${flag}` : "";
  const receiverCurrencyOptions: CurrencyOpt[] = receiverCurrencies.map((c) => ({
    value: c.id,
    label: c.code,
    name: c.name,
    flag: buildFlagUrl(c.flag),
  }));
  const recipients = recipientsData?.recipients ?? [];

  const selectedTxType = txTypes.find((t) => t.id === txTypeId);
  const selectedCurrency = receiverCurrencies.find((c) => c.id === receiverCurrencyId);
  const selectedSender = senders.find((s) => s.slug === senderSlug);
  const selectedRecipient = recipients.find((r) => r.slug === recipientSlug);

  const numAmount = parseFloat(amount) || 0;
  const charges = useMemo(
    () => computeCharge(numAmount, selectedTxType),
    [numAmount, selectedTxType],
  );
  const netAmount = Math.max(0, numAmount - charges.total);
  const willGet = selectedCurrency
    ? (netAmount * Number(selectedCurrency.rate)).toFixed(2)
    : "0.00";
  const totalPayable = numAmount + charges.total;

  const canSubmit =
    senderSlug && recipientSlug && txTypeId && receiverCurrencyId && numAmount > 0;

  function handleSend() {
    if (!canSubmit || !txTypeId || !receiverCurrencyId) return;
    confirm(
      {
        amount,
        receiver_currency: receiverCurrencyId,
        sender: senderSlug,
        recipient: recipientSlug,
        transaction_type: txTypeId,
      },
      {
        onSuccess: () => {
          notify(t("agent.sendRemittance.submittedSuccessfully"), "success");
          setSubmitted(true);
        },
        onError: (err: Error) => notify(err.message || t("agent.sendRemittance.submissionFailed"), "error"),
      },
    );
  }

  function reset() {
    setSenderSlug("");
    setRecipientSlug("");
    setTxTypeId(null);
    setTxTypeName("");
    setReceiverCurrencyId(null);
    setAmount("");
    setSubmitted(false);
  }

  if (indexLoading) {
    return <AgentSendRemittanceSkeleton />;
  }

  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 flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <div className="flex items-center gap-4">
            <div className="icon-box-md grid place-items-center rounded-2xl bg-gradient-to-br from-brand-500 to-accent-500 text-white shadow-lg">
              <Send className={cn("icon-xl", dir === "rtl" && "[transform:scaleX(-1)]")} />
            </div>
            <div>
              <h1 className="text-2xl font-bold tracking-tight text-slate-900 dark:text-white">{t("agent.sendRemittance.title")}</h1>
              <p className="mt-1 text-sm text-slate-500 dark:text-slate-400">
                {t("agent.sendRemittance.subtitle")}
              </p>
            </div>
          </div>
          {selectedCurrency && (
            <div className="flex items-center gap-2.5 rounded-xl border border-slate-200 bg-slate-50 px-4 py-2.5 dark:border-slate-800 dark:bg-slate-800/50">
              <ArrowUpDown className="h-4 w-4 shrink-0 text-brand-500 dark:text-brand-400" />
              <div>
                <p className="text-xs font-semibold capitalize text-slate-400">{t("agent.sendRemittance.exchangeRateLabel")}</p>
                <p className="text-sm font-semibold text-slate-900 dark:text-white">
                  {t("agent.sendRemittance.rateFormat").replace("{base}", base).replace("{rate}", Number(selectedCurrency!.rate).toFixed(2)).replace("{code}", selectedCurrency!.code)}
                </p>
              </div>
            </div>
          )}
        </header>
      </m.div>

      {/* Success State */}
      {submitted ? (
        <m.div variants={itemVariants} className="flex flex-col items-center gap-6 rounded-3xl border border-slate-200/60 bg-white p-8 shadow-sm text-center backdrop-blur-md dark:border-slate-800/60 dark:bg-slate-900/40 sm:p-12">
          <div className="relative">
            <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>
          <div>
            <h2 className="text-2xl font-bold tracking-tight text-slate-900 dark:text-white">
              {t("agent.sendRemittance.transferSubmittedTitle")}
            </h2>
            <p className="mt-2 text-sm text-slate-500 dark:text-slate-400 max-w-sm mx-auto">
              {t("agent.sendRemittance.transferSubmittedDesc")}
            </p>
          </div>
          <Button
            size="lg"
            onClick={reset}
            className="bg-gradient-to-r from-brand-600 to-brand-500 text-white font-bold shadow-lg shadow-brand-500/25 hover:-translate-y-0.5 transition-all"
          >
            {t("agent.sendRemittance.sendAnotherTransfer")}
            <ArrowRight className={cn("ms-2 h-4 w-4", dir === "rtl" && "[transform:scaleX(-1)]")} />
          </Button>
        </m.div>
      ) : (
        /* Main 2-column layout */
        <m.div variants={itemVariants} className="grid grid-cols-1 gap-3 xl:grid-cols-2 xl:gap-6">
          {/* ── Left: Form ── */}
          <div 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="border-b border-slate-100 p-4 dark:border-slate-800/60 sm:p-6">
              <h2 className="text-[length:var(--text-lg-fixed)] font-semibold text-slate-900 dark:text-white">
                {t("agent.sendRemittance.formTitle")}
              </h2>
            </div>
            <div className="divide-y divide-slate-100/80 dark:divide-white/5">
              {/* Amount */}
              <div className="flex flex-col gap-1.5 p-4 sm:p-6">
                <label className="block text-[length:var(--text-sm-fixed)] font-medium capitalize text-slate-500 dark:text-slate-400">
                  {t("agent.sendRemittance.youSendExactly")}
                </label>
                <div className="flex items-center gap-0 overflow-hidden rounded-xl border border-slate-200/80 bg-slate-50/50 shadow-sm dark:border-slate-700/60 dark:bg-slate-900/50 focus-within:border-brand-500 focus-within:ring-4 focus-within:ring-brand-500/10">
                  <input
                    type="number"
                    min="0"
                    step="0.01"
                    value={amount}
                    onChange={(e) => setAmount(e.target.value)}
                    placeholder="0.00"
                    className="h-12 flex-1 bg-transparent px-4 text-lg font-semibold text-slate-900 outline-none placeholder:text-slate-300/50 placeholder:font-normal placeholder:text-base dark:text-white dark:placeholder:text-slate-600"
                  />
                  <div className="flex h-12 items-center border-l border-slate-200/80 bg-slate-100/80 px-4 dark:border-slate-700/60 dark:bg-slate-800/80">
                    <span className="text-sm font-bold text-brand-600 dark:text-brand-400">{base}</span>
                  </div>
                </div>

                {/* Fee breakdown under amount */}
                {numAmount > 0 && selectedTxType && (
                  <div className="space-y-1 pt-1">
                    <div className="flex items-center justify-between gap-4">
                      <span className="text-xs text-slate-500 dark:text-slate-400">
                        {t("agent.sendRemittance.feesCharges")}
                      </span>
                      <span className="text-xs font-bold text-rose-500 dark:text-rose-400">
                        -{charges.total.toFixed(2)} {base}
                      </span>
                    </div>
                    <div className="flex items-center justify-between gap-4">
                      <span className="text-xs text-slate-500 dark:text-slate-400">
                        {t("agent.sendRemittance.amountWillConvert")}
                      </span>
                      <span className="text-xs font-bold text-slate-700 dark:text-slate-200">
                        {netAmount.toFixed(2)} {base}
                      </span>
                    </div>
                  </div>
                )}
              </div>

              {/* Recipient Gets */}
              <div className="flex flex-col gap-1.5 p-4 sm:p-6">
                <label className="block text-[length:var(--text-sm-fixed)] font-medium capitalize text-slate-500 dark:text-slate-400">
                  {t("agent.sendRemittance.receiverCurrencyLabel")}
                </label>
                <div className="flex items-center gap-3">
                  <div ref={currencyRef} className="flex-1">
                    <Select<CurrencyOpt>
                      instanceId="currency-select"
                      placeholder={t("agent.sendRemittance.currencyPlaceholder")}
                      isSearchable
                      inputValue={currencySearch}
                      onInputChange={(val, { action }) => { if (action === "input-change") setCurrencySearch(val); }}
                      menuIsOpen={currencyMenu.menuIsOpen}
                      onMenuOpen={currencyMenu.onMenuOpen}
                      onMenuClose={() => { currencyMenu.onMenuClose(); setCurrencySearch(""); }}
                      unstyled
                      components={SEARCHABLE_SELECT_COMPONENTS}
                      classNames={SELECT_CLS}
                      {...MENU_PORTAL_PROPS}
                      options={receiverCurrencyOptions}
                      value={receiverCurrencyOptions.find((o) => o.value === receiverCurrencyId) ?? null}
                      onChange={(opt) => setReceiverCurrencyId(opt?.value ?? null)}
                      filterOption={(option, input) => {
                        if (!input) return true;
                        const lower = input.toLowerCase();
                        return option.data.label.toLowerCase().includes(lower) || option.data.name.toLowerCase().includes(lower);
                      }}
                      formatOptionLabel={(opt, { context }) =>
                        context === "menu" ? (
                          <div className="flex items-center gap-3">
                            {opt.flag ? (
                              <img src={opt.flag} alt="" aria-hidden className="h-7 w-7 shrink-0 rounded-full object-cover" />
                            ) : (
                              <span className="h-7 w-7 shrink-0 rounded-full bg-slate-200 dark:bg-slate-700" />
                            )}
                            <span className="flex-1 truncate text-sm text-slate-900 dark:text-white">{opt.name}</span>
                            <span className="text-xs font-bold text-slate-400 dark:text-slate-500">{opt.label}</span>
                          </div>
                        ) : (
                          <div className="flex items-center gap-2">
                            {opt.flag && (
                              <img src={opt.flag} alt="" aria-hidden className="h-5 w-5 shrink-0 rounded-full object-cover" />
                            )}
                            <span className="text-sm font-semibold text-slate-800 dark:text-slate-100">{opt.label}</span>
                          </div>
                        )
                      }
                    />
                  </div>
                  {selectedCurrency && numAmount > 0 && (
                    <div className="flex h-12 items-center rounded-xl border border-emerald-200 bg-emerald-50/80 px-5 dark:border-emerald-700/40 dark:bg-emerald-900/20">
                      <span className="text-base font-bold tabular-nums text-emerald-700 dark:text-emerald-300">
                        {willGet}
                      </span>
                      <span className="ml-1.5 text-xs font-bold text-emerald-600/70 dark:text-emerald-400/70">
                        {selectedCurrency.code}
                      </span>
                    </div>
                  )}
                </div>
              </div>

              {/* Transfer Method */}
              <div className="flex flex-col gap-1.5 p-4 sm:p-6">
                <label className="block text-[length:var(--text-sm-fixed)] font-medium capitalize text-slate-500 dark:text-slate-400">
                  {t("agent.sendRemittance.receivingMethodLabel")}
                </label>
                <Select
                  instanceId="txtype-select"
                  placeholder={t("agent.sendRemittance.transferMethodPlaceholder")}
                  isSearchable={false}
                  unstyled
                  classNames={SELECT_CLS}
                  {...MENU_PORTAL_PROPS}
                  options={txTypes.map((t) => ({ value: t.id, label: t.name }))}
                  value={txTypeId ? { value: txTypeId, label: selectedTxType?.name ?? "" } : null}
                  onChange={(opt) => {
                    setTxTypeId(opt?.value ?? null);
                    setTxTypeName(txTypes.find((t) => t.id === opt?.value)?.name ?? "");
                    setRecipientSlug("");
                  }}
                />
              </div>

              {/* Sender */}
              <div className="flex flex-col gap-1.5 p-4 sm:p-6">
                <div className="flex items-center justify-between">
                  <label className="block text-[length:var(--text-sm-fixed)] font-medium capitalize text-slate-500 dark:text-slate-400">
                    {t("agent.sendRemittance.senderLabel")}
                  </label>
                  <Link
                    href="/agent/my-senders"
                    className="flex items-center gap-1 text-xs font-bold text-brand-600 hover:text-brand-700 dark:text-brand-400"
                  >
                    <UserPlus className="icon-xs" />
                    {t("agent.sendRemittance.addSender")}
                  </Link>
                </div>
                <div ref={senderRef}>
                  <Select
                    instanceId="sender-select"
                    placeholder={t("agent.sendRemittance.senderPlaceholder")}
                    isSearchable
                    inputValue={senderSearch}
                    onInputChange={(val, { action }) => { if (action === "input-change") setSenderSearch(val); }}
                    menuIsOpen={senderMenu.menuIsOpen}
                    onMenuOpen={senderMenu.onMenuOpen}
                    onMenuClose={() => { senderMenu.onMenuClose(); setSenderSearch(""); }}
                    unstyled
                    components={SEARCHABLE_SELECT_COMPONENTS}
                    classNames={SELECT_CLS}
                    {...MENU_PORTAL_PROPS}
                    options={senders.map((s) => ({ value: s.slug, label: s.name }))}
                    value={senderSlug ? { value: senderSlug, label: selectedSender?.name ?? "" } : null}
                    onChange={(opt) => setSenderSlug(opt?.value ?? "")}
                  />
                </div>
              </div>

              {/* Recipient */}
              <div className="flex flex-col gap-1.5 p-4 sm:p-6">
                <div className="flex items-center justify-between">
                  <label className="block text-[length:var(--text-sm-fixed)] font-medium capitalize text-slate-500 dark:text-slate-400">
                    {t("agent.sendRemittance.recipientLabel")}
                  </label>
                  <Link
                    href="/agent/my-recipients"
                    className="flex items-center gap-1 text-xs font-bold text-brand-600 hover:text-brand-700 dark:text-brand-400"
                  >
                    <Users className="icon-xs" />
                    {t("agent.sendRemittance.addRecipient")}
                  </Link>
                </div>
                {txTypeName ? (
                  recipientsLoading ? (
                    <div className="h-12 animate-pulse rounded-xl bg-slate-100 dark:bg-slate-800" />
                  ) : (
                    <div ref={recipientRef}>
                      <Select
                        instanceId="recipient-select"
                        placeholder={t("agent.sendRemittance.recipientPlaceholder")}
                        isSearchable
                        inputValue={recipientSearch}
                        onInputChange={(val, { action }) => { if (action === "input-change") setRecipientSearch(val); }}
                        menuIsOpen={recipientMenu.menuIsOpen}
                        onMenuOpen={recipientMenu.onMenuOpen}
                        onMenuClose={() => { recipientMenu.onMenuClose(); setRecipientSearch(""); }}
                        unstyled
                        components={SEARCHABLE_SELECT_COMPONENTS}
                        classNames={SELECT_CLS}
                        {...MENU_PORTAL_PROPS}
                        options={recipients.map((r) => ({ value: r.slug, label: r.name }))}
                        value={
                          recipientSlug
                            ? { value: recipientSlug, label: selectedRecipient?.name ?? "" }
                            : null
                        }
                        onChange={(opt) => setRecipientSlug(opt?.value ?? "")}
                        noOptionsMessage={() => t("agent.sendRemittance.noRecipientsForMethod")}
                      />
                    </div>
                  )
                ) : (
                  <div className="flex h-12 items-center rounded-xl border border-dashed border-slate-200 px-4 text-sm text-slate-400 dark:border-slate-700">
                    {t("agent.sendRemittance.selectMethodFirst")}
                  </div>
                )}
              </div>

              {/* Send Button */}
              <div className="p-4 sm:p-6">
                <Button
                  size="lg"
                  disabled={!canSubmit || isPending}
                  onClick={handleSend}
                  className={cn(
                    "w-full font-semibold tracking-wide transition-all duration-300",
                    canSubmit
                      ? "bg-gradient-to-r from-brand-600 to-brand-500 text-white shadow-lg shadow-brand-500/25 hover:from-brand-500 hover:to-brand-400 hover:-translate-y-0.5"
                      : "opacity-60",
                  )}
                >
                  {isPending ? (
                    <>
                      <Loader2 className="mr-2 h-5 w-5 animate-spin" />
                      {t("agent.sendRemittance.sending")}
                    </>
                  ) : (
                    <>
                      <Send className={cn("me-2 h-5 w-5", dir === "rtl" && "[transform:scaleX(-1)]")} />
                      {t("agent.sendRemittance.sendTransfer")}
                    </>
                  )}
                </Button>
              </div>
            </div>
          </div>

          {/* ── Right: Summary ── */}
          <div className="space-y-4">
            <div 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="border-b border-slate-100 p-4 dark:border-slate-800/60 sm:p-6">
                <h2 className="text-[length:var(--text-lg-fixed)] font-semibold text-slate-900 dark:text-white">
                  {t("agent.sendRemittance.summaryTitle")}
                </h2>
              </div>
              <div className="pb-3 sm:pb-4">
                <SummaryRow
                  icon={Send}
                  label={t("agent.sendRemittance.sendingAmount")}
                  value={numAmount > 0 ? `${numAmount.toFixed(2)} ${base}` : "—"}
                  highlight
                />
                <SummaryRow
                  icon={ArrowUpDown}
                  label={t("agent.sendRemittance.exchangeRateLabel")}
                  value={
                    selectedCurrency
                      ? `1 ${base} = ${Number(selectedCurrency.rate).toFixed(2)} ${selectedCurrency.code}`
                      : "—"
                  }
                />
                <SummaryRow
                  icon={TrendingUp}
                  label={t("agent.sendRemittance.totalFees")}
                  value={
                    numAmount > 0 && selectedTxType
                      ? `${charges.total.toFixed(2)} ${base}`
                      : "—"
                  }
                />
                <SummaryRow
                  icon={ArrowUpDown}
                  label={t("agent.sendRemittance.amountWillConvert")}
                  value={
                    numAmount > 0 && selectedTxType
                      ? `${netAmount.toFixed(2)} ${base}`
                      : "—"
                  }
                />
                <SummaryRow
                  icon={CheckCircle2}
                  label={t("agent.sendRemittance.willGetAmount")}
                  value={
                    selectedCurrency && numAmount > 0
                      ? `${willGet} ${selectedCurrency.code}`
                      : "—"
                  }
                  highlight
                />
              </div>

              {/* Total Payable */}
              {numAmount > 0 && (
                <div className="mb-6 rounded-xl bg-gradient-to-r from-brand-50 to-purple-50 px-6 py-4 dark:from-brand-500/10 dark:to-purple-500/10 sm:mb-7 sm:px-7 sm:py-5">
                  <div className="flex items-center justify-between">
                    <span className="flex items-center gap-2.5 text-[length:var(--text-sm-fixed)] font-semibold capitalize text-brand-600/80 dark:text-brand-400/80">
                      <span className="grid h-7 w-7 shrink-0 place-items-center rounded-lg bg-brand-100/70 dark:bg-brand-500/15">
                        <Wallet className="h-3.5 w-3.5 text-brand-600 dark:text-brand-400" aria-hidden />
                      </span>
                      {t("agent.sendRemittance.totalPayable")}
                    </span>
                    <span className="text-[length:var(--text-lg-fixed)] font-bold tabular-nums text-brand-700 dark:text-brand-300">
                      {totalPayable.toFixed(2)} {base}
                    </span>
                  </div>
                </div>
              )}
            </div>

            {/* Tip Card */}
            <div className="rounded-3xl border border-amber-200/60 bg-amber-50/60 p-6 dark:border-amber-500/20 dark:bg-amber-500/10 sm:p-7">
              <p className="text-xs font-semibold text-amber-700 dark:text-amber-300">
                {t("agent.sendRemittance.tipText")}
              </p>
            </div>
          </div>
        </m.div>
      )}

      {/* Transaction Log */}
      <m.div variants={itemVariants}>
        <RemittanceLog />
      </m.div>

      </m.div>
    </Container>
  );
}
