﻿"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { AgentHeader } from "@/roles/agent/components/agent-header";
import { getClientSession, validateSessionData } from "@/features/auth";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Wallet,
  Clock,
  CheckCircle,
  CheckCircle2,
  XCircle,
  Plus,
  Send,
  IndianRupee,
  TrendingUp,
  CreditCard,
  Loader2,
  Trash2,
  Building,
  ArrowDownToLine,
  AlertCircle,
  Calendar,
  Search,
  Filter,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { toast } from "sonner";
import {
  createMyPaymentMethodAction,
  deleteMyPaymentMethodAction,
  getMyPaymentMethodsAction,
} from "@/features/payment/actions/payment-methods-actions";
import { getAgentWithdrawalRequestsAction } from "@/features/payment/actions/withdrawals-actions";
import type { PaymentMethodItem } from "@/core/api/services/payment-methods";
import type { WithdrawalPagination } from "@/core/api/services/withdrawals";
import type {
  WithdrawalStats,
  WithdrawRequest,
  WithdrawStatus,
} from "@/features/payment/services/withdrawals.service";

type AgentWithdrawalTabStatus = WithdrawStatus;

interface WithdrawalTabState {
  withdrawals: WithdrawRequest[];
  pagination: WithdrawalPagination;
  isLoading: boolean;
  error: string | null;
  loaded: boolean;
}

function getMethodLabel(method: PaymentMethodItem): string {
  switch (method.method_type) {
    case "NET_BANKING":
      return `${method.details.bank_name || method.provider_name} - ${String(method.details.account_number ?? "").slice(-4) ? `****${String(method.details.account_number).slice(-4)}` : ""}`;
    case "UPI":
      return `UPI - ${method.details.upi_id || method.provider_name}`;
    case "CARD":
      return `Card - ****${String(method.details.card_number ?? "").slice(-4)}`;
    case "WALLET":
      return `${method.details.wallet_type || "Wallet"} - ${method.details.mobile_number || method.provider_name}`;
  }
}

const withdrawTabs = [
  {
    id: "pending",
    apiStatus: "pending",
    label: "Pending Withdraw",
    icon: Clock,
  },
  {
    id: "approved",
    apiStatus: "approved",
    label: "Approved Withdraw",
    icon: CheckCircle2,
  },
  {
    id: "cancelled",
    apiStatus: "rejected",
    label: "Cancelled Withdraw",
    icon: XCircle,
  },
] as const;

const statusConfig = {
  pending: {
    icon: Clock,
    badgeClass:
      "bg-amber-50 text-amber-600 border-amber-200 dark:bg-amber-950 dark:text-amber-400 dark:border-amber-800",
    label: "Pending",
  },
  approved: {
    icon: CheckCircle,
    badgeClass:
      "bg-emerald-50 text-emerald-600 border-emerald-200 dark:bg-emerald-950 dark:text-emerald-400 dark:border-emerald-800",
    label: "Approved",
  },
  cancelled: {
    icon: XCircle,
    badgeClass:
      "bg-red-50 text-red-600 border-red-200 dark:bg-red-950 dark:text-red-400 dark:border-red-800",
    label: "Cancelled",
  },
};

const emptyWithdrawalPagination: WithdrawalPagination = {
  currentPage: 1,
  from: null,
  lastPage: 1,
  links: [],
  nextPageUrl: null,
  perPage: 20,
  prevPageUrl: null,
  to: null,
  total: 0,
};

function createEmptyWithdrawalTabState(): WithdrawalTabState {
  return {
    withdrawals: [],
    pagination: emptyWithdrawalPagination,
    isLoading: false,
    error: null,
    loaded: false,
  };
}

function getInitialWithdrawalTabsState(): Record<
  AgentWithdrawalTabStatus,
  WithdrawalTabState
> {
  return {
    pending: createEmptyWithdrawalTabState(),
    approved: createEmptyWithdrawalTabState(),
    cancelled: createEmptyWithdrawalTabState(),
  };
}

function formatCurrency(amount: number) {
  return `₹${amount.toLocaleString("en-IN")}`;
}

function formatDate(value?: string) {
  if (!value) return "-";

  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "-";

  return date.toLocaleDateString("en-IN", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  });
}

function getExpectedDate(value: string) {
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "-";

  date.setDate(date.getDate() + 3);
  return formatDate(date.toISOString());
}

function maskAccount(accountNumber: string) {
  if (!accountNumber || accountNumber === "N/A") return "N/A";

  const lastFour = accountNumber.slice(-4);
  return lastFour ? `****${lastFour}` : accountNumber;
}

