"use client";

import React, { useRef, useState } from "react";
import { m } from "framer-motion";
import Select from "react-select";
import { SEARCHABLE_SELECT_COMPONENTS } from "@/components/common/SearchableSelectParts";
import {
  CheckCircle2,
  Clock,
  Loader2,
  UploadCloud,
  ArrowRight,
  CreditCard,
  AlertCircle,
  ScrollText,
} from "lucide-react";
import { Container } from "@/components/common/Container";
import { Button } from "@/components/common/Button";
import { AgentMoneyOutSkeleton } from "@/components/skeletons/AgentMoneyOutSkeleton";
import {
  useMoneyOutData,
  useMoneyOutSubmit,
  useMoneyOutConfirm,
  type MoneyOutSubmitResult,
  type DynamicField,
} from "@/hooks/queries/useAgentMoneyOut";
import { useAgentTransactions, type MoneyOutTx } from "@/hooks/queries/useAgentDashboard";
import { notify } from "@/lib/notify";
import { cn } from "@/lib/utils";
import { useTranslation } from "@/hooks/useTranslation";
import { useAgentKycGate } from "@/hooks/useAgentKycGate";
import { AgentKycGate } from "@/components/agent/AgentKycGate";
import { useControlledSelectMenu } from "@/hooks/useControlledSelectMenu";

// ─── Shared styles ────────────────────────────────────────────────────────────

const INPUT =
  "h-12 w-full rounded-xl border border-slate-200/80 bg-slate-50/50 px-4 text-[length:var(--text-sm)] font-medium text-slate-900 outline-none transition-all placeholder:text-slate-400 hover:border-slate-300 hover:bg-slate-50 focus:border-brand-500 focus:bg-white focus:ring-4 focus:ring-brand-500/10 dark:border-slate-700/60 dark:bg-slate-900/50 dark:text-white dark:hover:border-slate-600 dark:hover:bg-slate-900/80 dark:focus:border-brand-400 dark:focus:bg-slate-900 dark:focus:ring-brand-400/10 backdrop-blur-sm";
const LABEL = "text-[length:var(--text-sm)] font-medium capitalize tracking-wider text-slate-500 dark:text-slate-400";

const SELECT_STYLES = {
  input: (base: object) => ({ ...base, outline: "none", boxShadow: "none", border: "none", caretColor: "auto" }),
};

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 } },
};

