"use client";

import DataTable from "@/app/features/DataTable/DataTable";
import { useDispatch, useSelector } from "react-redux";
import { AppDispatch } from "@/app/redux/store";
import {
  selectFilters,
  selectPagination,
  selectSort,
} from "@/app/redux/advanedSearch/selectors";
import {
  setStatus,
  setError as setAdvancedSearchError,
} from "@/app/redux/advanedSearch/advancedSearchSlice";
import { useEffect, useMemo, useState } from "react";
import { TransactionRow, BackendTransaction } from "../interface";

export default function DepositTransactionPage() {
  const dispatch = useDispatch<AppDispatch>();
  const filters = useSelector(selectFilters);
  const pagination = useSelector(selectPagination);
  const sort = useSelector(selectSort);
  const [tableRows, setTableRows] = useState<TransactionRow[]>([]);
  const [rowCount, setRowCount] = useState(0);

  const memoizedRows = useMemo(() => tableRows, [tableRows]);

  const depositFilters = useMemo(() => {
    return {
      ...filters,
      Type: {
        operator: "==",
        value: "deposit",
      },
    };
  }, [filters]);

  useEffect(() => {
    const fetchDeposits = async () => {
      dispatch(setStatus("loading"));
      dispatch(setAdvancedSearchError(null));
      try {
        const response = await fetch("/api/dashboard/transactions/deposits", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            filters: depositFilters,
            pagination,
            sort,
          }),
        });

        if (!response.ok) {
          dispatch(setAdvancedSearchError("Failed to fetch deposits"));
          setTableRows([]);
          return;
        }

        const backendData = await response.json();
        const transactions: BackendTransaction[] =
          backendData.transactions || [];

        const rows: TransactionRow[] = transactions.map(tx => ({
          id: tx.id,
          userId: tx.customer,
          transactionId: String(tx.external_id ?? tx.id),
          type: tx.type,
          currency: tx.currency,
          amount: tx.amount,
          status: tx.status,
          dateTime: tx.created || tx.modified,
          merchantId: tx.merchant_id,
          pspId: tx.psp_id,
          methodId: tx.method_id,
          modified: tx.modified,
        }));

        setTableRows(rows);
        setRowCount(100);
        dispatch(setStatus("succeeded"));
      } catch (error) {
        dispatch(
          setAdvancedSearchError(
            error instanceof Error ? error.message : "Unknown error"
          )
        );
        setTableRows([]);
      }
    };

    fetchDeposits();
  }, [dispatch, depositFilters, pagination, sort]);

  return (
    <DataTable rows={memoizedRows} enableStatusActions totalRows={rowCount} />
  );
}
