'use client';

/**
 * 계좌 입출금 내역
 *
 * 기획서 기준:
 * - 통계 5개: 입금, 출금, 잔고, 계좌, 거래
 * - 테이블 11컬럼: 체크박스, No., 거래일시, 구분, 계좌정보, 적요/내용, 입금, 출금, 잔액, 취급점, 상대계좌예금주명
 * - 필터: ④구분(은행계좌/대출계좌/증권계좌/보험계좌), ⑤금융기관
 * - 액션: ①저장, 엑셀 다운로드, ②입출금 수기 입력
 * - 행 클릭 → 수기 입력/수정 모달
 * - ③수정 영역 하이라이트, ⑥수정 스티커
 * - 범례: 수기 계좌(🟠) / 연동 계좌(🔵)
 * - 날짜 프리셋: 이번달, 지난달, D-2월~D-5월
 */

import { useState, useMemo, useCallback, useEffect } from 'react';
import { format, startOfMonth, endOfMonth } from 'date-fns';
import {
  Building2, Save, Download, Plus, RefreshCw, Loader2,
} from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Checkbox } from '@/components/ui/checkbox';
import { TableRow, TableCell } from '@/components/ui/table';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { MobileCard } from '@/components/organisms/MobileCard';
import {
  UniversalListPage,
  type UniversalListConfig,
  type SelectionHandlers,
  type RowClickHandlers,
  type StatCard,
} from '@/components/templates/UniversalListPage';
import type { BankTransaction, AccountCategoryFilter, SortOption } from './types';
import {
  TRANSACTION_KIND_LABELS,
  ACCOUNT_CATEGORY_OPTIONS,
  ACCOUNT_CATEGORY_LABELS,
} from './types';
import {
  getBankTransactionList,
  getBankTransactionSummary,
  getBankAccountOptions,
  getFinancialInstitutions,
  batchSaveTransactions,
  type BankTransactionSummaryData,
} from './actions';
import { TransactionFormModal } from './TransactionFormModal';
import { syncBankTransactions } from '@/components/settings/BarobillIntegration/actions';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { formatNumber } from '@/lib/utils/amount';
import { downloadExcel, type ExcelColumn } from '@/lib/utils/excel-download';

// ===== 엑셀 다운로드 컬럼 =====
const excelColumns: ExcelColumn<BankTransaction & Record<string, unknown>>[] = [
  { header: '거래일시', key: 'transactionDate', width: 12 },
  { header: '구분', key: 'type', width: 8,
    transform: (v) => v === 'deposit' ? '입금' : '출금' },
  { header: '은행명', key: 'bankName', width: 12 },
  { header: '계좌명', key: 'accountName', width: 15 },
  { header: '적요/내용', key: 'note', width: 20 },
  { header: '입금', key: 'depositAmount', width: 14 },
  { header: '출금', key: 'withdrawalAmount', width: 14 },
  { header: '잔액', key: 'balance', width: 14 },
  { header: '취급점', key: 'branch', width: 12 },
  { header: '상대계좌예금주명', key: 'depositorName', width: 18 },
];

// ===== 테이블 컬럼 정의 (체크박스 제외 10개) =====
const tableColumns = [
  { key: 'rowNumber', label: 'No.', className: 'text-center w-[50px]' },
  { key: 'transactionDate', label: '거래일시', sortable: true, copyable: true },
  { key: 'type', label: '구분', className: 'text-center', sortable: true, copyable: true },
  { key: 'accountInfo', label: '계좌정보', sortable: true, copyable: true },
  { key: 'note', label: '적요/내용', sortable: true, copyable: true },
  { key: 'depositAmount', label: '입금', className: 'text-right', sortable: true, copyable: true },
  { key: 'withdrawalAmount', label: '출금', className: 'text-right', sortable: true, copyable: true },
  { key: 'balance', label: '잔액', className: 'text-right', sortable: true, copyable: true },
  { key: 'branch', label: '취급점', className: 'text-center', sortable: true, copyable: true },
  { key: 'depositorName', label: '상대계좌예금주명', sortable: true, copyable: true },
];

