"use client";
import { useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";
import {
  DataTable,
  type Column,
  type DataTableFilter,
  type RemoteTableState,
} from "@/components/shared/data-table";
import { PreviewLink } from "@/components/layout/preview-context";
import {
  DetailList,
  StatusBadge,
} from "@/components/shared/page";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { currency, recentDateTime } from "@/lib/format";
import {
  getPaymentTransactions,
  type TransactionPagination,
} from "./transactions-api";
import type { PaymentTransaction } from "./transactions-model";

const pageSizes = [10, 25, 50, 100];
const initialPagination: TransactionPagination = {
  page: 1,
  limit: 10,
  total: 0,
  pages: 1,
};
const transactionFilters: DataTableFilter<PaymentTransaction>[] = [
  {
    key: "status",
    label: "Status",
    options: [
      "pending",
      "processing",
      "success",
      "failed",
      "canceled",
      "expired",
      "reversed",
    ],
  },
  {
    key: "transactionType",
    queryKey: "transaction_type",
    label: "Transaction type",
    options: [
      "TOPUP",
      "CHARGE",
      "RESERVATION",
      "SUBSCRIPTION",
      "INVOICE",
      "WITHDRAWAL",
      "FREE_CREDIT",
    ],
  },
  {
    key: "gateway",
    queryKey: "payment_gateway",
    label: "Payment gateway",
    options: ["paypal", "xendit", "midtrans"],
  },
  {
    key: "channelCode",
    queryKey: "payment_method",
    label: "Payment method",
    options: [
      "cards",
      "virtual_account",
      "e_wallet",
      "over_the_counter",
      "qr",
    ],
  },
  { key: "email", queryKey: "email", label: "Customer email", type: "text" },
  { key: "userId", queryKey: "user_id", label: "User ID", type: "text" },
  { key: "id", queryKey: "order_id", label: "Transaction ID", type: "text" },
  {
    key: "createdAt",
    queryKey: "start_date",
    label: "Created from",
    type: "date",
    dateComparison: "gte",
    maxQueryKey: "end_date",
  },
  {
    key: "createdAt",
    queryKey: "end_date",
    label: "Created to",
    type: "date",
    dateComparison: "lte",
    minQueryKey: "start_date",
  },
];

function TransactionCustomerEmail({
  email,
  userId,
}: {
  email: string;
  userId: string;
}) {
  if (!email) return "—";
  if (!userId || userId === "00000000-0000-0000-0000-000000000000") {
    return email;
  }

  return (
    <PreviewLink
      href={`/customers/${encodeURIComponent(userId)}`}
      whenDenied={email}
      className="whitespace-nowrap text-foreground hover:text-success hover:underline"
    >
      {email}
    </PreviewLink>
  );
}

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

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

function formatAmount(amount: number, currencyCode: string) {
  const code = currencyCode.toUpperCase();
  if (code === "IDR") return currency(amount);
  try {
    return new Intl.NumberFormat("en-US", {
      style: "currency",
      currency: code,
    }).format(amount);
  } catch {
    return `${code} ${amount.toLocaleString("en-US")}`;
  }
}

function readPage(value: string | null) {
  const page = Number(value);
  return Number.isSafeInteger(page) && page > 0 ? page : 1;
}

function readLimit(value: string | null) {
  const limit = Number(value);
  return pageSizes.includes(limit) ? limit : 10;
}

export function TransactionHistory() {
  const params = useSearchParams();
  const page = readPage(params.get("paginate_page"));
  const limit = readLimit(params.get("paginate_limit"));
  const search = params.get("query") ?? "";
  const status = params.get("status") ?? "";
  const transactionType = params.get("transaction_type") ?? "";
  const email = params.get("email") ?? "";
  const userId = params.get("user_id") ?? "";
  const orderId = params.get("order_id") ?? "";
  const paymentGateway = params.get("payment_gateway") ?? "";
  const paymentMethod = params.get("payment_method") ?? "";
  const startDate = params.get("start_date") ?? "";
  const endDate = params.get("end_date") ?? "";
  const [remoteRows, setRemoteRows] = useState<PaymentTransaction[]>([]);
  const [pagination, setPagination] =
    useState<TransactionPagination>(initialPagination);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [refreshKey, setRefreshKey] = useState(0);
  const [selected, setSelected] = useState<PaymentTransaction | null>(null);

  useEffect(() => {
    const controller = new AbortController();
    async function load() {
      setLoading(true);
      setError("");
      try {
        const result = await getPaymentTransactions(
          {
            page,
            limit,
            search,
            status,
            transactionType,
            email,
            userId,
            orderId,
            paymentGateway,
            paymentMethod,
            startDate,
            endDate,
          },
          controller.signal,
        );
        setRemoteRows(result.rows);
        setPagination(result.pagination);
      } catch (err: unknown) {
        if (controller.signal.aborted) return;
        setRemoteRows([]);
        setError(
          err instanceof Error
            ? err.message
            : "Could not load transactions.",
        );
      } finally {
        if (!controller.signal.aborted) setLoading(false);
      }
    }
    void load();
    return () => controller.abort();
  }, [
    page,
    limit,
    search,
    status,
    transactionType,
    email,
    userId,
    orderId,
    paymentGateway,
    paymentMethod,
    startDate,
    endDate,
    refreshKey,
  ]);

  const columns: Column<PaymentTransaction>[] = [
    {
      key: "id",
      label: "Transaction ID",
      sortKey: null,
    },
    {
      key: "email",
      label: "Customer email",
      sortKey: null,
      render: (row) => (
        <TransactionCustomerEmail email={row.email} userId={row.userId} />
      ),
    },
    {
      key: "transactionType",
      label: "Type",
      sortKey: null,
      render: (row) => transactionTypeLabel(row.transactionType),
    },
    {
      key: "amount",
      label: "Amount",
      sortKey: null,
      render: (row) => formatAmount(row.amount, row.currency),
    },
    {
      key: "status",
      label: "Status",
      sortKey: null,
      render: (row) => <StatusBadge>{statusLabel(row.status)}</StatusBadge>,
    },
    {
      key: "createdAt",
      label: "Created At",
      sortKey: null,
      render: (row) => (row.createdAt ? recentDateTime(row.createdAt) : "—"),
    },
  ];

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

  return (
    <div className="space-y-5">
      <DataTable
        title="Transaction History"
        description="Review payment transaction types, amounts, and status."
        rows={remoteRows}
        remote={remoteTable}
        searchDebounceMs={350}
        pageSizes={pageSizes}
        searchPlaceholder="Transaction ID or customer email..."
        filters={transactionFilters}
        emptyMessage="No transactions found."
        columns={columns}
        actions={(row) => (
          <Button variant="outline" size="sm" onClick={() => setSelected(row)}>
            Details
          </Button>
        )}
      />
      <Dialog
        open={!!selected}
        onOpenChange={(open) => {
          if (!open) setSelected(null);
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Transaction details</DialogTitle>
            <DialogDescription>
              {selected?.id}
            </DialogDescription>
          </DialogHeader>
          {selected && (
            <DetailList
              items={{
                Type: transactionTypeLabel(selected.transactionType),
                Amount: formatAmount(selected.amount, selected.currency),
                Status: <StatusBadge>{statusLabel(selected.status)}</StatusBadge>,
                "Channel type": selected.channelCode || "—",
                "Payment gateway": selected.gateway || "—",
                ...(selected.userId ? { "User ID": selected.userId } : {}),
                Email: (
                  <TransactionCustomerEmail
                    email={selected.email}
                    userId={selected.userId}
                  />
                ),
                ...(selected.reference ? { Reference: selected.reference } : {}),
                Created: selected.createdAt
                  ? recentDateTime(selected.createdAt)
                  : "—",
              }}
            />
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