const SELECT_CLS = {
  control: ({ menuIsOpen }: { menuIsOpen: boolean }) =>
    cn(
      INPUT,
      "flex cursor-pointer items-center shadow-sm !min-h-12 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/80 bg-white/95 shadow-xl backdrop-blur-xl dark:border-slate-700/80 dark:bg-slate-900/95 z-50",
  menuList: () => "max-h-56 overflow-y-auto",
  option: ({ isFocused }: { isFocused: boolean }) =>
    cn(
      "px-4 py-2.5 text-[length:var(--text-sm)] cursor-pointer transition-colors",
      isFocused
        ? "bg-brand-50/80 text-brand-700 dark:bg-brand-500/20 dark:text-brand-300 font-semibold"
        : "text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800/50 font-medium",
    ),
  placeholder: () => "text-slate-400 text-[length:var(--text-sm)] font-medium",
  singleValue: () => "text-[length:var(--text-sm)] font-semibold text-slate-800 dark:text-slate-100",
  valueContainer: () => "px-0",
  dropdownIndicator: () => "cursor-pointer text-slate-400 hover:text-slate-600 dark:text-slate-500 dark:hover:text-slate-300",
};

// ─── Breakdown row ─────────────────────────────────────────────────────────────

function BreakdownRow({
  label,
  value,
  highlight,
}: {
  label: string;
  value: string;
  highlight?: boolean;
}) {
  return (
    <div className="flex items-center justify-between px-4 py-3.5">
      <span className="text-[length:var(--text-sm)] font-medium text-slate-500 dark:text-slate-400">{label}</span>
      <span className={cn(
        "text-[length:var(--text-sm)] font-semibold tabular-nums",
        highlight ? "text-emerald-600 dark:text-emerald-400" : "text-slate-800 dark:text-slate-100"
      )}>
        {value}
      </span>
    </div>
  );
}

// ─── Dynamic field renderer ────────────────────────────────────────────────────

function DynamicFieldInput({
  field,
  value,
  onChange,
}: {
  field: DynamicField;
  value: string | File | null;
  onChange: (v: string | File) => void;
}) {
  const inputRef = useRef<HTMLInputElement | null>(null);
  const [dragging, setDragging] = useState(false);
  const [preview, setPreview] = useState<string | null>(null);
  const { t } = useTranslation();

  if (field.type === "file") {
    function handleFile(f: File) {
      onChange(f);
      const reader = new FileReader();
      reader.onloadend = () => setPreview(reader.result as string);
      reader.readAsDataURL(f);
    }

    return (
      <div className="flex flex-col gap-1.5">
        <div className="flex items-center justify-between">
          <label className={LABEL}>
            {field.label}
            {field.required && <span className="ms-1 text-rose-500">*</span>}
          </label>
          {value instanceof File && (
            <button
              type="button"
              onClick={() => { onChange(""); setPreview(null); }}
              className="text-[length:var(--text-xs)] font-semibold text-rose-500 hover:text-rose-600 dark:hover:text-rose-400 transition-colors"
            >
              {t("agent.moneyOut.removeFile")}
            </button>
          )}
        </div>
        <button
          type="button"
          onDragOver={(e) => { e.preventDefault(); setDragging(true); }}
          onDragLeave={() => setDragging(false)}
          onDrop={(e) => {
            e.preventDefault();
            setDragging(false);
            const f = e.dataTransfer.files[0];
            if (f) handleFile(f);
          }}
          onClick={() => inputRef.current?.click()}
          className={cn(
            "group relative flex min-h-[140px] w-full cursor-pointer flex-col items-center justify-center gap-3 overflow-hidden rounded-2xl border-2 border-dashed transition-all duration-200",
            dragging
              ? "border-brand-500 bg-brand-50/80 dark:border-brand-400 dark:bg-brand-500/10 scale-[1.02]"
              : preview
                ? "border-emerald-300 bg-emerald-50/30 dark:border-emerald-700/50 dark:bg-emerald-900/10"
                : "border-slate-200 bg-slate-50 hover:border-brand-300 hover:bg-slate-100 dark:border-slate-700 dark:bg-slate-800/50 dark:hover:border-slate-600 dark:hover:bg-slate-800",
          )}
        >
          {preview ? (
            <div className="absolute inset-0 p-2">
              <img src={preview} alt={field.label} className="h-full w-full object-contain rounded-xl" />
              <div className="absolute inset-0 bg-black/0 transition-colors group-hover:bg-black/10" />
            </div>
          ) : (
            <>
              <div className={cn(
                "rounded-full p-3 transition-colors duration-300",
                dragging ? "bg-brand-100 text-brand-600 dark:bg-brand-500/20 dark:text-brand-400" : "bg-white text-slate-400 shadow-sm dark:bg-slate-900 dark:text-slate-500"
              )}>
                <UploadCloud className="icon-xl" />
              </div>
              <div className="text-center">
                <p className="text-[length:var(--text-sm)] font-medium text-slate-600 dark:text-slate-300">
                  {t("agent.moneyOut.dropFileHere")}{" "}
                  <span className="text-brand-600 dark:text-brand-400 hover:underline">{t("agent.moneyOut.browse")}</span>
                </p>
                <p className="mt-1 text-[length:var(--text-xs)] font-medium text-slate-400 dark:text-slate-500">
                  {field.validation.mimes.map((m) => m.trim()).join(", ").toUpperCase()} up to{" "}
                  {field.validation.max}MB
                </p>
              </div>
            </>
          )}
          <input
            ref={inputRef}
            type="file"
            accept={field.validation.mimes.map((m) => `image/${m.trim()}`).join(",")}
            className="sr-only"
            onChange={(e) => {
              const f = e.target.files?.[0];
              if (f) handleFile(f);
              e.target.value = "";
            }}
          />
        </button>
        {value instanceof File && (
          <div className="flex items-center gap-2 text-[length:var(--text-xs)] font-semibold text-emerald-600 dark:text-emerald-400">
            <CheckCircle2 className="icon-sm" />
            <span className="truncate">{value.name}</span>
            <span className="opacity-70">({(value.size / 1024).toFixed(0)} KB)</span>
          </div>
        )}
      </div>
    );
  }

  return (
    <div className="flex flex-col gap-1.5">
      <label className={LABEL}>
        {field.label}
        {field.required && <span className="ms-1 text-rose-500">*</span>}
      </label>
      <input
        type="text"
        value={typeof value === "string" ? value : ""}
        onChange={(e) => onChange(e.target.value)}
        placeholder={`Enter ${field.label.toLowerCase()}`}
        className={INPUT}
      />
    </div>
  );
}

// ─── Step 1: Submit form ───────────────────────────────────────────────────────

function SubmitStep({
  baseCurrency,
  gateways,
  minLimit,
  maxLimit,
  onSuccess,
}: {
  baseCurrency: string;
  gateways: { name: string; alias: string }[];
  minLimit: string;
  maxLimit: string;
  onSuccess: (result: MoneyOutSubmitResult) => void;
}) {
  const [gateway, setGateway] = useState("");
  const [gatewaySearch, setGatewaySearch] = useState("");
  const gatewayRef = useRef<HTMLDivElement>(null);
  const gatewayMenu = useControlledSelectMenu(gatewayRef, "select-menu-portal");
  const [amount, setAmount] = useState("");
  const { mutate: submit, isPending } = useMoneyOutSubmit();
  const { t } = useTranslation();

  const gatewayOptions = gateways.map((g) => ({ value: g.alias, label: g.name }));

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!gateway || !amount) return;
    submit(
      { amount, payment_gateway: gateway },
      {
        onSuccess: (result) => onSuccess(result),
        onError: (err: Error) => notify(err.message || t("agent.moneyOut.submissionFailed"), "error"),
      },
    );
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      <div className="flex flex-col gap-1.5">
        <label className={LABEL}>
          {t("agent.moneyOut.gatewayLabel")} <span className="text-rose-500">*</span>
        </label>
        <div ref={gatewayRef}>
          <Select
            unstyled
            isSearchable
            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}
            options={gatewayOptions}
            value={gateway ? gatewayOptions.find((o) => o.value === gateway) ?? null : null}
            onChange={(opt) => setGateway(opt?.value ?? "")}
            placeholder={t("agent.moneyOut.gatewayPlaceholder")}
            classNames={SELECT_CLS}
            styles={SELECT_STYLES}
          />
        </div>
      </div>

      <div className="flex flex-col gap-1.5">
        <div className="flex items-center justify-between">
          <label className={LABEL}>
            {t("agent.moneyOut.amountLabel").replace("{currency}", baseCurrency)} <span className="text-rose-500">*</span>
          </label>
        </div>
        <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">
            {baseCurrency}
          </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={minLimit}
              max={maxLimit}
              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"
            />
            <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.moneyOut.minLimit").replace("{n}", String(minLimit))}
              </span>
            </div>
          </div>
        </div>
      </div>

      <Button
        type="submit"
        size="md"
        disabled={isPending || !gateway || !amount}
        className={cn(
          "group w-full font-bold tracking-wide transition-all duration-300",
          !isPending && gateway && amount
            ? "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:shadow-brand-500/40 hover:-translate-y-0.5 active:translate-y-0 dark:from-brand-500 dark:to-brand-400 dark:shadow-brand-900/20"
            : ""
        )}
      >
        {isPending ? (
          <>
            <Loader2 className="me-2 h-5 w-5 animate-spin" />
            {t("agent.moneyOut.calculating")}
          </>
        ) : (
          <>
            {t("agent.moneyOut.previewWithdrawal")}
            <ArrowRight className="ms-2 h-4 w-4 transition-transform group-hover:translate-x-1 rtl:-scale-x-100" />
          </>
        )}
      </Button>
    </form>
  );
}