// ===== 기본 Summary =====
const DEFAULT_SUMMARY: BankTransactionSummaryData = {
  totalDeposit: 0,
  totalWithdrawal: 0,
  totalBalance: 0,
  accountCount: 0,
  unsetCount: 0,
};

export function BankTransactionInquiry() {
  // ===== 데이터 상태 =====
  const [data, setData] = useState<BankTransaction[]>([]);
  const [summary, setSummary] = useState<BankTransactionSummaryData>(DEFAULT_SUMMARY);
  const [pagination, setPagination] = useState({
    currentPage: 1, lastPage: 1, perPage: 20, total: 0,
  });

  // 계좌/금융기관 옵션
  const [accountOptions, setAccountOptions] = useState<{ id: number; label: string }[]>([]);
  const [financialInstitutionOptions, setFinancialInstitutionOptions] = useState<
    { value: string; label: string }[]
  >([{ value: 'all', label: '전체' }]);

  // 필터 상태
  const [searchQuery, setSearchQuery] = useState('');
  const [sortOption] = useState<SortOption>('latest');
  const [accountCategoryFilter, setAccountCategoryFilter] = useState<AccountCategoryFilter>('all');
  const [financialInstitutionFilter, setFinancialInstitutionFilter] = useState('all');
  const [currentPage, setCurrentPage] = useState(1);
  const [isLoading, setIsLoading] = useState(true);

  // 날짜 범위
  const [startDate, setStartDate] = useState(() => format(startOfMonth(new Date()), 'yyyy-MM-dd'));
  const [endDate, setEndDate] = useState(() => format(endOfMonth(new Date()), 'yyyy-MM-dd'));

  // 모달 상태
  const [modalOpen, setModalOpen] = useState(false);
  const [modalMode, setModalMode] = useState<'create' | 'edit'>('create');
  const [selectedTransaction, setSelectedTransaction] = useState<BankTransaction | null>(null);

  // 수정 추적 (로컬 변경사항)
  const [localChanges, setLocalChanges] = useState<Map<string, Partial<BankTransaction>>>(new Map());
  const [isBatchSaving, setIsBatchSaving] = useState(false);
  const [isSyncing, setIsSyncing] = useState(false);

  // ===== 데이터 로드 =====
  const loadData = useCallback(async () => {
    setIsLoading(true);
    try {
      const sortMapping: Record<SortOption, { sortBy: string; sortDir: 'asc' | 'desc' }> = {
        latest: { sortBy: 'transaction_date', sortDir: 'desc' },
        oldest: { sortBy: 'transaction_date', sortDir: 'asc' },
        amountHigh: { sortBy: 'amount', sortDir: 'desc' },
        amountLow: { sortBy: 'amount', sortDir: 'asc' },
      };
      const sortParams = sortMapping[sortOption];

      const [listResult, summaryResult, accountsResult, fiResult] = await Promise.all([
        getBankTransactionList({
          page: currentPage,
          perPage: 20,
          startDate,
          endDate,
          search: searchQuery || undefined,
          sortBy: sortParams.sortBy,
          sortDir: sortParams.sortDir,
          accountCategory: accountCategoryFilter,
          financialInstitution: financialInstitutionFilter,
        }),
        getBankTransactionSummary({ startDate, endDate }),
        getBankAccountOptions(),
        getFinancialInstitutions(),
      ]);

      if (listResult.success) {
        setData(listResult.data);
        setPagination(listResult.pagination);
      }
      if (summaryResult.success && summaryResult.data) {
        setSummary(summaryResult.data);
      }
      if (accountsResult.success) {
        setAccountOptions(accountsResult.data);
      }
      if (fiResult.success) {
        setFinancialInstitutionOptions([
          { value: 'all', label: '전체' },
          ...fiResult.data,
        ]);
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('[BankTransactionInquiry] loadData error:', error);
    } finally {
      setIsLoading(false);
    }
  }, [currentPage, startDate, endDate, searchQuery, sortOption, accountCategoryFilter, financialInstitutionFilter]);

  useEffect(() => {
    loadData();
  }, [loadData]);

  // ===== 핸들러 =====
  const handleRowClick = useCallback((item: BankTransaction) => {
    setSelectedTransaction(item);
    setModalMode('edit');
    setModalOpen(true);
  }, []);

  const handleCreateClick = useCallback(() => {
    setSelectedTransaction(null);
    setModalMode('create');
    setModalOpen(true);
  }, []);

  const handleModalSuccess = useCallback(() => {
    loadData();
  }, [loadData]);

  // ① 저장 버튼 (변경사항 일괄 저장)
  const handleBatchSave = useCallback(async () => {
    if (localChanges.size === 0) {
      toast.info('변경된 내용이 없습니다.');
      return;
    }
    setIsBatchSaving(true);
    try {
      const changes = Array.from(localChanges.entries()).map(([id, data]) => ({
        id,
        data: {
          bankAccountId: data.bankAccountId ?? undefined,
          transactionDate: data.transactionDate,
          type: data.type,
          amount: data.depositAmount || data.withdrawalAmount,
          note: data.note ?? '',
          depositorName: data.depositorName ?? '',
          memo: data.memo ?? '',
          branch: data.branch ?? '',
        },
      }));
      const result = await batchSaveTransactions(changes);
      if (result.success) {
        toast.success('저장이 완료되었습니다.');
        setLocalChanges(new Map());
        loadData();
      } else {
        toast.error(result.error || '저장에 실패했습니다.');
      }
    } catch {
      toast.error('저장 중 오류가 발생했습니다.');
    } finally {
      setIsBatchSaving(false);
    }
  }, [localChanges, loadData]);

  // 바로빌 동기화
  const handleSync = useCallback(async () => {
    setIsSyncing(true);
    try {
      const sd = startDate.replace(/-/g, '');
      const ed = endDate.replace(/-/g, '');
      const result = await syncBankTransactions(sd, ed);
      if (result.success && result.data) {
        toast.success(`은행 거래 ${result.data.synced}건 동기화 완료`);
        loadData();
      } else {
        toast.error(result.error || '동기화에 실패했습니다.');
      }
    } catch {
      toast.error('동기화 중 오류가 발생했습니다.');
    } finally {
      setIsSyncing(false);
    }
  }, [startDate, endDate, loadData]);

  // 엑셀 다운로드 (프론트 xlsx 생성)
  const handleExcelDownload = useCallback(async () => {
    try {
      toast.info('엑셀 파일 생성 중...');
      const allData: BankTransaction[] = [];
      let page = 1;
      let lastPage = 1;

      do {
        const result = await getBankTransactionList({
          startDate,
          endDate,
          accountCategory: accountCategoryFilter,
          financialInstitution: financialInstitutionFilter,
          perPage: 100,
          page,
        });
        if (result.success && result.data.length > 0) {
          allData.push(...result.data);
          lastPage = result.pagination?.lastPage ?? 1;
        } else {
          break;
        }
        page++;
      } while (page <= lastPage);

      if (allData.length > 0) {
        await downloadExcel({
          data: allData as (BankTransaction & Record<string, unknown>)[],
          columns: excelColumns,
          filename: '계좌입출금내역',
          sheetName: '입출금내역',
        });
        toast.success('엑셀 다운로드 완료');
      } else {
        toast.warning('다운로드할 데이터가 없습니다.');
      }
    } catch {
      toast.error('엑셀 다운로드에 실패했습니다.');
    }
  }, [startDate, endDate, accountCategoryFilter, financialInstitutionFilter]);

  // ===== 합계 계산 =====
  const tableTotals = useMemo(() => {
    const totalDeposit = data.reduce((sum, item) => sum + item.depositAmount, 0);
    const totalWithdrawal = data.reduce((sum, item) => sum + item.withdrawalAmount, 0);
    return { totalDeposit, totalWithdrawal };
  }, [data]);

  // 행이 수정되었는지 확인
  const isRowModified = useCallback(
    (id: string) => localChanges.has(id) || false,
    [localChanges]
  );

  // 셀이 수정되었는지 확인 (서버에서 온 modifiedFields)
  const isCellModified = useCallback(
    (item: BankTransaction, field: string) => {
      return item.modifiedFields?.includes(field) || false;
    },
    []
  );

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<BankTransaction> = useMemo(
    () => ({
      title: '계좌 입출금 내역',
      description: '은행 계좌의 입출금 내역을 조회하고 관리합니다',
      icon: Building2,
      basePath: '/accounting/bank-transactions',
      idField: 'id',

      actions: {
        getList: async () => ({
          success: true,
          data,
          totalCount: pagination.total,
        }),
      },

      columns: tableColumns,
      clientSideFiltering: false,
      itemsPerPage: 20,
      showCheckbox: true,
      showRowNumber: true,

      // 검색
      searchPlaceholder: '계좌명, 적요, 예금주명 검색...',
      onSearchChange: setSearchQuery,
      searchFilter: (item: BankTransaction, search: string) => {
        const s = search.toLowerCase();
        return (
          item.accountName?.toLowerCase().includes(s) ||
          item.note?.toLowerCase().includes(s) ||
          item.depositorName?.toLowerCase().includes(s) ||
          false
        );
      },

      // 날짜 선택기 (이번달~D-5월 프리셋)
      dateRangeSelector: {
        enabled: true,
        showPresets: true,
        presets: ['thisMonth', 'lastMonth', 'twoMonthsAgo', 'threeMonthsAgo', 'fourMonthsAgo', 'fiveMonthsAgo'],
        presetLabels: {
          thisMonth: '이번달',
          lastMonth: '지난달',
          twoMonthsAgo: 'D-2월',
          threeMonthsAgo: 'D-3월',
          fourMonthsAgo: 'D-4월',
          fiveMonthsAgo: 'D-5월',
        },
        startDate,
        endDate,
        onStartDateChange: setStartDate,
        onEndDateChange: setEndDate,
      },

      // 헤더 액션: 동기화 + ①저장 + 엑셀 다운로드 + ②수기 입력
      headerActions: () => (
        <div className="flex items-center gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={handleSync}
            disabled={isSyncing}
          >
            {isSyncing ? (
              <Loader2 className="h-4 w-4 mr-1 animate-spin" />
            ) : (
              <RefreshCw className="h-4 w-4 mr-1" />
            )}
            {isSyncing ? '동기화 중...' : '동기화'}
          </Button>
          <Button
            size="sm"
            onClick={handleBatchSave}
            disabled={isBatchSaving || localChanges.size === 0}
            className="bg-orange-500 hover:bg-orange-600 text-white"
          >
            {isBatchSaving ? (
              <Loader2 className="h-4 w-4 mr-1 animate-spin" />
            ) : (
              <Save className="h-4 w-4 mr-1" />
            )}
            저장
          </Button>
          <Button variant="outline" size="sm" onClick={handleExcelDownload}>
            <Download className="h-4 w-4 mr-1" />
            엑셀 다운로드
          </Button>
          <Button size="sm" onClick={handleCreateClick}>
            <Plus className="h-4 w-4 mr-1" />
            입출금 수기 입력
          </Button>
        </div>
      ),

      // 테이블 헤더 액션: 총 N건 + ④구분 + ⑤금융기관
      tableHeaderActions: () => (
        <div className="flex items-center gap-2 flex-wrap">
          <span className="text-sm text-muted-foreground whitespace-nowrap">
            총 {pagination.total}건
          </span>
          <Button
            variant="ghost"
            size="icon"
            className="h-8 w-8"
            onClick={() => loadData()}
            disabled={isLoading}
          >
            {isLoading ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <RefreshCw className="h-4 w-4" />
            )}
          </Button>

          {/* ④ 구분 */}
          <Select
            value={accountCategoryFilter}
            onValueChange={(v) => setAccountCategoryFilter(v as AccountCategoryFilter)}
          >
            <SelectTrigger className="min-w-[120px] w-auto">
              <SelectValue placeholder="구분" />
            </SelectTrigger>
            <SelectContent>
              {ACCOUNT_CATEGORY_OPTIONS.map((opt) => (
                <SelectItem key={opt.value} value={opt.value}>
                  {opt.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>

          {/* ⑤ 금융기관 */}
          <Select
            value={financialInstitutionFilter}
            onValueChange={setFinancialInstitutionFilter}
          >
            <SelectTrigger className="min-w-[140px] w-auto">
              <SelectValue placeholder="금융기관" />
            </SelectTrigger>
            <SelectContent>
              {financialInstitutionOptions.map((opt) => (
                <SelectItem key={opt.value} value={opt.value}>
                  {opt.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      ),

      // 합계 행 + 범례 (체크박스+No.+9데이터 = 12컬럼)
      tableFooter: (
        <>
          <TableRow className="bg-muted/50 font-medium">
            <TableCell />
            <TableCell colSpan={5} className="text-right font-bold">합계</TableCell>
            <TableCell className="text-right font-bold text-blue-600">
              {formatNumber(tableTotals.totalDeposit)}
            </TableCell>
            <TableCell className="text-right font-bold text-red-600">
              {formatNumber(tableTotals.totalWithdrawal)}
            </TableCell>
            <TableCell />
            <TableCell />
            <TableCell />
          </TableRow>
          <TableRow>
            <TableCell colSpan={12} className="py-2">
              <div className="flex items-center gap-4 text-xs text-muted-foreground">
                <span className="flex items-center gap-1.5">
                  <span className="inline-block w-2.5 h-2.5 rounded-full bg-orange-400" />
                  수기 계좌
                </span>
                <span className="flex items-center gap-1.5">
                  <span className="inline-block w-2.5 h-2.5 rounded-full bg-blue-400" />
                  연동 계좌
                </span>
              </div>
            </TableCell>
          </TableRow>
        </>
      ),

      // 통계 카드 5개
      computeStats: (): StatCard[] => [
        {
          label: '입금',
          value: `${formatNumber(summary.totalDeposit)}원`,
          icon: Building2,
          iconColor: 'text-blue-500',
        },
        {
          label: '출금',
          value: `${formatNumber(summary.totalWithdrawal)}원`,
          icon: Building2,
          iconColor: 'text-red-500',
        },
        {
          label: '잔고',
          value: `${formatNumber(summary.totalBalance)}원`,
          icon: Building2,
          iconColor: 'text-green-500',
        },
        {
          label: '계좌',
          value: `${summary.accountCount}개`,
          icon: Building2,
          iconColor: 'text-gray-500',
        },
        {
          label: '거래',
          value: `${pagination.total}건`,
          icon: Building2,
          iconColor: 'text-orange-500',
        },
      ],

      // 테이블 행 렌더링
      renderTableRow: (
        item: BankTransaction,
        _index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<BankTransaction>
      ) => {
        const rowModified = isRowModified(item.id);

        return (
          <TableRow
            key={item.id}
            className={`cursor-pointer hover:bg-muted/50 ${rowModified ? 'bg-green-50' : ''}`}
            onClick={() => handleRowClick(item)}
          >
            {/* 체크박스 */}
            <TableCell className="text-center w-[40px]" onClick={(e) => e.stopPropagation()}>
              <Checkbox
                checked={handlers.isSelected}
                onCheckedChange={() => handlers.onToggle()}
              />
            </TableCell>
            {/* No. */}
            <TableCell className="text-center">{globalIndex}</TableCell>
            {/* 거래일시 */}
            <TableCell>
              <span className={isCellModified(item, 'transaction_date') ? 'bg-green-100 px-1 rounded' : ''}>
                {item.transactionDate}
                {item.transactionTime && (
                  <span className="text-xs text-gray-400 ml-1">{item.transactionTime}</span>
                )}
              </span>
            </TableCell>
            {/* 구분 (계좌 카테고리) */}
            <TableCell className="text-center text-sm">
              {item.accountCategory
                ? ACCOUNT_CATEGORY_LABELS[item.accountCategory]
                : '은행계좌'}
            </TableCell>
            {/* 계좌정보 (수기: 🟠, 연동: 🔵) - 은행명 + 마스킹 계좌번호 */}
            <TableCell>
              <div className="flex items-center gap-1.5">
                <span
                  className={`inline-block w-2.5 h-2.5 rounded-full shrink-0 ${
                    item.isManual ? 'bg-orange-400' : 'bg-blue-400'
                  }`}
                />
                <span className="text-sm truncate">
                  {item.bankName || item.accountName}
                  {item.accountNumber && (
                    <span className="text-muted-foreground ml-1">
                      ****{item.accountNumber.slice(-4)}
                    </span>
                  )}
                </span>
              </div>
            </TableCell>
            {/* 적요/내용 (수정 하이라이트) */}
            <TableCell>
              <div className="flex items-center gap-1">
                <span className={isCellModified(item, 'note') ? 'bg-green-100 px-1 rounded' : ''}>
                  {item.note || '-'}
                </span>
                {isCellModified(item, 'note') && (
                  <Badge variant="outline" className="bg-green-50 text-green-700 border-green-300 text-[10px] px-1 py-0">
                    수정
                  </Badge>
                )}
              </div>
            </TableCell>
            {/* 입금 */}
            <TableCell className={`text-right font-medium text-blue-600 ${isCellModified(item, 'deposit_amount') ? 'bg-green-100 rounded' : ''}`}>
              {item.depositAmount > 0 ? formatNumber(item.depositAmount) : '-'}
            </TableCell>
            {/* 출금 */}
            <TableCell className={`text-right font-medium text-red-600 ${isCellModified(item, 'withdrawal_amount') ? 'bg-green-100 rounded' : ''}`}>
              {item.withdrawalAmount > 0 ? formatNumber(item.withdrawalAmount) : '-'}
            </TableCell>
            {/* 잔액 */}
            <TableCell className="text-right font-medium">
              {formatNumber(item.balance)}
            </TableCell>
            {/* 취급점 */}
            <TableCell className="text-center text-sm text-muted-foreground">
              {item.branch || '-'}
            </TableCell>
            {/* 상대계좌예금주명 */}
            <TableCell className="text-sm">
              {item.depositorName || '-'}
            </TableCell>
          </TableRow>
        );
      },

      // 모바일 카드 렌더링
      renderMobileCard: (
        item: BankTransaction,
        _index: number,
        _globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<BankTransaction>
      ) => {
        return (
          <MobileCard
            key={item.id}
            title={`${item.bankName || item.accountName}${item.accountNumber ? ` ****${item.accountNumber.slice(-4)}` : ''}`}
            subtitle={item.transactionDate}
            badge={TRANSACTION_KIND_LABELS[item.type]}
            badgeVariant="outline"
            badgeClassName={
              item.type === 'deposit'
                ? 'border-blue-300 text-blue-600 bg-blue-50'
                : 'border-red-300 text-red-600 bg-red-50'
            }
            isSelected={handlers.isSelected}
            onToggle={handlers.onToggle}
            onClick={() => handleRowClick(item)}
            details={[
              { label: '적요', value: item.note || '-' },
              {
                label: '입금',
                value: item.depositAmount > 0 ? `${formatNumber(item.depositAmount)}원` : '-',
              },
              {
                label: '출금',
                value: item.withdrawalAmount > 0 ? `${formatNumber(item.withdrawalAmount)}원` : '-',
              },
              { label: '잔액', value: `${formatNumber(item.balance)}원` },
              { label: '취급점', value: item.branch || '-' },
              { label: '예금주', value: item.depositorName || '-' },
            ]}
          />
        );
      },
    }),
    [
      data,
      pagination,
      summary,
      accountCategoryFilter,
      financialInstitutionFilter,
      financialInstitutionOptions,
      sortOption,
      startDate,
      endDate,
      tableTotals,
      isLoading,
      isBatchSaving,
      localChanges,
      handleBatchSave,
      handleExcelDownload,
      handleCreateClick,
      handleRowClick,
      handleSync,
      isRowModified,
      isCellModified,
      isSyncing,
      loadData,
    ]
  );

  return (
    <>
      <UniversalListPage
        config={config}
        initialData={data}
        externalPagination={{
          currentPage,
          totalPages: pagination.lastPage,
          totalItems: pagination.total,
          itemsPerPage: 20,
          onPageChange: setCurrentPage,
        }}
        externalIsLoading={isLoading}
      />

      {/* 수기 입력/수정 모달 */}
      <TransactionFormModal
        open={modalOpen}
        onOpenChange={setModalOpen}
        mode={modalMode}
        transaction={selectedTransaction}
        accountOptions={accountOptions}
        onSuccess={handleModalSuccess}
      />
    </>
  );
}
