"use client";

import * as React from "react";

import { CustomerStandardAssetListTable } from "@/app/customer/_components/customer-standard-asset-list-table";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { resolveClientCustomerTenant } from "@/lib/tenant/client-tenant";

import { saveTransactionsColumnPrefsClient } from "../../_lib/transactions-api";
import {
  buildTransactionsPageSearchParams,
  DEFAULT_TRANSACTIONS_PAGE_SIZE,
  DEFAULT_TRANSACTIONS_SORTING,
  EMPTY_TRANSACTIONS_FILTERS,
  getTransactionsFilterColumnValue,
  parseTransactionsPageStateFromSearchParams,
  placementDateRangeToFilters,
  setTransactionsFilterColumnValue,
  type TransactionsFilters,
} from "../../_lib/transactions-filters";
import { useTransactionsList } from "../../_lib/use-transactions-list";
import { AllTransactionsDetailSheet } from "./all-transactions-detail-sheet";
import {
  createAllTransactionsColumns,
  FALLBACK_TRANSACTIONS_GRID_COLUMNS,
  TRANSACTIONS_OPTIONS_COLUMN_ID,
} from "./columns";
import type { TransactionRow } from "./schema";

function TransactionsDetailSheet({
  row,
  open,
  onOpenChange,
}: {
  row: TransactionRow | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}) {
  const tenant = resolveClientCustomerTenant() ?? "";
  return (
    <AllTransactionsDetailSheet row={row} open={open} onOpenChange={onOpenChange} tenant={tenant} />
  );
}

function useTransactionsListWithFilterOptions(
  args: Parameters<typeof useTransactionsList>[0],
) {
  const result = useTransactionsList(args);
  const filterOptions = React.useMemo(
    () => ({
      banks: result.bankOptions ?? [],
      types: result.categoryOptions ?? [],
      executionTypes: result.executionTypeOptions ?? [],
      transactions: [],
    }),
    [result.bankOptions, result.categoryOptions, result.executionTypeOptions],
  );

  return { ...result, filterOptions };
}

export function ListAllTransactionsTable() {
  return (
    <CustomerStandardAssetListTable<
      TransactionRow,
      TransactionsFilters,
      typeof TransactionsDetailSheet
    >
      title="All Transactions"
      emptyMessage="No transactions found."
      rowsPerPageId="transactions-rows-per-page"
      moduleId="bond"
      singularName="Transaction"
      formConfig={{ listPath: "/transactions", newButtonLabel: "New transaction" }}
      optionsColumnId={TRANSACTIONS_OPTIONS_COLUMN_ID}
      fallbackColumns={FALLBACK_TRANSACTIONS_GRID_COLUMNS}
      defaultPageSize={DEFAULT_TRANSACTIONS_PAGE_SIZE}
      defaultSorting={DEFAULT_TRANSACTIONS_SORTING}
      emptyFilters={EMPTY_TRANSACTIONS_FILTERS}
      showNewButton={false}
      resolveCanCreate={() => false}
      useList={useTransactionsListWithFilterOptions}
      saveColumnPrefs={saveTransactionsColumnPrefsClient}
      parsePageState={parseTransactionsPageStateFromSearchParams}
      buildPageSearchParams={buildTransactionsPageSearchParams}
      getFilterColumnValue={getTransactionsFilterColumnValue}
      setFilterColumnValue={setTransactionsFilterColumnValue}
      placementDateRangeToFilters={placementDateRangeToFilters}
      getRangeFilters={(filters) => ({
        price: filters.price,
        quantity: filters.quantity,
        amount: filters.amount,
      })}
      applyRangeFilter={(filters, field, value) => {
        if (field !== "price" && field !== "quantity" && field !== "amount") return filters;
        return { ...filters, [field]: value };
      }}
      createColumns={createAllTransactionsColumns}
      DetailSheet={TransactionsDetailSheet}
      toolbarActions={({ filters, setFilters, setPagination, filterOptions }) => {
        const executionType = filters.executionTypeId ?? "All";
        return (
          <Select
            value={executionType}
            onValueChange={(value) => {
              setFilters((current) => ({
                ...current,
                executionTypeId: value === "All" ? undefined : value,
              }));
              setPagination((current) => ({ ...current, pageIndex: 0 }));
            }}
          >
            <SelectTrigger className="h-9 w-40">
              <SelectValue placeholder="Execution Type" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="All">Execution Type</SelectItem>
              {filterOptions.executionTypes.map((type) => {
                const option = typeof type === "string" ? { value: type, label: type } : type;
                return (
                  <SelectItem key={option.value} value={option.value}>
                    {option.label}
                  </SelectItem>
                );
              })}
            </SelectContent>
          </Select>
        );
      }}
    />
  );
}
