"use client";
import { useEffect, useState, type ReactNode } from "react";
import { useSearchParams } from "next/navigation";
import {
  DataTable,
  type Column,
  type RemoteTableState,
} from "@/components/shared/data-table";
import { StatusBadge } from "@/components/shared/page";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { readListQuery } from "@/lib/list-query";
import { currency, recentDateTime } from "@/lib/format";
import {
  getWithdrawalRequest,
  getWithdrawalRequests,
  type WithdrawalPagination,
} from "./api-client";
import type { WithdrawalRequest } from "./model";

const statusOptions = [
  "PENDING_APPROVAL",
  "APPROVED",
  "PROCESSING",
  "PAID",
  "REJECTED",
  "FAILED",
  "CANCELLED",
];

const initialPagination: WithdrawalPagination = {
  page: 1,
  limit: 25,
  total: 0,
  pages: 1,
};

function statusLabel(status: string) {
  return status
    .toLowerCase()
    .replaceAll("_", " ")
    .replace(/\b\w/g, (letter) => letter.toUpperCase());
}

function WithdrawalDetailSection({
  title,
  items,
}: {
  title: string;
  items: Record<string, ReactNode>;
}) {
  return (
    <section className="overflow-hidden rounded-lg border bg-card">
      <h3 className="border-b bg-muted/30 px-4 py-3 text-sm font-semibold">
        {title}
      </h3>
      <dl className="grid gap-x-5 gap-y-4 p-4 sm:grid-cols-2">
        {Object.entries(items).map(([label, value]) => (
          <div key={label} className="min-w-0">
            <dt className="text-xs text-muted-foreground">{label}</dt>
            <dd className="mt-1 break-words font-medium">{value ?? "—"}</dd>
          </div>
        ))}
      </dl>
    </section>
  );
}

