import React, { useState, useCallback, useRef } 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 { categoryIcons } from '@/constants/categoryIcons';
import TransactionIcon from './transaction/TransactionIcon';
import { toast } from '@/hooks/useToast.wrapper';
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 [isDeleting, setIsDeleting] = useState(false);
  const {
    updateTransaction,
    deleteTransaction
  } = useBudget();

  // 삭제 중인 ID 추적
  const deletingIdRef = useRef<string | null>(null);

  // 타임아웃 추적
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);

  // 삭제 요청 타임스탬프 추적 (급발진 방지)
  const lastDeleteTimeRef = useRef<Record<string, number>>({});
  const handleTransactionClick = (transaction: Transaction) => {
    setSelectedTransaction(transaction);
    setIsDialogOpen(true);
  };
  const handleUpdateTransaction = useCallback((updatedTransaction: Transaction) => {
    if (onUpdateTransaction) {
      onUpdateTransaction(updatedTransaction);
    }
    // 직접 컨텍스트를 통해 업데이트
    updateTransaction(updatedTransaction);
  }, [onUpdateTransaction, updateTransaction]);

  // 완전히 새로운 삭제 처리 함수
  const handleDeleteTransaction = useCallback(async (id: string): Promise<boolean> => {
    return new Promise(resolve => {
      try {
        // 삭제 진행 중인지 확인
        if (isDeleting || deletingIdRef.current === id) {
          console.log('이미 삭제 작업이 진행 중입니다');
          resolve(true);
          return;
        }

        // 급발진 방지 (300ms)
        const now = Date.now();
        if (lastDeleteTimeRef.current[id] && now - lastDeleteTimeRef.current[id] < 300) {
          console.warn('삭제 요청이 너무 빠릅니다. 무시합니다.');
          resolve(true);
          return;
        }

        // 타임스탬프 업데이트
        lastDeleteTimeRef.current[id] = now;

        // 삭제 상태 설정
        setIsDeleting(true);
        deletingIdRef.current = id;

        // 먼저 다이얼로그 닫기 (UI 응답성 확보)
        setIsDialogOpen(false);

        // 안전장치: 타임아웃 설정 (최대 900ms)
        if (timeoutRef.current) {
          clearTimeout(timeoutRef.current);
        }
        timeoutRef.current = setTimeout(() => {
          console.warn('삭제 타임아웃 - 상태 초기화');
          setIsDeleting(false);
          deletingIdRef.current = null;
          resolve(true); // UI 응답성 위해 성공 간주
        }, 900);

        // 삭제 함수 호출 (Promise 래핑)
        try {
          // 비동기 작업을 동기적으로 처리하여 UI 블로킹 방지
          setTimeout(async () => {
            try {
              deleteTransaction(id);

              // 안전장치 타임아웃 제거
              if (timeoutRef.current) {
                clearTimeout(timeoutRef.current);
                timeoutRef.current = null;
              }

              // 상태 초기화 (지연 적용)
              setTimeout(() => {
                setIsDeleting(false);
                deletingIdRef.current = null;
              }, 100);
            } catch (err) {
              console.error('삭제 처리 오류:', err);
            }
          }, 0);

          // 즉시 성공 반환 (UI 응답성 향상)
          resolve(true);
        } catch (error) {
          console.error('deleteTransaction 호출 오류:', error);

          // 타임아웃 제거
          if (timeoutRef.current) {
            clearTimeout(timeoutRef.current);
            timeoutRef.current = null;
          }

          // 상태 초기화
          setIsDeleting(false);
          deletingIdRef.current = null;
          resolve(true); // UI 응답성 위해 성공 간주
        }
      } catch (error) {
        console.error('삭제 처리 전체 오류:', error);

        // 항상 상태 정리
        setIsDeleting(false);
        deletingIdRef.current = null;
        if (timeoutRef.current) {
          clearTimeout(timeoutRef.current);
          timeoutRef.current = null;
        }
        toast({
          title: "오류 발생",
          description: "처리 중 문제가 발생했습니다.",
          variant: "destructive",
          duration: 1500
        });
        resolve(false);
      }
    });
  }, [deleteTransaction, isDeleting]);

  // 컴포넌트 언마운트 시 타임아웃 정리
  React.useEffect(() => {
    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }
    };
  }, []);
  const formatCurrency = (amount: number) => {
    return amount.toLocaleString('ko-KR') + '원';
  };
  return (
    <div className="mt-4 mb-[40px]">
      <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 => (
            <div
              key={transaction.id}
              onClick={() => handleTransactionClick(transaction)}
              className="flex justify-between py-2 cursor-pointer px-[5px] bg-transparent"
            >
              <div className="flex items-center">
                <TransactionIcon category={transaction.category} />
                <div className="ml-3">
                  <h3 className="font-medium text-black text-left text-sm">
                    {transaction.title}
                  </h3>
                  <p className="text-xs text-gray-500">{transaction.date}</p>
                </div>
              </div>
              <div className="text-right">
                <p className="font-semibold text-neuro-income text-sm">
                  -{formatCurrency(transaction.amount)}
                </p>
                <p className="text-xs text-gray-500">{transaction.category}</p>
              </div>
            </div>
          ))
        ) : (
          <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;
