﻿"use client";

import { useEffect, useState } from "react";
import { useRouter, useSearchParams } 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,
  Pencil,
  Trash2,
  Building,
  ArrowDownToLine,
  AlertCircle,
  Calendar,
  Search,
  Filter,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { toast } from "sonner";

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

interface PaymentMethod {
  id: string;
  type: "bank" | "upi";
  bankName?: string;
  accountNumber?: string;
  ifscCode?: string;
  accountHolder?: string;
  upiId?: string;
  isPrimary: boolean;
}

const initialPaymentMethods: PaymentMethod[] = [
  {
    id: "1",
    type: "bank",
    bankName: "HDFC Bank",
    accountNumber: "XXXX XXXX 4521",
    ifscCode: "HDFC0001234",
    accountHolder: "Travel Agent Pvt Ltd",
    isPrimary: true,
  },
  {
    id: "2",
    type: "bank",
    bankName: "ICICI Bank",
    accountNumber: "XXXX XXXX 7832",
    ifscCode: "ICIC0005678",
    accountHolder: "Travel Agent Pvt Ltd",
    isPrimary: false,
  },
  {
    id: "3",
    type: "upi",
    upiId: "agent@upi",
    isPrimary: false,
  },
];

const withdrawData = {
  pending: [
    {
      id: "WD001",
      amount: "â‚¹15,000",
      requestDate: "Dec 08, 2025",
      bankAccount: "HDFC Bank ****4521",
      bankName: "HDFC Bank",
      expectedDate: "Dec 12, 2025",
      method: "NEFT",
    },
    {
      id: "WD002",
      amount: "â‚¹8,500",
      requestDate: "Dec 09, 2025",
      bankAccount: "ICICI Bank ****7832",
      bankName: "ICICI Bank",
      expectedDate: "Dec 13, 2025",
      method: "IMPS",
    },
  ],
  approved: [
    {
      id: "WD010",
      amount: "â‚¹22,000",
      requestDate: "Dec 01, 2025",
      bankAccount: "HDFC Bank ****4521",
      bankName: "HDFC Bank",
      processedDate: "Dec 03, 2025",
      transactionId: "TXN123456789",
      method: "NEFT",
    },
    {
      id: "WD011",
      amount: "â‚¹15,800",
      requestDate: "Dec 02, 2025",
      bankAccount: "ICICI Bank ****7832",
      bankName: "ICICI Bank",
      processedDate: "Dec 04, 2025",
      transactionId: "TXN123457890",
      method: "IMPS",
    },
  ],
  cancelled: [
    {
      id: "WD020",
      amount: "â‚¹5,000",
      requestDate: "Nov 25, 2025",
      bankAccount: "HDFC Bank ****4521",
      bankName: "HDFC Bank",
      cancelledDate: "Nov 26, 2025",
      reason: "Insufficient earnings balance",
    },
  ],
};

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",
  },
};