function getWithdrawalMethod(withdrawal: WithdrawRequest) {
  return withdrawal.bankDetails.ifscCode &&
    withdrawal.bankDetails.ifscCode !== "N/A"
    ? "BANK"
    : "TRANSFER";
}

function calculateWithdrawalStats(
  withdrawalItems: WithdrawRequest[]
): WithdrawalStats {
  const pending = withdrawalItems.filter((item) => item.status === "pending");
  const approved = withdrawalItems.filter((item) => item.status === "approved");
  const cancelled = withdrawalItems.filter(
    (item) => item.status === "cancelled"
  );

  return {
    totalPending: pending.length,
    totalPendingAmount: pending.reduce(
      (total, item) => total + item.withdrawAmount,
      0
    ),
    totalApproved: approved.length,
    totalApprovedAmount: approved.reduce(
      (total, item) => total + item.withdrawAmount,
      0
    ),
    totalCancelled: cancelled.length,
    totalCancelledAmount: cancelled.reduce(
      (total, item) => total + item.withdrawAmount,
      0
    ),
  };
}

export default function EarningWithdrawPage() {
  const router = useRouter();
  const [agentEmail, setAgentEmail] = useState<string>(
    "info@ameeraholidays.com"
  );
  const [agentName, setAgentName] = useState<string>("Agent");
  const [isLoading, setIsLoading] = useState(true);
  const [activeTab, setActiveTab] =
    useState<AgentWithdrawalTabStatus>("pending");
  const [searchQuery, setSearchQuery] = useState("");
  const [withdrawalTabsState, setWithdrawalTabsState] = useState<
    Record<AgentWithdrawalTabStatus, WithdrawalTabState>
  >(getInitialWithdrawalTabsState);

  // Payment methods state
  const [paymentMethods, setPaymentMethods] = useState<PaymentMethodItem[]>([]);
  const [isLoadingMethods, setIsLoadingMethods] = useState(false);
  const [isSubmittingMethod, setIsSubmittingMethod] = useState(false);
  const [deletingMethodId, setDeletingMethodId] = useState<
    string | number | null
  >(null);
  const [isMethodsDialogOpen, setIsMethodsDialogOpen] = useState(false);
  const [isAddMethodDialogOpen, setIsAddMethodDialogOpen] = useState(false);
  const hasLoadedPaymentMethodsRef = useRef(false);
  const paymentMethodsRequestRef = useRef<ReturnType<
    typeof getMyPaymentMethodsAction
  > | null>(null);

  // Withdraw dialog state
  const [isWithdrawDialogOpen, setIsWithdrawDialogOpen] = useState(false);
  const [withdrawForm, setWithdrawForm] = useState({
    amount: "",
    methodId: "",
  });

  const [methodForm, setMethodForm] = useState({
    type: "bank" as "bank" | "upi",
    bankName: "",
    accountNumber: "",
    ifscCode: "",
    accountHolder: "",
    upiId: "",
  });

  const allLoadedWithdrawals = Object.values(withdrawalTabsState).flatMap(
    (tabState) => tabState.withdrawals
  );
  const withdrawalStats = calculateWithdrawalStats(allLoadedWithdrawals);
  const availableBalance = allLoadedWithdrawals.reduce(
    (highest, withdrawal) => Math.max(highest, withdrawal.walletBalance),
    0
  );
  const walletData = {
    totalEarnings:
      availableBalance +
      withdrawalStats.totalPendingAmount +
      withdrawalStats.totalApprovedAmount,
    availableBalance,
    pendingWithdrawal: withdrawalStats.totalPendingAmount,
    totalWithdrawn: withdrawalStats.totalApprovedAmount,
  };

  useEffect(() => {
    const session = getClientSession("agent_session");
    if (!session || !validateSessionData(session) || session.role !== "agent") {
      router.push("/login");
      return;
    }
    setAgentEmail(session.email || "info@ameeraholidays.com");
    setAgentName(session.name || "Agent");
    setIsLoading(false);
  }, [router]);

  const loadWithdrawals = useCallback(
    async (
      tab: AgentWithdrawalTabStatus,
      page = 1,
      options: { force?: boolean } = {}
    ) => {
      const tabConfig = withdrawTabs.find((item) => item.id === tab);
      if (!tabConfig) return;

      const currentState = withdrawalTabsState[tab];
      if (
        currentState.pagination.currentPage === page &&
        (currentState.loaded || currentState.isLoading) &&
        !options.force
      ) {
        return;
      }

      setWithdrawalTabsState((prev) => ({
        ...prev,
        [tab]: {
          ...prev[tab],
          pagination: {
            ...prev[tab].pagination,
            currentPage: page,
          },
          isLoading: true,
          error: null,
        },
      }));

      try {
        const result = await getAgentWithdrawalRequestsAction(
          tabConfig.apiStatus,
          page
        );

        setWithdrawalTabsState((prev) => {
          if (!result.success || !result.data) {
            return {
              ...prev,
              [tab]: {
                ...prev[tab],
                withdrawals: [],
                pagination: {
                  ...emptyWithdrawalPagination,
                  currentPage: page,
                },
                isLoading: false,
                error: result.error ?? "Failed to load withdrawal requests",
                loaded: true,
              },
            };
          }

          return {
            ...prev,
            [tab]: {
              withdrawals: result.data.withdrawals,
              pagination: result.data.pagination,
              isLoading: false,
              error: null,
              loaded: true,
            },
          };
        });
      } catch (error) {
        setWithdrawalTabsState((prev) => ({
          ...prev,
          [tab]: {
            ...prev[tab],
            withdrawals: [],
            pagination: {
              ...emptyWithdrawalPagination,
              currentPage: page,
            },
            isLoading: false,
            error:
              error instanceof Error
                ? error.message
                : "Failed to load withdrawal requests",
            loaded: true,
          },
        }));
      }
    },
    [withdrawalTabsState]
  );

  useEffect(() => {
    const tabState = withdrawalTabsState[activeTab];

    if (!tabState.loaded && !tabState.isLoading) {
      void loadWithdrawals(activeTab, tabState.pagination.currentPage);
    }
  }, [activeTab, loadWithdrawals, withdrawalTabsState]);

  const loadPaymentMethods = useCallback(async (force = false) => {
    if (!force && hasLoadedPaymentMethodsRef.current) return;

    hasLoadedPaymentMethodsRef.current = true;
    setIsLoadingMethods(true);

    const pending =
      paymentMethodsRequestRef.current ?? getMyPaymentMethodsAction();
    paymentMethodsRequestRef.current = pending;

    try {
      const result = await pending;
      if (result.success) {
        setPaymentMethods(result.data ?? []);
      } else {
        toast.error(result.error ?? "Failed to load payment methods");
      }
    } finally {
      if (paymentMethodsRequestRef.current === pending) {
        paymentMethodsRequestRef.current = null;
      }
      setIsLoadingMethods(false);
    }
  }, []);

  useEffect(() => {
    void loadPaymentMethods();
  }, [loadPaymentMethods]);

  const resetMethodForm = () => {
    setMethodForm({
      type: "bank",
      bankName: "",
      accountNumber: "",
      ifscCode: "",
      accountHolder: "",
      upiId: "",
    });
  };

  const handleAddMethod = async () => {
    try {
      setIsSubmittingMethod(true);
      const payload =
        methodForm.type === "bank"
          ? {
              provider_name: methodForm.bankName || "Bank Account",
              method_type: "NET_BANKING" as const,
              details: {
                bank_name: methodForm.bankName,
                account_number: methodForm.accountNumber,
                ifsc_code: methodForm.ifscCode,
                account_holder_name: methodForm.accountHolder,
              },
              status: "inactive" as const,
            }
          : {
              provider_name: methodForm.upiId || "UPI",
              method_type: "UPI" as const,
              details: { upi_id: methodForm.upiId },
              status: "inactive" as const,
            };

      const result = await createMyPaymentMethodAction(payload);
      if (!result.success) {
        toast.error(result.error ?? "Failed to add payment method");
        return;
      }

      if (result.data) {
        setPaymentMethods((prev) => [result.data!, ...prev]);
      } else {
        await loadPaymentMethods(true);
      }

      setIsAddMethodDialogOpen(false);
      resetMethodForm();
      toast.success("Payment method added successfully");
    } finally {
      setIsSubmittingMethod(false);
    }
  };

  const handleDeleteMethod = async (id: string | number) => {
    try {
      setDeletingMethodId(id);
      const result = await deleteMyPaymentMethodAction(id);
      if (!result.success) {
        toast.error(result.error ?? "Failed to delete payment method");
        return;
      }
      setPaymentMethods((prev) => prev.filter((m) => m.id !== id));
      toast.success("Payment method deleted");
    } finally {
      setDeletingMethodId(null);
    }
  };

  const handleWithdrawSubmit = () => {
    if (
      !withdrawForm.amount ||
      !withdrawForm.methodId ||
      Number(withdrawForm.amount) < 1000
    ) {
      toast.error("Please fill all fields correctly");
      return;
    }
    if (Number(withdrawForm.amount) > walletData.availableBalance) {
      toast.error("Amount exceeds available balance");
      return;
    }
    toast.success(
      `Withdrawal request of ${formatCurrency(Number(withdrawForm.amount))} submitted successfully`
    );
    setIsWithdrawDialogOpen(false);
    setWithdrawForm({ amount: "", methodId: "" });
  };

  const activeTabState = withdrawalTabsState[activeTab];
  const currentWithdrawals = activeTabState.withdrawals;
  const activePagination = activeTabState.pagination;
  const config = statusConfig[activeTab];
  const StatusIcon = config?.icon || Clock;

  const filteredWithdrawals = currentWithdrawals.filter((withdrawal) => {
    const query = searchQuery.toLowerCase();

    return (
      withdrawal.id.toLowerCase().includes(query) ||
      withdrawal.name.toLowerCase().includes(query) ||
      withdrawal.bankDetails.bankName.toLowerCase().includes(query) ||
      String(withdrawal.withdrawAmount).includes(query) ||
      formatCurrency(withdrawal.withdrawAmount).toLowerCase().includes(query)
    );
  });

  if (isLoading) {
    return (
      <div className="flex h-screen items-center justify-center">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-800" />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 via-white to-gray-100 dark:from-gray-950 dark:via-gray-900 dark:to-gray-950">
      <AgentHeader agentEmail={agentEmail} agentName={agentName} />

      <main className="container mx-auto p-4 md:p-6 lg:p-8">
        {/* Wallet Summary Section with Gradient */}
        <div className="mb-8 rounded-2xl overflow-hidden shadow-xl">
          <div
            className="p-6 md:p-8"
            style={{
              background:
                "linear-gradient(135deg, #1a1a2e 0%, #2d2d44 50%, #3d3d5c 100%)",
            }}
          >
            <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-6">
              <div className="flex items-center gap-4">
                <div className="p-4 rounded-2xl bg-white/10 backdrop-blur-sm">
                  <Wallet className="h-8 w-8 text-white" />
                </div>
                <div>
                  <p className="text-white/70 text-sm font-medium">
                    Available Balance
                  </p>
                  <h2 className="text-3xl md:text-4xl font-bold text-white flex items-center">
                    <IndianRupee className="h-7 w-7" />
                    {walletData.availableBalance.toLocaleString("en-IN")}
                  </h2>
                </div>
              </div>

              <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3">
                <Button
                  variant="outline"
                  className="bg-transparent border-white/30 text-white hover:bg-white/10 hover:text-white"
                  onClick={() => setIsMethodsDialogOpen(true)}
                >
                  <CreditCard className="h-4 w-4 mr-2" />
                  Withdraw Methods
                </Button>
                <Button
                  size="lg"
                  className="bg-white text-gray-800 hover:bg-white/90 font-semibold shadow-lg"
                  onClick={() => setIsWithdrawDialogOpen(true)}
                >
                  <Send className="h-5 w-5 mr-2" />
                  Withdraw Funds
                </Button>
              </div>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4 mt-8">
              <div className="bg-white/10 backdrop-blur-sm rounded-xl p-4">
                <div className="flex items-center gap-3">
                  <TrendingUp className="h-5 w-5 text-emerald-300" />
                  <div>
                    <p className="text-white/70 text-xs">Total Earnings</p>
                    <p className="text-white font-semibold">
                      {formatCurrency(walletData.totalEarnings)}
                    </p>
                  </div>
                </div>
              </div>
              <div className="bg-white/10 backdrop-blur-sm rounded-xl p-4">
                <div className="flex items-center gap-3">
                  <Clock className="h-5 w-5 text-amber-300" />
                  <div>
                    <p className="text-white/70 text-xs">Pending Withdrawal</p>
                    <p className="text-white font-semibold">
                      {formatCurrency(walletData.pendingWithdrawal)}
                    </p>
                  </div>
                </div>
              </div>
              <div className="bg-white/10 backdrop-blur-sm rounded-xl p-4">
                <div className="flex items-center gap-3">
                  <CheckCircle2 className="h-5 w-5 text-cyan-300" />
                  <div>
                    <p className="text-white/70 text-xs">Total Withdrawn</p>
                    <p className="text-white font-semibold">
                      {formatCurrency(walletData.totalWithdrawn)}
                    </p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Main Content with Sidebar */}
        <div className="flex flex-col md:flex-row gap-6">
          {/* Sidebar with status tabs */}
          <div className="w-full md:w-64 shrink-0">
            <Card className="border-border/50 overflow-hidden shadow-sm">
              <div className="h-1 bg-gradient-to-r from-gray-700 to-gray-900" />
              <div className="p-3 border-b border-border/50 bg-muted/30">
                <h3 className="font-semibold text-sm text-muted-foreground uppercase tracking-wider">
                  Withdrawal Status
                </h3>
              </div>
              <div className="p-2">
                {withdrawTabs.map((tab) => {
                  const Icon = tab.icon;
                  const isActive = activeTab === tab.id;
                  return (
                    <button
                      key={tab.id}
                      onClick={() => setActiveTab(tab.id)}
                      className={cn(
                        "w-full flex items-center gap-3 px-4 py-3 rounded-lg font-medium transition-all text-left mb-1 last:mb-0",
                        isActive
                          ? "agent-btn text-white shadow-md"
                          : "text-muted-foreground hover:text-foreground hover:bg-muted"
                      )}
                    >
                      <Icon
                        className={cn("h-5 w-5", isActive ? "text-white" : "")}
                      />
                      {tab.label}
                    </button>
                  );
                })}
              </div>
            </Card>
          </div>

          {/* Content area with withdrawal table */}
          <div className="flex-1">
            <Card className="border-border/50 shadow-sm overflow-hidden">
              <div className="h-1 bg-gradient-to-r from-gray-700 to-gray-900" />
              <CardHeader>
                <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                  <CardTitle className="text-xl font-semibold flex items-center gap-3">
                    {config?.label} Withdrawals
                    <Badge variant="outline" className={config?.badgeClass}>
                      {searchQuery
                        ? filteredWithdrawals.length
                        : activePagination.total}
                    </Badge>
                  </CardTitle>

                  <div className="flex items-center gap-2">
                    <div className="relative">
                      <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                      <Input
                        placeholder="Search..."
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        className="pl-9 w-[180px]"
                      />
                    </div>
                    <Button variant="outline" size="icon">
                      <Filter className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </CardHeader>

              <CardContent>
                {activeTabState.isLoading ? (
                  <div className="flex items-center justify-center py-12">
                    <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
                  </div>
                ) : activeTabState.error ? (
                  <div className="text-center py-12">
                    <AlertCircle className="h-12 w-12 mx-auto text-red-500 mb-4" />
                    <h3 className="text-xl font-semibold mb-2">
                      Unable to load withdrawals
                    </h3>
                    <p className="text-muted-foreground max-w-md mx-auto mb-4">
                      {activeTabState.error}
                    </p>
                    <Button
                      variant="outline"
                      onClick={() =>
                        loadWithdrawals(
                          activeTab,
                          activePagination.currentPage,
                          {
                            force: true,
                          }
                        )
                      }
                    >
                      Try Again
                    </Button>
                  </div>
                ) : filteredWithdrawals.length === 0 ? (
                  <div className="text-center py-12">
                    <div className="p-4 rounded-full bg-gradient-to-br from-gray-200 to-gray-300 dark:from-gray-700 dark:to-gray-600 inline-block mb-4">
                      <Wallet className="h-12 w-12 text-gray-600 dark:text-gray-300" />
                    </div>
                    <h3 className="text-xl font-semibold mb-2">
                      {config?.label} Withdrawals
                    </h3>
                    <p className="text-muted-foreground max-w-md mx-auto">
                      No {config?.label.toLowerCase()} withdrawals found. Your
                      withdrawal requests will appear here.
                    </p>
                  </div>
                ) : (
                  <div className="space-y-3">
                    {filteredWithdrawals.map((withdrawal) => (
                      <div
                        key={withdrawal.id}
                        className="flex flex-col sm:flex-row sm:items-center gap-4 p-4 rounded-xl bg-gradient-to-br from-white to-gray-50 dark:from-gray-800 dark:to-gray-850 border border-border/50 hover:shadow-md transition-all duration-200"
                      >
                        <div className="p-2.5 rounded-xl bg-slate-100 dark:bg-slate-800 shrink-0">
                          <StatusIcon className="h-5 w-5 text-slate-600 dark:text-slate-300" />
                        </div>

                        <div className="flex-1 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
                          <div>
                            <p className="text-2xl font-bold">
                              {formatCurrency(withdrawal.withdrawAmount)}
                            </p>
                            <p className="text-xs text-muted-foreground">
                              #{withdrawal.id}
                            </p>
                          </div>

                          <div>
                            <div className="flex items-center gap-1.5 text-sm font-medium">
                              <Building className="h-3.5 w-3.5 text-muted-foreground" />
                              {withdrawal.bankDetails.bankName}
                            </div>
                            <p className="text-xs text-muted-foreground">
                              {withdrawal.bankDetails.bankName}{" "}
                              {maskAccount(
                                withdrawal.bankDetails.accountNumber
                              )}
                            </p>
                            <Badge variant="secondary" className="mt-1 text-xs">
                              {getWithdrawalMethod(withdrawal)}
                            </Badge>
                          </div>

                          <div>
                            <p className="text-xs text-muted-foreground flex items-center gap-1">
                              <Calendar className="h-3 w-3" />
                              Requested: {formatDate(withdrawal.requestedAt)}
                            </p>
                            {activeTab === "pending" && (
                              <p className="text-xs text-muted-foreground mt-1">
                                Expected:{" "}
                                {getExpectedDate(withdrawal.requestedAt)}
                              </p>
                            )}
                            {activeTab === "approved" && (
                              <>
                                <p className="text-xs text-emerald-600 dark:text-emerald-400 mt-1">
                                  Processed:{" "}
                                  {formatDate(withdrawal.processedAt)}
                                </p>
                                {withdrawal.referenceNumber && (
                                  <p className="text-xs text-muted-foreground">
                                    TXN: {withdrawal.referenceNumber}
                                  </p>
                                )}
                              </>
                            )}
                            {activeTab === "cancelled" && (
                              <>
                                <p className="text-xs text-red-600 dark:text-red-400 mt-1">
                                  Cancelled:{" "}
                                  {formatDate(withdrawal.processedAt)}
                                </p>
                                {withdrawal.cancelReason && (
                                  <p className="text-xs text-muted-foreground">
                                    {withdrawal.cancelReason}
                                  </p>
                                )}
                              </>
                            )}
                          </div>

                          <div className="flex items-center justify-end">
                            <Badge
                              variant="outline"
                              className={config?.badgeClass}
                            >
                              {config?.label}
                            </Badge>
                          </div>
                        </div>
                      </div>
                    ))}
                    {activePagination.lastPage > 1 && (
                      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 pt-3">
                        <p className="text-sm text-muted-foreground">
                          Showing {activePagination.from ?? 0} to{" "}
                          {activePagination.to ?? 0} of {activePagination.total}{" "}
                          withdrawals
                        </p>
                        <div className="flex items-center gap-2">
                          <Button
                            variant="outline"
                            size="sm"
                            disabled={
                              activePagination.currentPage <= 1 ||
                              activeTabState.isLoading
                            }
                            onClick={() =>
                              loadWithdrawals(
                                activeTab,
                                activePagination.currentPage - 1,
                                { force: true }
                              )
                            }
                          >
                            Previous
                          </Button>
                          {activePagination.links
                            .filter((link) => link.page !== null)
                            .map((link) => (
                              <Button
                                key={link.label}
                                variant={link.active ? "default" : "outline"}
                                size="sm"
                                disabled={
                                  link.page === activePagination.currentPage ||
                                  activeTabState.isLoading
                                }
                                onClick={() =>
                                  link.page
                                    ? loadWithdrawals(activeTab, link.page, {
                                        force: true,
                                      })
                                    : undefined
                                }
                              >
                                {link.label}
                              </Button>
                            ))}
                          <Button
                            variant="outline"
                            size="sm"
                            disabled={
                              activePagination.currentPage >=
                                activePagination.lastPage ||
                              activeTabState.isLoading
                            }
                            onClick={() =>
                              loadWithdrawals(
                                activeTab,
                                activePagination.currentPage + 1,
                                { force: true }
                              )
                            }
                          >
                            Next
                          </Button>
                        </div>
                      </div>
                    )}
                  </div>
                )}
              </CardContent>
            </Card>
          </div>
        </div>
      </main>

      {/* Withdraw Methods Dialog */}
      <Dialog open={isMethodsDialogOpen} onOpenChange={setIsMethodsDialogOpen}>
        <DialogContent className="max-w-xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <CreditCard className="h-5 w-5" />
              Withdraw Methods
            </DialogTitle>
            <DialogDescription>
              Manage your payment methods for withdrawals
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-4">
            {isLoadingMethods ? (
              <div className="flex items-center justify-center py-8">
                <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
              </div>
            ) : paymentMethods.length === 0 ? (
              <div className="text-center py-8">
                <CreditCard className="h-12 w-12 mx-auto text-muted-foreground/50 mb-3" />
                <p className="text-muted-foreground">
                  No payment methods added yet
                </p>
              </div>
            ) : (
              <div className="space-y-3">
                {paymentMethods.map((method) => {
                  const isActive =
                    String(method.status).toLowerCase() === "active";
                  return (
                    <div
                      key={method.id}
                      className={`p-4 rounded-xl border ${
                        isActive
                          ? "border-teal-500 bg-teal-50 dark:bg-teal-950/30"
                          : "border-border"
                      }`}
                    >
                      <div className="flex items-start justify-between">
                        <div className="flex items-center gap-3">
                          <div className="p-2 rounded-lg bg-slate-100 dark:bg-slate-800">
                            {method.method_type === "NET_BANKING" ? (
                              <Building className="h-5 w-5 text-slate-600 dark:text-slate-300" />
                            ) : (
                              <Wallet className="h-5 w-5 text-slate-600 dark:text-slate-300" />
                            )}
                          </div>
                          <div>
                            {method.method_type === "NET_BANKING" ? (
                              <>
                                <p className="font-medium">
                                  {method.details.bank_name ||
                                    method.provider_name}
                                </p>
                                <p className="text-sm text-muted-foreground">
                                  {method.details.account_number
                                    ? `****${String(method.details.account_number).slice(-4)}`
                                    : ""}
                                </p>
                                <p className="text-xs text-muted-foreground">
                                  {method.details.account_holder_name}
                                </p>
                              </>
                            ) : (
                              <>
                                <p className="font-medium">
                                  {method.method_type}
                                </p>
                                <p className="text-sm text-muted-foreground">
                                  {method.details.upi_id ||
                                    method.provider_name}
                                </p>
                              </>
                            )}
                          </div>
                        </div>
                        <div className="flex items-center gap-2">
                          {isActive && (
                            <Badge className="bg-teal-100 text-teal-700 dark:bg-teal-900 dark:text-teal-300">
                              Primary
                            </Badge>
                          )}
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-8 w-8 text-red-500 hover:text-red-600 hover:bg-red-50"
                            disabled={deletingMethodId === method.id}
                            onClick={() => handleDeleteMethod(method.id)}
                          >
                            {deletingMethodId === method.id ? (
                              <Loader2 className="h-4 w-4 animate-spin" />
                            ) : (
                              <Trash2 className="h-4 w-4" />
                            )}
                          </Button>
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>

          <DialogFooter>
            <Button
              onClick={() => {
                resetMethodForm();
                setIsAddMethodDialogOpen(true);
              }}
              className="frontend-btn"
            >
              <Plus className="h-4 w-4 mr-2" />
              Add Payment Method
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Add Payment Method Dialog */}
      <Dialog
        open={isAddMethodDialogOpen}
        onOpenChange={setIsAddMethodDialogOpen}
      >
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>Add Payment Method</DialogTitle>
          </DialogHeader>

          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label>Method Type</Label>
              <Select
                value={methodForm.type}
                onValueChange={(value: "bank" | "upi") =>
                  setMethodForm({ ...methodForm, type: value })
                }
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="bank">Bank Account</SelectItem>
                  <SelectItem value="upi">UPI</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {methodForm.type === "bank" ? (
              <>
                <div className="space-y-2">
                  <Label htmlFor="bankName">Bank Name</Label>
                  <Input
                    id="bankName"
                    placeholder="e.g., HDFC Bank"
                    value={methodForm.bankName}
                    onChange={(e) =>
                      setMethodForm({ ...methodForm, bankName: e.target.value })
                    }
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="accountNumber">Account Number</Label>
                  <Input
                    id="accountNumber"
                    placeholder="Enter account number"
                    value={methodForm.accountNumber}
                    onChange={(e) =>
                      setMethodForm({
                        ...methodForm,
                        accountNumber: e.target.value,
                      })
                    }
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="ifscCode">IFSC Code</Label>
                  <Input
                    id="ifscCode"
                    placeholder="e.g., HDFC0001234"
                    value={methodForm.ifscCode}
                    onChange={(e) =>
                      setMethodForm({ ...methodForm, ifscCode: e.target.value })
                    }
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="accountHolder">Account Holder Name</Label>
                  <Input
                    id="accountHolder"
                    placeholder="Name as per bank records"
                    value={methodForm.accountHolder}
                    onChange={(e) =>
                      setMethodForm({
                        ...methodForm,
                        accountHolder: e.target.value,
                      })
                    }
                  />
                </div>
              </>
            ) : (
              <div className="space-y-2">
                <Label htmlFor="upiId">UPI ID</Label>
                <Input
                  id="upiId"
                  placeholder="e.g., yourname@upi"
                  value={methodForm.upiId}
                  onChange={(e) =>
                    setMethodForm({ ...methodForm, upiId: e.target.value })
                  }
                />
              </div>
            )}
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setIsAddMethodDialogOpen(false)}
              disabled={isSubmittingMethod}
            >
              Cancel
            </Button>
            <Button
              onClick={handleAddMethod}
              className="frontend-btn"
              disabled={isSubmittingMethod}
            >
              {isSubmittingMethod ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Adding...
                </>
              ) : (
                "Add Method"
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Withdraw Now Dialog */}
      <Dialog
        open={isWithdrawDialogOpen}
        onOpenChange={setIsWithdrawDialogOpen}
      >
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <ArrowDownToLine className="h-5 w-5" />
              Withdraw Funds
            </DialogTitle>
            <DialogDescription>
              Request a withdrawal to your linked account
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-4">
            <div className="p-4 rounded-lg bg-teal-50 dark:bg-teal-950/30 border border-teal-200 dark:border-teal-800">
              <div className="flex items-center justify-between">
                <span className="text-sm text-muted-foreground">
                  Available Balance
                </span>
                <span className="text-xl font-bold">
                  {formatCurrency(walletData.availableBalance)}
                </span>
              </div>
            </div>

            <div className="space-y-2">
              <Label htmlFor="withdrawAmount">Amount to Withdraw</Label>
              <div className="relative">
                <span className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground">
                  ₹
                </span>
                <Input
                  id="withdrawAmount"
                  type="number"
                  placeholder="Enter amount"
                  className="pl-8"
                  value={withdrawForm.amount}
                  onChange={(e) =>
                    setWithdrawForm({ ...withdrawForm, amount: e.target.value })
                  }
                />
              </div>
              <div className="flex gap-2">
                {["5000", "10000", "20000", "45000"].map((amount) => (
                  <Button
                    key={amount}
                    variant="outline"
                    size="sm"
                    className="flex-1 bg-transparent"
                    onClick={() => setWithdrawForm({ ...withdrawForm, amount })}
                  >
                    {formatCurrency(Number(amount))}
                  </Button>
                ))}
              </div>
            </div>

            <div className="space-y-2">
              <Label>Select Payment Method</Label>
              <Select
                value={withdrawForm.methodId}
                onValueChange={(value) =>
                  setWithdrawForm({ ...withdrawForm, methodId: value })
                }
              >
                <SelectTrigger>
                  <SelectValue placeholder="Choose a payment method" />
                </SelectTrigger>
                <SelectContent>
                  {paymentMethods.map((method) => (
                    <SelectItem key={method.id} value={String(method.id)}>
                      <div className="flex items-center gap-2">
                        {method.method_type === "NET_BANKING" ? (
                          <Building className="h-4 w-4" />
                        ) : (
                          <Wallet className="h-4 w-4" />
                        )}
                        {getMethodLabel(method)}
                        {String(method.status).toLowerCase() === "active" && (
                          <Badge variant="secondary" className="text-xs">
                            Primary
                          </Badge>
                        )}
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {Number(withdrawForm.amount) > 0 && withdrawForm.methodId && (
              <div className="p-4 rounded-lg bg-emerald-50 dark:bg-emerald-950/30 border border-emerald-200 dark:border-emerald-800">
                <div className="flex items-start gap-2">
                  <CheckCircle className="h-5 w-5 text-emerald-600 dark:text-emerald-400 mt-0.5" />
                  <div className="text-sm">
                    <p className="font-medium text-emerald-700 dark:text-emerald-300">
                      Ready to withdraw
                    </p>
                    <p className="text-emerald-600 dark:text-emerald-400">
                      {formatCurrency(Number(withdrawForm.amount))} will be
                      transferred within 2-3 business days
                    </p>
                  </div>
                </div>
              </div>
            )}

            <div className="p-3 rounded-lg bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800">
              <div className="flex items-start gap-2">
                <AlertCircle className="h-4 w-4 text-amber-600 dark:text-amber-400 mt-0.5" />
                <p className="text-xs text-amber-700 dark:text-amber-300">
                  Minimum withdrawal: ₹1,000. Processing time: 2-3 business
                  days.
                </p>
              </div>
            </div>
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setIsWithdrawDialogOpen(false)}
            >
              Cancel
            </Button>
            <Button
              onClick={handleWithdrawSubmit}
              disabled={
                !withdrawForm.amount ||
                !withdrawForm.methodId ||
                Number(withdrawForm.amount) < 1000
              }
              className="frontend-btn"
            >
              <ArrowDownToLine className="h-4 w-4 mr-2" />
              Request Withdrawal
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