export function WithdrawalRequests() {
  const params = useSearchParams();
  const query = readListQuery(Object.fromEntries(params));
  const status = params.get("status") ?? "";
  const createdAtStart = params.get("created_at_start") ?? "";
  const createdAtEnd = params.get("created_at_end") ?? "";
  const requestedSort = params.get("sort_by") ?? "";
  const sortBy = ["created_at", "updated_at", "amount"].includes(requestedSort)
    ? requestedSort
    : "created_at";
  const sortOrder = params.get("sort_order") === "asc" ? "asc" : "desc";

  const [remoteRows, setRemoteRows] = useState<WithdrawalRequest[]>([]);
  const [pagination, setPagination] =
    useState<WithdrawalPagination>(initialPagination);
  const [listLoading, setListLoading] = useState(true);
  const [listError, setListError] = useState("");
  const [refreshKey, setRefreshKey] = useState(0);
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [selectedDetail, setSelectedDetail] =
    useState<WithdrawalRequest | null>(null);
  const [detailLoading, setDetailLoading] = useState(false);
  const [detailError, setDetailError] = useState("");
  const [detailRetryKey, setDetailRetryKey] = useState(0);
  useEffect(() => {
    const controller = new AbortController();
    async function load() {
      setListLoading(true);
      setListError("");
      try {
        const result = await getWithdrawalRequests(
          {
            page: query.page,
            limit: query.limit,
            search: query.search,
            status,
            createdAtStart,
            createdAtEnd,
            sortBy,
            sortOrder,
          },
          controller.signal,
        );
        setRemoteRows(result.rows);
        setPagination(result.pagination);
      } catch (err: unknown) {
        if (controller.signal.aborted) return;
        setRemoteRows([]);
        setListError(
          err instanceof Error
            ? err.message
            : "Could not load withdrawal requests.",
        );
      } finally {
        if (!controller.signal.aborted) setListLoading(false);
      }
    }
    void load();
    return () => controller.abort();
  }, [
    query.page,
    query.limit,
    query.search,
    status,
    createdAtStart,
    createdAtEnd,
    sortBy,
    sortOrder,
    refreshKey,
  ]);

  useEffect(() => {
    if (!selectedId) return;
    const withdrawalId = selectedId;
    const controller = new AbortController();
    async function load() {
      setDetailLoading(true);
      setDetailError("");
      try {
        const detail = await getWithdrawalRequest(withdrawalId, controller.signal);
        setSelectedDetail((current) => {
          if (!current || current.id !== withdrawalId) return detail;
          return {
            ...current,
            ...detail,
            email: detail.email || current.email,
            fullName: detail.fullName || current.fullName,
            phone: detail.phone || current.phone,
          };
        });
      } catch (err: unknown) {
        if (controller.signal.aborted) return;
        setDetailError(
          err instanceof Error
            ? err.message
            : "Could not load withdrawal details.",
        );
      } finally {
        if (!controller.signal.aborted) setDetailLoading(false);
      }
    }
    void load();
    return () => controller.abort();
  }, [selectedId, detailRetryKey]);

  const selected =
    selectedDetail?.id === selectedId
      ? selectedDetail
      : remoteRows.find((row) => row.id === selectedId);

  function open(row: WithdrawalRequest) {
    setSelectedId(row.id);
    setSelectedDetail(row);
    setDetailError("");
  }

  function closeDetails() {
    setSelectedId(null);
    setSelectedDetail(null);
    setDetailError("");
  }

  const liveColumns: Column<WithdrawalRequest>[] = [
    {
      key: "createdAt",
      label: "Request Time",
      sortKey: "created_at",
      render: (row) => (
        <div>
          {recentDateTime(row.createdAt)}
          <div className="text-xs text-muted-foreground">
            {row.id}
            {row.email ? ` · ${row.email}` : ""}
          </div>
        </div>
      ),
    },
    {
      key: "bank",
      label: "Bank Details",
      sortKey: null,
      render: (row) => (
        <div className="min-w-40">
          {row.bank || "—"} · {row.accountNumber || "—"}
          <div className="text-xs text-muted-foreground">
            {row.accountHolder || "—"}
          </div>
        </div>
      ),
    },
    {
      key: "amount",
      label: "Amount",
      sortKey: "amount",
      render: (row) => currency(row.amount),
    },
    {
      key: "adminFee",
      label: "Transferred Amount",
      sortKey: null,
      render: (row) => (
        <div>
          {currency(Math.max(0, row.amount - row.adminFee))}
          <div className="text-xs text-muted-foreground">
            Fee: {currency(row.adminFee)}
          </div>
        </div>
      ),
    },
    {
      key: "status",
      label: "Status",
      sortKey: null,
      render: (row) => <StatusBadge>{statusLabel(row.status)}</StatusBadge>,
    },
    {
      key: "updatedAt",
      label: "Updated At",
      sortKey: "updated_at",
      render: (row) =>
        row.updatedAt ? recentDateTime(row.updatedAt) : "—",
    },
  ];

  const remoteTable: RemoteTableState = {
    ...pagination,
    loading: listLoading,
    error: listError,
    onRefresh: () => setRefreshKey((current) => current + 1),
  };

  return (
    <div className="space-y-5">
      <DataTable
        title="Withdrawal Requests"
        description="Review bank details, requested amounts, and processing history."
        rows={remoteRows}
        remote={remoteTable}
        filters={[
          { key: "status", label: "Status", options: statusOptions },
          {
            key: "createdAt",
            queryKey: "created_at_start",
            label: "Created from",
            type: "date",
            dateComparison: "gte",
            maxQueryKey: "created_at_end",
          },
          {
            key: "createdAt",
            queryKey: "created_at_end",
            label: "Created to",
            type: "date",
            dateComparison: "lte",
            minQueryKey: "created_at_start",
            hint: "Asia/Jakarta · inclusive dates",
          },
        ]}
        searchPlaceholder="Request, customer or bank..."
        columns={liveColumns}
        actions={(row) => (
          <Button variant="outline" size="sm" onClick={() => open(row)}>
            View
          </Button>
        )}
      />
      <Dialog
        open={!!selectedId}
        onOpenChange={(open) => {
          if (!open) closeDetails();
        }}
      >
        <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-3xl">
          <DialogHeader>
            <DialogTitle>Withdrawal details</DialogTitle>
            <DialogDescription className="break-all font-mono text-xs">
              {selected?.id}
            </DialogDescription>
          </DialogHeader>
          {selected && (
            <>
              <WithdrawalDetailSection
                title="Withdrawal summary"
                items={{
                  Status: <StatusBadge>{statusLabel(selected.status)}</StatusBadge>,
                  "Requested amount": currency(selected.amount),
                  "Admin fee": currency(selected.adminFee),
                  "Transferred amount": currency(
                    Math.max(0, selected.amount - selected.adminFee),
                  ),
                  "Payout status": selected.payoutStatus || "—",
                  ...(selected.createdAt
                    ? { "Requested at": recentDateTime(selected.createdAt) }
                    : {}),
                  ...(selected.updatedAt
                    ? { "Updated at": recentDateTime(selected.updatedAt) }
                    : {}),
                  ...(selected.rejectionReason
                    ? { "Rejection reason": selected.rejectionReason }
                    : {}),
                  ...(selected.transferProofUrl
                    ? {
                        "Transfer proof": (
                          <a
                            className="text-primary underline underline-offset-2"
                            href={selected.transferProofUrl}
                            target="_blank"
                            rel="noreferrer"
                          >
                            Open proof
                          </a>
                        ),
                      }
                    : {}),
                }}
              />
              <div className="grid gap-3 sm:grid-cols-2">
                <WithdrawalDetailSection
                  title="Customer"
                  items={{
                    Name: selected.fullName || "—",
                    Email: selected.email || "—",
                    Phone: selected.phone || "—",
                  }}
                />
                <WithdrawalDetailSection
                  title="Bank details"
                  items={{
                    Bank: selected.bank || "—",
                    "Account number": selected.accountNumber || "—",
                    "Account holder": selected.accountHolder || "—",
                  }}
                />
              </div>
              <WithdrawalDetailSection
                title="Customer account activity"
                items={{
                  Balance:
                    selected.balance === undefined
                      ? "—"
                      : currency(selected.balance),
                  "Total sessions":
                    selected.totalSession?.toLocaleString("id-ID") ?? "—",
                  "Last top-up": selected.lastTopUp ? (
                    <div className="space-y-1">
                      <div>
                        {selected.lastTopUp.amount === null
                          ? "—"
                          : `${selected.lastTopUp.currency || "IDR"} ${selected.lastTopUp.amount.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`}
                      </div>
                      {selected.lastTopUp.id && (
                        <span
                          className="block truncate font-mono text-[11px] text-muted-foreground"
                          title={selected.lastTopUp.id}
                        >
                          {selected.lastTopUp.id}
                        </span>
                      )}
                      {selected.lastTopUp.createdAt && (
                        <div className="text-xs text-muted-foreground">
                          {recentDateTime(selected.lastTopUp.createdAt)}
                        </div>
                      )}
                    </div>
                  ) : "—",
                }}
              />
              {detailLoading && (
                <p role="status" className="text-sm text-muted-foreground">
                  Loading full withdrawal details…
                </p>
              )}
              {detailError && (
                <div role="alert" className="space-y-2 text-sm text-destructive">
                  <p>{detailError}</p>
                  <Button
                    type="button"
                    size="sm"
                    variant="outline"
                    onClick={() => setDetailRetryKey((current) => current + 1)}
                  >
                    Retry details
                  </Button>
                </div>
              )}
            </>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
