"use client";

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

export default function AllTransactionPage() {
  const dispatch = useDispatch<AppDispatch>();
  const filters = useSelector(selectFilters);
  const pagination = useSelector(selectPagination);
  const sort = useSelector(selectSort);

  const [tableData, setTableData] = useState<{
    transactions: TransactionRow[];
    total: number;
  }>({ transactions: [], total: 0 });
  const [totalRows, setRowCount] = useState(0);
  const extraColumns: string[] = []; // static for now

  // Memoize rows to avoid new reference each render
  const memoizedRows = useMemo(
    () => tableData.transactions,
    [tableData.transactions]
  );

  // Fetch data when filters, pagination, or sort changes
  useEffect(() => {
    const fetchData = async () => {
      dispatch(setAdvancedSearchError(null));
      try {
        const response = await fetch("/api/dashboard/transactions", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ filters, pagination, sort }),
        });

        if (!response.ok) {
          dispatch(setAdvancedSearchError("Failed to fetch transactions"));
          setTableData({ transactions: [], total: 0 });
          return;
        }

        const data = await response.json();
        const transactions = data.transactions || [];

        const rows = transactions.map((tx: BackendTransaction) => ({
          id: tx.id || 0,
          userId: tx.customer,
          transactionId: 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,
        }));

        setTableData({ transactions: rows, total: data?.total });
      } catch (error) {
        dispatch(
          setAdvancedSearchError(
            error instanceof Error ? error.message : "Unknown error"
          )
        );
        setTableData({ transactions: [], total: 0 });
      }
    };

    fetchData();
  }, [dispatch, filters, pagination, sort]);

  return (
    <DataTable
      rows={memoizedRows}
      extraColumns={extraColumns}
      totalRows={tableData.total}
    />
  );
}
