"use client"

import { useState, useEffect } from "react"
import { WithdrawalRequestsTable } from "@/components/withdrawal-requests-table"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Table, TableHeader, TableRow, TableHead, TableBody, TableCell } from "@/components/ui/table" // New import
import { getWithdrawalRequests, approveAgentWithdrawal, approveSuperAgentWithdrawal, disburseAllCommissionsToCredit, getPendingCommissionsSummary } from "@/services/api" // Modified import


export default function WithdrawalRequestsPage() {
  const [withdrawalRequests, setWithdrawalRequests] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)
  const [pendingSummary, setPendingSummary] = useState(null) // New state
  const [pendingLoading, setPendingLoading] = useState(true) // New state
  const [pendingError, setPendingError] = useState(null) // New state

  const fetchRequests = async () => {
    setLoading(true)
    setError(null)
    try {
      const data = await getWithdrawalRequests()
      setWithdrawalRequests(data)
    } catch (err) {
      setError("Failed to fetch withdrawal requests.")
      console.error(err)
    } finally {
      setLoading(false)
    }
  }

  const fetchPendingSummary = async () => { // New function
    setPendingLoading(true)
    setPendingError(null)
    try {
      const data = await getPendingCommissionsSummary()
      setPendingSummary(data)
    } catch (err) {
      setPendingError("Failed to fetch pending commissions summary.")
      console.error(err)
    } finally {
      setPendingLoading(false)
    }
  }

  useEffect(() => {
    fetchRequests()
    fetchPendingSummary() // Fetch summary on initial load
  }, [])

  const handleApprove = async (withdrawalId, type) => {
    console.log(`Approving ${type} withdrawal request ${withdrawalId}`)
    try {
      const requestToApprove = withdrawalRequests.find(req => req.withdrawal_id === withdrawalId);

      if (!requestToApprove) {
        throw new Error("Withdrawal request not found.");
      }

      const payload = { customer_id: requestToApprove.requester_id };

      if (type === "agent") {
        await approveAgentWithdrawal(withdrawalId, payload)
      } else if (type === "super_agent") {
        await approveSuperAgentWithdrawal(withdrawalId, payload)
      }
      alert(`Withdrawal request ${withdrawalId} (${type}) approved!`)
      fetchRequests()
    } catch (err) {
      console.error("Approval failed:", err)
      alert("Failed to approve withdrawal request.")
    }
  }

  const handleDisburseAll = async () => {
    if (!confirm("Are you sure you want to disburse all outstanding commissions to credit? This action cannot be undone.")) {
      return;
    }
    setPendingLoading(true); // Use pendingLoading for this tab
    setPendingError(null);
    try {
      await disburseAllCommissionsToCredit();
      alert("All outstanding commissions have been disbursed to credit successfully!");
      fetchPendingSummary(); // Re-fetch summary to update the list
    } catch (err) {
      console.error("Failed to disburse commissions:", err);
      setPendingError("Failed to disburse all outstanding commissions.");
      alert("Failed to disburse all outstanding commissions.");
    } finally {
      setPendingLoading(false);
    }
  };

  return (
    <div className="flex-1 space-y-4 p-8 pt-6">
      <h2 className="text-3xl font-bold tracking-tight mb-4">Commission Management</h2> {/* Changed title */}

      <Tabs defaultValue="withdrawal-requests" className="space-y-4">
        <TabsList>
          <TabsTrigger value="withdrawal-requests">Withdrawal Requests</TabsTrigger>
          <TabsTrigger value="pending-commissions">Pending Commissions</TabsTrigger>
        </TabsList>

        <TabsContent value="withdrawal-requests" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Manage Commission Withdrawal Requests</CardTitle>
            </CardHeader>
            <CardContent>
              {loading && <p>Loading withdrawal requests...</p>}
              {error && <p className="text-red-500">{error}</p>}
              {!loading && !error && (
                <WithdrawalRequestsTable
                  requests={withdrawalRequests}
                  onApprove={handleApprove}
                />
              )}
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="pending-commissions" className="space-y-4">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <CardTitle className="text-sm font-medium">Pending Commissions Summary</CardTitle>
              <Button onClick={handleDisburseAll}>Disburse All Outstanding Commissions</Button>
            </CardHeader>
            <CardContent>
              {pendingLoading && <p>Loading pending commissions summary...</p>}
              {pendingError && <p className="text-red-500">{pendingError}</p>}
              {!pendingLoading && !pendingError && pendingSummary && (
                <>
                  <div className="text-2xl font-bold mb-4">
                    Total Pending: {pendingSummary.total_pending_commission}
                  </div>

                  {pendingSummary.breakdown && pendingSummary.breakdown.length > 0 ? (
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>Username</TableHead>
                          <TableHead>Role</TableHead>
                          <TableHead className="text-right">Pending Commission</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {pendingSummary.breakdown.map((item) => (
                          <TableRow key={item.user_id}>
                            <TableCell>{item.username}</TableCell>
                            <TableCell>{item.role}</TableCell>
                            <TableCell className="text-right">{item.pending_commission}</TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  ) : (
                    <p>No detailed breakdown available.</p>
                  )}
                </>
              )}
              {!pendingLoading && !pendingError && !pendingSummary && (
                <p>No pending commissions found.</p>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  )
}
