"use client"

import { useState, useMemo, useCallback } from "react"
import { Clock, CheckCircle2, XCircle, Wallet } from "lucide-react"
import { Card, CardContent } from "@/components/ui/card"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { WithdrawTable } from "./withdraw-table"
import { SendMoneyDialog } from "./send-money-dialog"
import { CancelWithdrawDialog } from "./cancel-withdraw-dialog"
import { WithdrawDetailsDialog } from "./withdraw-details-dialog"
import { withdrawalDataStore, type WithdrawRequest, type WithdrawUserType } from "@/lib/data/withdrawals"
import { useToastEnhanced } from "@/hooks/use-toast-enhanced"

interface WithdrawalsClientProps {
  userType: WithdrawUserType
  title: string
  description: string
}

function formatCurrency(amount: number): string {
  if (amount >= 10000000) {
    return `₹${(amount / 10000000).toFixed(2)}Cr`
  } else if (amount >= 100000) {
    return `₹${(amount / 100000).toFixed(2)}L`
  } else {
    return `₹${amount.toLocaleString("en-IN")}`
  }
}

export function WithdrawalsClient({ userType, title, description }: WithdrawalsClientProps) {
  const toast = useToastEnhanced()
  const [currentStatus, setCurrentStatus] = useState<"pending" | "approved" | "cancelled">("pending")

  const [withdrawals, setWithdrawals] = useState<WithdrawRequest[]>(withdrawalDataStore.getWithdrawalsByType(userType))
  const [selectedWithdrawal, setSelectedWithdrawal] = useState<WithdrawRequest | null>(null)
  const [isSendMoneyOpen, setIsSendMoneyOpen] = useState(false)
  const [isCancelOpen, setIsCancelOpen] = useState(false)
  const [isDetailsOpen, setIsDetailsOpen] = useState(false)

  const pendingWithdrawals = useMemo(() => withdrawals.filter((w) => w.status === "pending"), [withdrawals])
  const approvedWithdrawals = useMemo(() => withdrawals.filter((w) => w.status === "approved"), [withdrawals])
  const cancelledWithdrawals = useMemo(() => withdrawals.filter((w) => w.status === "cancelled"), [withdrawals])

  const stats = useMemo(() => withdrawalDataStore.getWithdrawalStats(userType), [userType, withdrawals])

  const handleTabChange = useCallback((value: string) => {
    setCurrentStatus(value as "pending" | "approved" | "cancelled")
  }, [])

  const handleSendMoneyClick = useCallback((withdrawal: WithdrawRequest) => {
    setSelectedWithdrawal(withdrawal)
    setIsSendMoneyOpen(true)
  }, [])

  const handleCancelClick = useCallback((withdrawal: WithdrawRequest) => {
    setSelectedWithdrawal(withdrawal)
    setIsCancelOpen(true)
  }, [])

  const handleViewDetails = useCallback((withdrawal: WithdrawRequest) => {
    setSelectedWithdrawal(withdrawal)
    setIsDetailsOpen(true)
  }, [])

  const handleSendMoney = useCallback(
    (amount: number, referenceNumber: string) => {
      if (!selectedWithdrawal) return

      const updated = withdrawalDataStore.approveWithdrawal(selectedWithdrawal.id, amount, referenceNumber)
      if (updated) {
        setWithdrawals(withdrawalDataStore.getWithdrawalsByType(userType))
        toast.success({
          title: "Money Sent Successfully",
          description: `${amount.toLocaleString("en-IN", { style: "currency", currency: "INR" })} has been sent to ${selectedWithdrawal.name}.`,
        })
      }
      setIsSendMoneyOpen(false)
      setSelectedWithdrawal(null)
    },
    [selectedWithdrawal, userType, toast],
  )

  const handleCancelWithdrawal = useCallback(
    (reason: string) => {
      if (!selectedWithdrawal) return

      const updated = withdrawalDataStore.cancelWithdrawal(selectedWithdrawal.id, reason)
      if (updated) {
        setWithdrawals(withdrawalDataStore.getWithdrawalsByType(userType))
        toast.warning({
          title: "Withdrawal Cancelled",
          description: `Withdrawal request from ${selectedWithdrawal.name} has been cancelled.`,
        })
      }
      setIsCancelOpen(false)
      setSelectedWithdrawal(null)
    },
    [selectedWithdrawal, userType, toast],
  )

  return (
    <section aria-labelledby="withdrawals-heading" className="admin-section">
      <header className="admin-page-header">
        <h1 id="withdrawals-heading" className="admin-page-title">
          {title}
        </h1>
        <p className="admin-page-description">{description}</p>
      </header>

      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4 mb-6">
        <Card className="admin-card rounded-xl border-0">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-muted-foreground">Pending Withdrawals</p>
                <p className="text-2xl font-bold text-amber-600">{formatCurrency(stats.totalPendingAmount)}</p>
                <p className="text-xs text-muted-foreground mt-1">{stats.totalPending} pending requests</p>
              </div>
              <div className="h-12 w-12 rounded-xl bg-amber-500/10 flex items-center justify-center">
                <Clock className="h-6 w-6 text-amber-600" aria-hidden="true" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="admin-card rounded-xl border-0">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-muted-foreground">Total Sent</p>
                <p className="text-2xl font-bold text-emerald-600">{formatCurrency(stats.totalApprovedAmount)}</p>
                <p className="text-xs text-muted-foreground mt-1">{stats.totalApproved} approved requests</p>
              </div>
              <div className="h-12 w-12 rounded-xl bg-emerald-500/10 flex items-center justify-center">
                <CheckCircle2 className="h-6 w-6 text-emerald-600" aria-hidden="true" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="admin-card rounded-xl border-0">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-muted-foreground">Total Cancelled</p>
                <p className="text-2xl font-bold text-red-600">{formatCurrency(stats.totalCancelledAmount)}</p>
                <p className="text-xs text-muted-foreground mt-1">{stats.totalCancelled} cancelled requests</p>
              </div>
              <div className="h-12 w-12 rounded-xl bg-red-500/10 flex items-center justify-center">
                <XCircle className="h-6 w-6 text-red-600" aria-hidden="true" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="admin-card rounded-xl border-0">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-muted-foreground">Total Processed</p>
                <p className="text-2xl font-bold text-primary">
                  {formatCurrency(stats.totalApprovedAmount + stats.totalCancelledAmount)}
                </p>
                <p className="text-xs text-muted-foreground mt-1">
                  {stats.totalApproved + stats.totalCancelled} total processed
                </p>
              </div>
              <div className="h-12 w-12 rounded-xl bg-primary/10 flex items-center justify-center">
                <Wallet className="h-6 w-6 text-primary" aria-hidden="true" />
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      <Tabs value={currentStatus} onValueChange={handleTabChange} className="w-full">
        <TabsList className="mb-6 h-auto p-1.5 bg-muted/50 rounded-xl border border-border/50">
          <TabsTrigger
            value="pending"
            className="rounded-lg data-[state=active]:bg-background data-[state=active]:shadow-sm px-4 py-2"
          >
            Pending ({pendingWithdrawals.length})
          </TabsTrigger>
          <TabsTrigger
            value="approved"
            className="rounded-lg data-[state=active]:bg-background data-[state=active]:shadow-sm px-4 py-2"
          >
            Approved ({approvedWithdrawals.length})
          </TabsTrigger>
          <TabsTrigger
            value="cancelled"
            className="rounded-lg data-[state=active]:bg-background data-[state=active]:shadow-sm px-4 py-2"
          >
            Cancelled ({cancelledWithdrawals.length})
          </TabsTrigger>
        </TabsList>

        <TabsContent value="pending" className="mt-0">
          <WithdrawTable
            withdrawals={pendingWithdrawals}
            status="pending"
            onSendMoney={handleSendMoneyClick}
            onCancel={handleCancelClick}
            onViewDetails={handleViewDetails}
          />
        </TabsContent>

        <TabsContent value="approved" className="mt-0">
          <WithdrawTable
            withdrawals={approvedWithdrawals}
            status="approved"
            onSendMoney={handleSendMoneyClick}
            onCancel={handleCancelClick}
            onViewDetails={handleViewDetails}
          />
        </TabsContent>

        <TabsContent value="cancelled" className="mt-0">
          <WithdrawTable
            withdrawals={cancelledWithdrawals}
            status="cancelled"
            onSendMoney={handleSendMoneyClick}
            onCancel={handleCancelClick}
            onViewDetails={handleViewDetails}
          />
        </TabsContent>
      </Tabs>

      <SendMoneyDialog
        withdrawal={selectedWithdrawal}
        open={isSendMoneyOpen}
        onOpenChange={setIsSendMoneyOpen}
        onConfirm={handleSendMoney}
      />

      <CancelWithdrawDialog
        withdrawal={selectedWithdrawal}
        open={isCancelOpen}
        onOpenChange={setIsCancelOpen}
        onConfirm={handleCancelWithdrawal}
      />

      <WithdrawDetailsDialog withdrawal={selectedWithdrawal} open={isDetailsOpen} onOpenChange={setIsDetailsOpen} />
    </section>
  )
}