// ─── Step 2: Confirm form ──────────────────────────────────────────────────────

function ConfirmStep({
  result,
  onBack,
  onSuccess,
}: {
  result: MoneyOutSubmitResult;
  onBack: () => void;
  onSuccess: () => void;
}) {
  const { temporary_data, input_fields } = result;
  const bd = temporary_data.data;
  const cur = bd.base_currency.currency;

  const [fields, setFields] = useState<Record<string, string | File | null>>(() =>
    Object.fromEntries(input_fields.map((f) => [f.name, null])),
  );
  const { mutate: confirm, isPending } = useMoneyOutConfirm();
  const { t } = useTranslation();

  function handleConfirm(e: React.FormEvent) {
    e.preventDefault();

    const screenshot = fields["screenshot"];
    const trx_id = (fields["trx_id"] as string) ?? "";

    if (!screenshot || !(screenshot instanceof File)) {
      notify(t("agent.moneyOut.screenshotRequired"), "error");
      return;
    }

    confirm(
      { identifier: temporary_data.identifier, trx_id, screenshot },
      {
        onSuccess: () => {
          notify(t("agent.moneyOut.submittedSuccessfully"), "success");
          onSuccess();
        },
        onError: (err: Error) => notify(err.message || t("agent.moneyOut.confirmationFailed"), "error"),
      },
    );
  }

  return (
    <div className="space-y-5">
      {/* Breakdown */}
      <div className="space-y-2">
        <p className={cn(LABEL, "px-1")}>
          {t("agent.moneyOut.breakdownTitle")}
        </p>

        <div className="overflow-hidden rounded-xl border border-slate-200/60 dark:border-slate-800/60">
          {/* Rows */}
          <div className="divide-y divide-slate-100/60 dark:divide-slate-800/40">
            <BreakdownRow label={t("agent.moneyOut.labelGateway")} value={bd.payment_gateway.name} />
            <BreakdownRow label={t("agent.moneyOut.labelAmount")} value={`${bd.amount.toFixed(2)} ${cur}`} />
            <BreakdownRow label={t("agent.moneyOut.labelFees")} value={`${bd.total_charge.toFixed(2)} ${cur}`} />
            {bd.agent_profit.agent_profit_status === "1" && (
              <BreakdownRow
                label={t("agent.moneyOut.labelCommission")}
                value={`+${bd.agent_profit.total_commission.toFixed(2)} ${cur}`}
                highlight
              />
            )}
            <BreakdownRow
              label={t("agent.moneyOut.labelWillGet")}
              value={`${(bd.amount * (bd.exchange_rate ?? 1)).toFixed(2)} ${bd.payment_gateway.currency ?? cur}`}
            />
          </div>

          {/* Total — bottom section of same container */}
          <div className="border-t-2 border-slate-200/60 bg-slate-50/80 px-4 py-4 dark:border-slate-800/60 dark:bg-slate-800/30">
            <div className="flex items-center justify-between gap-4">
              <div>
                <p className={LABEL}>
                  {t("agent.moneyOut.totalPayable")}
                </p>
                <p className="mt-0.5 text-[length:var(--text-xs)] text-slate-400 dark:text-slate-500">
                  {t("agent.moneyOut.totalPayableDesc")}
                </p>
              </div>
              <p className="text-[length:var(--text-2xl)] font-black tabular-nums text-brand-600 dark:text-brand-400">
                {bd.payable_amount.toFixed(2)}{" "}
                <span className="text-[length:var(--text-sm)] font-bold text-slate-400 dark:text-slate-500">{cur}</span>
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Dynamic confirm fields */}
      <form id="confirm-form" onSubmit={handleConfirm} className="space-y-6">
        {input_fields.map((field) => (
          <DynamicFieldInput
            key={field.name}
            field={field}
            value={fields[field.name] ?? null}
            onChange={(v) => setFields((prev) => ({ ...prev, [field.name]: v }))}
          />
        ))}
      </form>

      <div className="flex gap-3">
        <Button
          type="button"
          onClick={onBack}
          size="md"
          className="flex-1 bg-slate-100 text-slate-700 hover:bg-slate-200 hover:-translate-y-0.5 active:translate-y-0 active:scale-[0.98] font-bold tracking-wide transition-all dark:bg-slate-800 dark:text-slate-300 dark:hover:bg-slate-700 border border-slate-200 dark:border-slate-700 shadow-sm"
        >
          {t("agent.moneyOut.back")}
        </Button>
        <Button
          type="submit"
          form="confirm-form"
          size="md"
          disabled={isPending}
          className="group flex-1 bg-gradient-to-r from-brand-600 to-brand-500 font-bold tracking-wide text-white shadow-lg shadow-brand-500/25 transition-all hover:from-brand-500 hover:to-brand-400 hover:shadow-brand-500/40 hover:-translate-y-0.5 active:translate-y-0 active:scale-[0.98] dark:from-brand-500 dark:to-brand-400 dark:shadow-brand-900/20"
        >
          {isPending ? (
            <>
              <Loader2 className="me-2 h-5 w-5 animate-spin" />
              {t("agent.moneyOut.processing")}
            </>
          ) : (
            <>
              {t("agent.moneyOut.confirmWithdrawal")}
            </>
          )}
        </Button>
      </div>
    </div>
  );
}

