
import React, { useState } from 'react';
import { Transaction } from './TransactionCard';
import TransactionEditDialog from './TransactionEditDialog';
import { ChevronRight } from 'lucide-react';
import { useBudget } from '@/contexts/BudgetContext';
import { Link } from 'react-router-dom';

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

const RecentTransactionsSection: React.FC<RecentTransactionsSectionProps> = ({ 
  transactions,
  onUpdateTransaction 
}) => {
  const [selectedTransaction, setSelectedTransaction] = useState<Transaction | null>(null);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const { updateTransaction, deleteTransaction } = useBudget();

  const handleTransactionClick = (transaction: Transaction) => {
    setSelectedTransaction(transaction);
    setIsDialogOpen(true);
  };

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

  const handleDeleteTransaction = (id: string) => {
    // 직접 컨텍스트를 통해 삭제
    deleteTransaction(id);
  };

  const formatCurrency = (amount: number) => {
    return amount.toLocaleString('ko-KR') + '원';
  };

  const getCategoryIcon = (category: string) => {
    switch (category) {
      case '식비':
        return '🍽️';
      case '교통비':
        return '🚗';
      case '생활비':
        return '🏠';
      case '쇼핑':
        return '🛍️';
      case '의료':
        return '💊';
      case '여가':
        return '🎮';
      case '교육':
        return '📚';
      default:
        return '💰';
    }
  };

  return (
    <div className="mt-6">
      <div className="flex justify-between items-center mb-3">
        <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) => (
            <div 
              key={transaction.id} 
              className="flex justify-between py-3 px-4 cursor-pointer hover:bg-gray-50" 
              onClick={() => handleTransactionClick(transaction)}
            >
              <div className="flex items-center">
                <span className="text-xl mr-3">{getCategoryIcon(transaction.category)}</span>
                <div>
                  <h3 className="font-medium">{transaction.title}</h3>
                  <p className="text-xs text-gray-500">{transaction.date}</p>
                </div>
              </div>
              <div className="text-right">
                <p className="font-semibold text-red-500">-{formatCurrency(transaction.amount)}</p>
                <p className="text-xs text-gray-500">{transaction.category}</p>
              </div>
            </div>
          ))
        ) : (
          <div className="py-4 text-center text-gray-500">
            지출 내역이 없습니다
          </div>
        )}
      </div>

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

export default RecentTransactionsSection;
