﻿"use client";

import { useState, useMemo, useCallback, useEffect } 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 { WithdrawDetailsDialog } from "./withdraw-details-dialog";
import type {
  WithdrawRequest,
  WithdrawUserType,
} from "@/features/payment/services/withdrawals.service";
import {
  getAgentWithdrawalRequestsAction,
  getHotelWithdrawalRequestsAction,
} from "@/features/payment/actions/withdrawals-actions";

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")}`;
  }
}

function getWithdrawalStats(withdrawals: WithdrawRequest[]) {
  const pending = withdrawals.filter((w) => w.status === "pending");
  const approved = withdrawals.filter((w) => w.status === "approved");
  const cancelled = withdrawals.filter((w) => w.status === "cancelled");

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

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

  const [withdrawals, setWithdrawals] = useState<WithdrawRequest[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [selectedWithdrawal, setSelectedWithdrawal] =
    useState<WithdrawRequest | null>(null);
  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(() => getWithdrawalStats(withdrawals), [withdrawals]);

  useEffect(() => {
    let isActive = true;
    const getWithdrawalRequests =
      userType === "agent"
        ? getAgentWithdrawalRequestsAction
        : getHotelWithdrawalRequestsAction;

    setIsLoading(true);
    setErrorMessage(null);

    getWithdrawalRequests()
      .then((result) => {
        if (!isActive) return;

        if (!result.success || !result.data) {
          setErrorMessage(
            result.error || `Unable to load ${userType} withdrawal requests.`
          );
          return;
        }

        setWithdrawals(result.data.withdrawals);
      })
      .catch((error) => {
        if (!isActive) return;
        setErrorMessage(
          error instanceof Error
            ? error.message
            : `Unable to load ${userType} withdrawal requests.`
        );
      })
      .finally(() => {
        if (isActive) setIsLoading(false);
      });

    return () => {
      isActive = false;
    };
  }, [userType]);

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

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

  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>

      {isLoading && (
        <div className="mb-4 rounded-md border bg-muted/30 px-4 py-3 text-sm text-muted-foreground">
          Loading withdrawal requests...
        </div>
      )}

      {errorMessage && (
        <div className="mb-4 rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive">
          {errorMessage}
        </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"
            onViewDetails={handleViewDetails}
          />
        </TabsContent>

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

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

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