// ─── Success state ─────────────────────────────────────────────────────────────

export function SuccessState({ onReset }: { onReset: () => void }) {
  const { t } = useTranslation();
  return (
    <div className="flex flex-col items-center justify-center gap-5 py-12 text-center animate-in fade-in slide-in-from-bottom-4 duration-500">
      <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 className="space-y-2">
        <h3 className="text-[length:var(--text-2xl)] font-black tracking-tight text-slate-900 dark:text-white">
          {t("agent.moneyOut.submittedTitle")}
        </h3>
        <p className="mx-auto max-w-xs text-[length:var(--text-sm)] font-medium text-slate-500 dark:text-slate-400">
          {t("agent.moneyOut.submittedDesc")}
        </p>
      </div>
      <Button
        size="md"
        onClick={onReset}
        className="mt-4 font-bold shadow-md hover:-translate-y-0.5 active:translate-y-0 active:scale-95 transition-all"
      >
        {t("agent.moneyOut.makeAnotherWithdrawal")}
      </Button>
    </div>
  );
}

// ─── Money Out Logs ────────────────────────────────────────────────────────────

const STATUS_MAP: Record<string, { label: string; cls: string }> = {
  pending:  { label: "Pending",   cls: "bg-amber-50 text-amber-700 dark:bg-amber-500/10 dark:text-amber-400" },
  complete: { label: "Complete",  cls: "bg-emerald-50 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-400" },
  success:  { label: "Success",   cls: "bg-emerald-50 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-400" },
  cancel:   { label: "Cancelled", cls: "bg-rose-50 text-rose-700 dark:bg-rose-500/10 dark:text-rose-400" },
  failed:   { label: "Failed",    cls: "bg-rose-50 text-rose-700 dark:bg-rose-500/10 dark:text-rose-400" },
  hold:     { label: "On Hold",   cls: "bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300" },
};

