
import React, { useEffect, useState, useRef, useCallback } from 'react';
import NavBar from '@/components/NavBar';
import AddTransactionButton from '@/components/AddTransactionButton';
import { useBudget } from '@/contexts/BudgetContext';
import { useTransactions } from '@/hooks/transactions';
import TransactionsHeader from '@/components/transactions/TransactionsHeader';
import TransactionsContent from '@/components/transactions/TransactionsContent';
import { Transaction } from '@/components/TransactionCard';
import { toast } from '@/hooks/useToast.wrapper';

const Transactions = () => {
  const { 
    transactions, 
    isLoading, 
    selectedMonth, 
    searchQuery,
    setSearchQuery,
    handlePrevMonth,
    handleNextMonth,
    refreshTransactions,
    totalExpenses,
    deleteTransaction
  } = useTransactions();

  const { budgetData } = useBudget();
  const [isProcessing, setIsProcessing] = useState(false);
  const processingTimeoutRef = useRef<NodeJS.Timeout | null>(null);

  // 삭제 핸들러 - 단순화된 버전
  const handleTransactionDelete = useCallback(async (id: string): Promise<boolean> => {
    if (isProcessing) {
      console.log('이미 삭제 작업이 진행 중입니다');
      return false;
    }

    try {
      setIsProcessing(true);
      
      // 타임아웃 설정
      processingTimeoutRef.current = setTimeout(() => {
        setIsProcessing(false);
      }, 2000);

      const result = await deleteTransaction(id);
      
      // 삭제 후 데이터 새로고침
      if (result) {
        setTimeout(() => {
          refreshTransactions();
        }, 500);
      }

      return result;
    } finally {
      if (processingTimeoutRef.current) {
        clearTimeout(processingTimeoutRef.current);
      }
      setIsProcessing(false);
    }
  }, [isProcessing, deleteTransaction, refreshTransactions]);

  // 컴포넌트 언마운트 시 타임아웃 정리
  useEffect(() => {
    return () => {
      if (processingTimeoutRef.current) {
        clearTimeout(processingTimeoutRef.current);
      }
    };
  }, []);

  // 트랜잭션을 날짜별로 그룹화
  const groupTransactionsByDate = useCallback((transactions: Transaction[]): Record<string, Transaction[]> => {
    const grouped: Record<string, Transaction[]> = {};
    
    transactions.forEach(transaction => {
      if (!transaction.date) return;
      
      const datePart = transaction.date.split(',')[0];
      if (!grouped[datePart]) {
        grouped[datePart] = [];
      }
      grouped[datePart].push(transaction);
    });
    
    return grouped;
  }, []);

  const isDisabled = isLoading || isProcessing;
  const groupedTransactions = groupTransactionsByDate(transactions);

  return (
    <div className="min-h-screen bg-neuro-background pb-24">
      <div className="max-w-md mx-auto px-6">
        <TransactionsHeader 
          selectedMonth={selectedMonth}
          searchQuery={searchQuery}
          setSearchQuery={setSearchQuery}
          handlePrevMonth={handlePrevMonth}
          handleNextMonth={handleNextMonth}
          budgetData={budgetData}
          totalExpenses={totalExpenses}
          isDisabled={isDisabled}
        />
        
        <TransactionsContent 
          isLoading={isLoading}
          isProcessing={isProcessing}
          transactions={transactions}
          groupedTransactions={groupedTransactions}
          searchQuery={searchQuery}
          selectedMonth={selectedMonth}
          setSearchQuery={setSearchQuery}
          onTransactionDelete={handleTransactionDelete}
          isDisabled={isDisabled}
        />
      </div>

      <AddTransactionButton />
      <NavBar />
    </div>
  );
};

export default Transactions;
