import React from 'react';
import { Transaction } from '@/contexts/budget/types';
import TransactionEditDialog from './TransactionEditDialog';
import { ChevronRight } from 'lucide-react';
import { useBudget } from '@/contexts/budget/BudgetContext';
import { Link } from 'react-router-dom';
import { useRecentTransactions } from '@/hooks/transactions/useRecentTransactions';
import { useRecentTransactionsDialog } from '@/hooks/transactions/useRecentTransactionsDialog';
import RecentTransactionItem from './recent-transactions/RecentTransactionItem';

interface RecentTransactionsSectionProps {
  transactions: Transaction[];
  onUpdateTransaction?: (transaction: Transaction) => void;
}

const RecentTransactionsSection: React.FC<RecentTransactionsSectionProps> = ({
  transactions,
  onUpdateTransaction
}) => {
  const { updateTransaction, deleteTransaction } = useBudget();
  
  // 트랜잭션 삭제 관련 로직은 커스텀 훅으로 분리
  const { handleDeleteTransaction, isDeleting } = useRecentTransactions(deleteTransaction);
  
  // 다이얼로그 관련 로직 분리
  const { 
    selectedTransaction, 
    isDialogOpen, 
    handleTransactionClick, 
    setIsDialogOpen 
  } = useRecentTransactionsDialog();

  const handleUpdateTransaction = (updatedTransaction: Transaction) => {
    if (onUpdateTransaction) {
      onUpdateTransaction(updatedTransaction);
    }
    // 직접 컨텍스트를 통해 업데이트
    updateTransaction(updatedTransaction);
  };

  return (
    <div className="mt-4 mb-[50px]">
      <div className="flex justify-between items-center mb-2">
        <h2 className="text-lg font-semibold">최근 지출</h2>
        <Link to="/transactions" className="text-sm text-neuro-income flex items-center">
          더보기 <ChevronRight size={16} />
        </Link>
      </div>
      
      <div className="neuro-card divide-y divide-gray-100 w-full">
        {transactions.length > 0 ? (
          transactions.map(transaction => (
            <RecentTransactionItem
              key={transaction.id}
              transaction={transaction}
              onClick={() => handleTransactionClick(transaction)}
            />
          ))
        ) : (
          <div className="py-3 text-center text-gray-500">
            지출 내역이 없습니다
          </div>
        )}
      </div>

      {selectedTransaction && (
        <TransactionEditDialog
          transaction={selectedTransaction}
          open={isDialogOpen}
          onOpenChange={setIsDialogOpen}
          onSave={handleUpdateTransaction}
          onDelete={handleDeleteTransaction}
        />
      )}
    </div>
  );
};

export default RecentTransactionsSection;