function StatusBadge({ status }: { status: string }) {
  const key = status.toLowerCase();
  const cfg = STATUS_MAP[key] ?? { label: status, cls: "bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300" };
  return (
    <span className={cn("badge capitalize font-medium text-[length:var(--text-sm-fixed)]", cfg.cls)}>
      {cfg.label}
    </span>
  );
}


function MoneyOutLogs() {
  const { data, isLoading, isError, refetch } = useAgentTransactions();
  const logs: MoneyOutTx[] = data?.money_out ?? [];
  const { t } = useTranslation();

  return (
    <div className="relative 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 gap-4 border-b border-slate-200/60 bg-slate-50/50 p-6 sm:p-7 dark:border-slate-800/60 dark:bg-slate-800/40">
        <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-rose-500 to-rose-600 text-white shadow-md">
          <ScrollText className="icon-lg" />
        </div>
        <div>
          <h2 className="text-[length:var(--text-lg-fixed)] font-bold tracking-tight text-slate-900 dark:text-white">
            {t("agent.moneyOut.logTitle")}
          </h2>
          <p className="text-[length:var(--text-sm)] font-medium text-slate-500 dark:text-slate-400">
            {isLoading
              ? t("agent.moneyOut.loading")
              : logs.length === 1
              ? t("agent.moneyOut.withdrawalCountOne")
              : t("agent.moneyOut.withdrawalCountOther").replace("{count}", String(logs.length))}
          </p>
        </div>
      </div>

      {/* Content */}
      {isLoading ? (
        <div className="divide-y divide-slate-100/60 dark:divide-slate-800/60">
          {Array.from({ length: 4 }).map((_, i) => (
            <div key={i} className="flex items-center gap-6 px-6 py-5 sm:px-8">
              <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" />
              <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-16 text-center">
          <AlertCircle className="h-8 w-8 text-rose-400" />
          <p className="text-[length:var(--text-sm)] font-bold text-slate-700 dark:text-slate-200">{t("agent.moneyOut.failedToLoadTransactions")}</p>
          <button
            onClick={() => refetch()}
            className="text-[length:var(--text-xs)] font-bold text-brand-600 hover:underline dark:text-brand-400"
          >
            {t("agent.moneyOut.tryAgain")}
          </button>
        </div>
      ) : logs.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">
            <Clock className="h-6 w-6 text-slate-400" />
          </div>
          <div>
            <p className="text-[length:var(--text-sm)] font-bold text-slate-600 dark:text-slate-300">{t("agent.moneyOut.noWithdrawals")}</p>
            <p className="text-[length:var(--text-xs)] text-slate-400 mt-0.5">{t("agent.moneyOut.noWithdrawalsDesc")}</p>
          </div>
        </div>
      ) : (
        <div className="overflow-x-auto">
          <table className="w-full min-w-max border-collapse">
            <thead>
              <tr className="border-b border-slate-100/60 bg-slate-50/60 dark:border-slate-800/60 dark:bg-slate-800/30">
                <th className="whitespace-nowrap px-6 py-3 text-start text-[length:var(--text-sm)] font-bold capitalize text-slate-600 dark:text-slate-300 sm:px-7">{t("agent.moneyOut.colTransaction")}</th>
                <th className="whitespace-nowrap px-3 py-3 text-start text-[length:var(--text-sm)] font-bold capitalize text-slate-600 dark:text-slate-300">{t("agent.moneyOut.colAmount")}</th>
                <th className="whitespace-nowrap px-3 py-3 text-start text-[length:var(--text-sm)] font-bold capitalize text-slate-600 dark:text-slate-300">{t("agent.moneyOut.colMethod")}</th>
                <th className="whitespace-nowrap px-3 py-3 text-start text-[length:var(--text-sm)] font-bold capitalize text-slate-600 dark:text-slate-300">{t("agent.moneyOut.colDate")}</th>
                <th className="whitespace-nowrap px-3 py-3 text-start text-[length:var(--text-sm)] font-bold capitalize text-slate-600 dark:text-slate-300">{t("agent.moneyOut.colTime")}</th>
                <th className="whitespace-nowrap px-3 py-3 pe-6 text-start text-[length:var(--text-sm)] font-bold capitalize text-slate-600 dark:text-slate-300 sm:pe-7">{t("agent.moneyOut.colStatus")}</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100/60 dark:divide-slate-800/60">
              {logs.map((tx, i) => (
                <tr
                  key={tx.transaction_id}
                  className={cn(
                    "transition-colors hover:bg-rose-50/20 dark:hover:bg-rose-500/5",
                    i % 2 !== 0 && "bg-slate-50/40 dark:bg-slate-800/10",
                  )}
                >
                  <td className="whitespace-nowrap px-6 py-4 text-start sm:px-7">
                    <p className="text-[length:var(--text-sm)] font-bold text-brand-600 dark:text-brand-400">#{tx.transaction_id}</p>
                    <p className="mt-0.5 text-[length:var(--text-xs)] font-medium text-slate-400">{tx.sender_currency}</p>
                  </td>
                  <td className="whitespace-nowrap px-3 py-4 text-start">
                    <p className="text-[length:var(--text-sm)] font-black tabular-nums text-rose-500 dark:text-rose-400">
                      <span dir="ltr" className="inline-flex items-baseline gap-1">
                        {Number(tx.request_amount).toFixed(2)}
                        <span className="text-[length:var(--text-xs)] font-semibold text-slate-400">{tx.sender_currency}</span>
                      </span>
                    </p>
                    <p className="mt-0.5 text-[length:var(--text-xs)] font-medium text-slate-400">{t("agent.moneyOut.fee").replace("{n}", Number(tx.total_charge).toFixed(2))}</p>
                  </td>
                  <td className="whitespace-nowrap px-3 py-4 text-start text-[length:var(--text-sm)] font-bold text-slate-800 dark:text-slate-200">
                    {tx.payment_method}
                  </td>
                  <td className="whitespace-nowrap px-3 py-4 text-start text-[length:var(--text-sm-fixed)] font-medium text-slate-400">
                    {new Date(tx.created_at).toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric" })}
                  </td>
                  <td className="whitespace-nowrap px-3 py-4 text-start text-[length:var(--text-sm-fixed)] font-medium text-slate-400">
                    <span dir="ltr">
                      {new Date(tx.created_at).toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit" })}
                    </span>
                  </td>
                  <td className="whitespace-nowrap px-3 py-4 pe-6 text-start sm:pe-7">
                    <StatusBadge status={tx.status} />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

// ─── Main view ─────────────────────────────────────────────────────────────────

type Step = "form" | "confirm" | "success";

export function AgentMoneyOutView() {
  const { data, isLoading, isError } = useMoneyOutData();
  const [step, setStep] = useState<Step>("form");
  const [submitResult, setSubmitResult] = useState<MoneyOutSubmitResult | null>(null);
  const { t } = useTranslation();
  const kycGateStatus = useAgentKycGate();

  if (isLoading) return <AgentMoneyOutSkeleton />;

  if (isError || !data) {
    return (
      <Container className="max-w-full pb-10">
        <div className="flex flex-col items-center gap-3 rounded-3xl border border-rose-200 bg-rose-50 p-16 text-center dark:border-rose-500/20 dark:bg-rose-500/10">
          <p className="font-semibold text-slate-900 dark:text-white">{t("agent.moneyOut.failedToLoad")}</p>
        </div>
      </Container>
    );
  }

  if (kycGateStatus) {
    return <AgentKycGate status={kycGateStatus} />;
  }

  const stepNum = step === "form" ? 1 : step === "confirm" ? 2 : 3;
  const STEPS = [t("agent.moneyOut.stepWithdrawalDetails"), t("agent.moneyOut.stepReviewConfirm"), t("agent.moneyOut.stepCompleted")];

  return (
    <Container className="max-w-full space-y-6 lg:space-y-8">
      <m.div variants={containerVariants} initial="hidden" animate="visible" className="space-y-6 lg:space-y-8">

        {/* 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-brand-500 to-accent-500 text-white shadow-lg">
              <CreditCard className="icon-xl" />
            </div>
            <div>
              <h1 className="text-[length:var(--text-2xl)] font-bold tracking-tight text-slate-900 dark:text-white">{t("agent.moneyOut.title")}</h1>
              <p className="mt-1 text-[length:var(--text-sm)] text-slate-500 dark:text-slate-400">{t("agent.moneyOut.subtitle")}</p>
            </div>
          </header>
        </m.div>

        {/* Step indicator — outside card */}
        <m.div variants={itemVariants}>
          <div className="flex w-full items-start justify-center 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 min-w-0 flex-1 flex-col items-center gap-1.5 px-1 sm:px-2">
                  <div
                    className={cn(
                      "grid h-7 w-7 shrink-0 place-items-center rounded-full text-[length:var(--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(
                      "text-center text-[length:var(--text-sm)] font-medium capitalize tracking-wider transition-colors duration-300",
                      isActive
                        ? "text-brand-600 dark:text-brand-400"
                        : isCompleted
                          ? "text-slate-500 dark:text-slate-400"
                          : "text-slate-400 dark:text-slate-600",
                    )}
                  >
                    {label}
                  </span>
                </div>,
                ...(!isLast ? [
                  <div key={`conn-${i}`} className="relative mx-1 mt-3 h-0.5 w-6 shrink-0 overflow-hidden rounded-full bg-slate-200 dark:bg-slate-700/60 sm:mx-2 sm:w-20">
                    <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>

        {/* Form card */}
        <m.div variants={itemVariants}>
          <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">

            {/* Step content */}
            <div className="p-6 sm:p-7">
              {step === "form" && (
                <div className="animate-in fade-in slide-in-from-bottom-4 duration-500">
                  <div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                    <div>
                      <h2 className="text-[length:var(--text-lg-fixed)] font-bold text-slate-900 dark:text-white">{t("agent.moneyOut.withdrawalDetailsTitle")}</h2>
                      <p className="mt-1 text-[length:var(--text-sm)] font-medium text-slate-500 dark:text-slate-400">
                        {t("agent.moneyOut.withdrawalDetailsDesc")}
                      </p>
                    </div>
                    <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.moneyOut.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">
                          {data.limits_data.min_limit}
                          <span className="text-slate-400">–</span>
                          {data.limits_data.max_limit}
                          <span className="text-brand-500 dark:text-brand-400">{data.base_currency}</span>
                        </span>
                      </p>
                    </div>
                  </div>
                  <SubmitStep
                    baseCurrency={data.base_currency}
                    gateways={data.payment_gateway}
                    minLimit={data.limits_data.min_limit}
                    maxLimit={data.limits_data.max_limit}
                    onSuccess={(result) => {
                      setSubmitResult(result);
                      setStep("confirm");
                    }}
                  />
                </div>
              )}

              {step === "confirm" && submitResult && (
                <div className="animate-in fade-in slide-in-from-right-4 duration-500">
                  <div className="mb-5">
                    <h2 className="text-[length:var(--text-xl)] font-bold text-slate-900 dark:text-white">{t("agent.moneyOut.reviewConfirmTitle")}</h2>
                    <p className="mt-1 text-[length:var(--text-sm)] font-medium text-slate-500 dark:text-slate-400">
                      {t("agent.moneyOut.reviewConfirmDesc")}
                    </p>
                  </div>
                  <ConfirmStep
                    result={submitResult}
                    onBack={() => setStep("form")}
                    onSuccess={() => setStep("success")}
                  />
                </div>
              )}

              {step === "success" && (
                <SuccessState
                  onReset={() => {
                    setSubmitResult(null);
                    setStep("form");
                  }}
                />
              )}
            </div>
          </div>
        </m.div>

        {/* Money Out Logs */}
        <m.div variants={itemVariants}>
          <MoneyOutLogs />
        </m.div>

      </m.div>
    </Container>
  );
}
