"use client";

import { useCallback, useEffect, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Search,
  Filter,
  Wallet,
  Calendar,
  CheckCircle,
  XCircle,
  Clock,
  Building,
  Loader2,
  AlertCircle,
} from "lucide-react";
import { getHotelWithdrawalRequestsAction } from "@/features/payment/actions/withdrawals-actions";
import type { WithdrawalPagination } from "@/core/api/services/withdrawals";
import type {
  WithdrawRequest,
  WithdrawStatus,
} from "@/features/payment/services/withdrawals.service";

interface WithdrawTableProps {
  status: string;
}

type HotelWithdrawalStatus = WithdrawStatus;

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

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 apiStatusByTab = {
  pending: "pending",
  approved: "approved",
  cancelled: "rejected",
} as const;

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<
  HotelWithdrawalStatus,
  WithdrawalTabState
> {
  return {
    pending: createEmptyWithdrawalTabState(),
    approved: createEmptyWithdrawalTabState(),
    cancelled: createEmptyWithdrawalTabState(),
  };
}

function normalizeStatus(value: string): HotelWithdrawalStatus {
  if (value === "rejected") return "cancelled";
  if (value === "approved" || value === "cancelled") return value;
  return "pending";
}

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

export function WithdrawTable({ status }: WithdrawTableProps) {
  const [searchQuery, setSearchQuery] = useState("");
  const [withdrawalTabsState, setWithdrawalTabsState] = useState<
    Record<HotelWithdrawalStatus, WithdrawalTabState>
  >(getInitialWithdrawalTabsState);
  const activeStatus = normalizeStatus(status);
  const activeTabState = withdrawalTabsState[activeStatus];
  const withdrawals = activeTabState.withdrawals;
  const activePagination = activeTabState.pagination;
  const config = statusConfig[activeStatus];
  const StatusIcon = config?.icon || Clock;

  const loadWithdrawals = useCallback(
    async (
      tab: HotelWithdrawalStatus,
      page = 1,
      options: { force?: boolean } = {}
    ) => {
      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 getHotelWithdrawalRequestsAction(
          apiStatusByTab[tab],
          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[activeStatus];

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

  const filteredWithdrawals = withdrawals.filter(
    (w) =>
      w.id.toLowerCase().includes(searchQuery.toLowerCase()) ||
      w.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      w.bankDetails.bankName
        .toLowerCase()
        .includes(searchQuery.toLowerCase()) ||
      String(w.withdrawAmount).includes(searchQuery) ||
      formatCurrency(w.withdrawAmount).includes(searchQuery)
  );

  return (
    <Card className="border bg-card">
      <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" />
            <p className="text-muted-foreground mb-4">{activeTabState.error}</p>
            <Button
              variant="outline"
              onClick={() =>
                loadWithdrawals(activeStatus, activePagination.currentPage, {
                  force: true,
                })
              }
            >
              Try Again
            </Button>
          </div>
        ) : filteredWithdrawals.length === 0 ? (
          <div className="text-center py-12">
            <Wallet className="h-12 w-12 mx-auto text-muted-foreground/50 mb-3" />
            <p className="text-muted-foreground">No withdrawals found</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-muted/30 hover:bg-muted/50 border border-border/50 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>
                    {activeStatus === "pending" && (
                      <p className="text-xs text-muted-foreground mt-1">
                        Expected: {getExpectedDate(withdrawal.requestedAt)}
                      </p>
                    )}
                    {activeStatus === "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>
                        )}
                      </>
                    )}
                    {activeStatus === "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(
                        activeStatus,
                        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(activeStatus, link.page, {
                                force: true,
                              })
                            : undefined
                        }
                      >
                        {link.label}
                      </Button>
                    ))}
                  <Button
                    variant="outline"
                    size="sm"
                    disabled={
                      activePagination.currentPage >=
                        activePagination.lastPage || activeTabState.isLoading
                    }
                    onClick={() =>
                      loadWithdrawals(
                        activeStatus,
                        activePagination.currentPage + 1,
                        { force: true }
                      )
                    }
                  >
                    Next
                  </Button>
                </div>
              </div>
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
}