export default function EarningWithdrawPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [agentEmail, setAgentEmail] = useState<string>(
    "info@ameeraholidays.com"
  );
  const [agentName, setAgentName] = useState<string>("Agent");
  const [isLoading, setIsLoading] = useState(true);
  const [activeTab, setActiveTab] = useState(
    searchParams.get("status") || "pending"
  );
  const [searchQuery, setSearchQuery] = useState("");

  // Payment methods state
  const [paymentMethods, setPaymentMethods] = useState<PaymentMethod[]>(
    initialPaymentMethods
  );
  const [isMethodsDialogOpen, setIsMethodsDialogOpen] = useState(false);
  const [isAddMethodDialogOpen, setIsAddMethodDialogOpen] = useState(false);
  const [isEditMethodDialogOpen, setIsEditMethodDialogOpen] = useState(false);
  const [selectedMethod, setSelectedMethod] = useState<PaymentMethod | 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 walletData = {
    totalEarnings: 125000,
    availableBalance: 45000,
    pendingWithdrawal: 23500,
    totalWithdrawn: 56500,
  };

  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 resetMethodForm = () => {
    setMethodForm({
      type: "bank",
      bankName: "",
      accountNumber: "",
      ifscCode: "",
      accountHolder: "",
      upiId: "",
    });
  };

  const handleAddMethod = () => {
    const newMethod: PaymentMethod = {
      id: Date.now().toString(),
      type: methodForm.type,
      bankName: methodForm.type === "bank" ? methodForm.bankName : undefined,
      accountNumber:
        methodForm.type === "bank" ? methodForm.accountNumber : undefined,
      ifscCode: methodForm.type === "bank" ? methodForm.ifscCode : undefined,
      accountHolder:
        methodForm.type === "bank" ? methodForm.accountHolder : undefined,
      upiId: methodForm.type === "upi" ? methodForm.upiId : undefined,
      isPrimary: paymentMethods.length === 0,
    };
    setPaymentMethods([...paymentMethods, newMethod]);
    setIsAddMethodDialogOpen(false);
    resetMethodForm();
    toast.success("Payment method added successfully");
  };

  const handleEditMethod = () => {
    if (!selectedMethod) return;
    setPaymentMethods(
      paymentMethods.map((method) =>
        method.id === selectedMethod.id
          ? {
              ...method,
              type: methodForm.type,
              bankName:
                methodForm.type === "bank" ? methodForm.bankName : undefined,
              accountNumber:
                methodForm.type === "bank"
                  ? methodForm.accountNumber
                  : undefined,
              ifscCode:
                methodForm.type === "bank" ? methodForm.ifscCode : undefined,
              accountHolder:
                methodForm.type === "bank"
                  ? methodForm.accountHolder
                  : undefined,
              upiId: methodForm.type === "upi" ? methodForm.upiId : undefined,
            }
          : method
      )
    );
    setIsEditMethodDialogOpen(false);
    setSelectedMethod(null);
    resetMethodForm();
    toast.success("Payment method updated successfully");
  };

  const handleDeleteMethod = (id: string) => {
    const method = paymentMethods.find((m) => m.id === id);
    if (method?.isPrimary) {
      toast.error("Cannot delete primary payment method");
      return;
    }
    setPaymentMethods(paymentMethods.filter((m) => m.id !== id));
    toast.success("Payment method deleted");
  };

  const handleSetPrimary = (id: string) => {
    setPaymentMethods(
      paymentMethods.map((method) => ({
        ...method,
        isPrimary: method.id === id,
      }))
    );
    toast.success("Primary payment method updated");
  };

  const openEditMethod = (method: PaymentMethod) => {
    setSelectedMethod(method);
    setMethodForm({
      type: method.type,
      bankName: method.bankName || "",
      accountNumber: method.accountNumber?.replace(/X/g, "") || "",
      ifscCode: method.ifscCode || "",
      accountHolder: method.accountHolder || "",
      upiId: method.upiId || "",
    });
    setIsEditMethodDialogOpen(true);
  };

  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 â‚¹${Number(withdrawForm.amount).toLocaleString("en-IN")} submitted successfully`
    );
    setIsWithdrawDialogOpen(false);
    setWithdrawForm({ amount: "", methodId: "" });
  };

  const withdrawals =
    withdrawData[activeTab as keyof typeof withdrawData] || [];
  const config = statusConfig[activeTab as keyof typeof statusConfig];
  const StatusIcon = config?.icon || Clock;

  const filteredWithdrawals = withdrawals.filter(
    (w) =>
      w.id.toLowerCase().includes(searchQuery.toLowerCase()) ||
      w.amount.includes(searchQuery)
  );

  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">
                      â‚¹{walletData.totalEarnings.toLocaleString("en-IN")}
                    </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">
                      â‚¹{walletData.pendingWithdrawal.toLocaleString("en-IN")}
                    </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">
                      â‚¹{walletData.totalWithdrawn.toLocaleString("en-IN")}
                    </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}>
                      {filteredWithdrawals.length}
                    </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>
                {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">
                              {withdrawal.amount}
                            </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.bankName}
                            </div>
                            <p className="text-xs text-muted-foreground">
                              {withdrawal.bankAccount}
                            </p>
                            {"method" in withdrawal && (
                              <Badge
                                variant="secondary"
                                className="mt-1 text-xs"
                              >
                                {withdrawal.method}
                              </Badge>
                            )}
                          </div>

                          <div>
                            <p className="text-xs text-muted-foreground flex items-center gap-1">
                              <Calendar className="h-3 w-3" />
                              Requested: {withdrawal.requestDate}
                            </p>
                            {activeTab === "pending" &&
                              "expectedDate" in withdrawal && (
                                <p className="text-xs text-muted-foreground mt-1">
                                  Expected: {withdrawal.expectedDate}
                                </p>
                              )}
                            {activeTab === "approved" &&
                              "processedDate" in withdrawal && (
                                <>
                                  <p className="text-xs text-emerald-600 dark:text-emerald-400 mt-1">
                                    Processed: {withdrawal.processedDate}
                                  </p>
                                  {"transactionId" in withdrawal && (
                                    <p className="text-xs text-muted-foreground">
                                      TXN: {withdrawal.transactionId}
                                    </p>
                                  )}
                                </>
                              )}
                            {activeTab === "cancelled" &&
                              "cancelledDate" in withdrawal && (
                                <>
                                  <p className="text-xs text-red-600 dark:text-red-400 mt-1">
                                    Cancelled: {withdrawal.cancelledDate}
                                  </p>
                                  {"reason" in withdrawal && (
                                    <p className="text-xs text-muted-foreground">
                                      {withdrawal.reason}
                                    </p>
                                  )}
                                </>
                              )}
                          </div>

                          <div className="flex items-center justify-end">
                            <Badge
                              variant="outline"
                              className={config?.badgeClass}
                            >
                              {config?.label}
                            </Badge>
                          </div>
                        </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">
            {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) => (
                  <div
                    key={method.id}
                    className={`p-4 rounded-xl border ${
                      method.isPrimary
                        ? "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.type === "bank" ? (
                            <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.type === "bank" ? (
                            <>
                              <p className="font-medium">{method.bankName}</p>
                              <p className="text-sm text-muted-foreground">
                                {method.accountNumber}
                              </p>
                              <p className="text-xs text-muted-foreground">
                                {method.accountHolder}
                              </p>
                            </>
                          ) : (
                            <>
                              <p className="font-medium">UPI</p>
                              <p className="text-sm text-muted-foreground">
                                {method.upiId}
                              </p>
                            </>
                          )}
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        {method.isPrimary && (
                          <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"
                          onClick={() => openEditMethod(method)}
                        >
                          <Pencil className="h-4 w-4" />
                        </Button>
                        {!method.isPrimary && (
                          <Button
                            variant="ghost"
                            size="icon"
                            className="h-8 w-8 text-red-500 hover:text-red-600 hover:bg-red-50"
                            onClick={() => handleDeleteMethod(method.id)}
                          >
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        )}
                      </div>
                    </div>
                    {!method.isPrimary && (
                      <Button
                        variant="link"
                        className="mt-2 p-0 h-auto text-sm text-teal-600"
                        onClick={() => handleSetPrimary(method.id)}
                      >
                        Set as Primary
                      </Button>
                    )}
                  </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)}
            >
              Cancel
            </Button>
            <Button onClick={handleAddMethod} className="frontend-btn">
              Add Method
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Edit Payment Method Dialog */}
      <Dialog
        open={isEditMethodDialogOpen}
        onOpenChange={setIsEditMethodDialogOpen}
      >
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>Edit 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="editBankName">Bank Name</Label>
                  <Input
                    id="editBankName"
                    placeholder="e.g., HDFC Bank"
                    value={methodForm.bankName}
                    onChange={(e) =>
                      setMethodForm({ ...methodForm, bankName: e.target.value })
                    }
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="editAccountNumber">Account Number</Label>
                  <Input
                    id="editAccountNumber"
                    placeholder="Enter account number"
                    value={methodForm.accountNumber}
                    onChange={(e) =>
                      setMethodForm({
                        ...methodForm,
                        accountNumber: e.target.value,
                      })
                    }
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="editIfscCode">IFSC Code</Label>
                  <Input
                    id="editIfscCode"
                    placeholder="e.g., HDFC0001234"
                    value={methodForm.ifscCode}
                    onChange={(e) =>
                      setMethodForm({ ...methodForm, ifscCode: e.target.value })
                    }
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="editAccountHolder">Account Holder Name</Label>
                  <Input
                    id="editAccountHolder"
                    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="editUpiId">UPI ID</Label>
                <Input
                  id="editUpiId"
                  placeholder="e.g., yourname@upi"
                  value={methodForm.upiId}
                  onChange={(e) =>
                    setMethodForm({ ...methodForm, upiId: e.target.value })
                  }
                />
              </div>
            )}
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setIsEditMethodDialogOpen(false)}
            >
              Cancel
            </Button>
            <Button onClick={handleEditMethod} className="frontend-btn">
              Save Changes
            </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">
                  â‚¹{walletData.availableBalance.toLocaleString("en-IN")}
                </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 })}
                  >
                    â‚¹{Number(amount).toLocaleString("en-IN")}
                  </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={method.id}>
                      <div className="flex items-center gap-2">
                        {method.type === "bank" ? (
                          <>
                            <Building className="h-4 w-4" />
                            {method.bankName} - {method.accountNumber}
                          </>
                        ) : (
                          <>
                            <Wallet className="h-4 w-4" />
                            UPI - {method.upiId}
                          </>
                        )}
                        {method.isPrimary && (
                          <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">
                      â‚¹{Number(withdrawForm.amount).toLocaleString("en-IN")}{" "}
                      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>
  );
}
