import { useCallback, useEffect, useState } from 'react';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { CreateTradeScreen } from '../../../src/screens/trade/CreateTradeScreen';
import { tradeService } from '../../../src/services/trade/tradeService';
import { Loading } from '../../../src/components/common';
import { View, Alert } from 'react-native';
import type { TradeItemDetailDTO } from '../../../src/types/trade';

export default function EditTradeRoute() {
  const { tradeId } = useLocalSearchParams<{ tradeId: string }>();
  const router = useRouter();
  const [item, setItem] = useState<TradeItemDetailDTO | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!tradeId) return;
    tradeService.getTradeItem(tradeId)
      .then(data => setItem(data))
      .catch(() => Alert.alert('错误', '加载商品信息失败'))
      .finally(() => setLoading(false));
  }, [tradeId]);

  const handleClose = useCallback(() => {
    router.back();
  }, [router]);

  const handleSuccess = useCallback(() => {
    router.back();
  }, [router]);

  if (loading) {
    return <Loading fullScreen />;
  }

  if (!item) {
    return null;
  }

  return (
    <CreateTradeScreen
      onClose={handleClose}
      onSuccess={handleSuccess}
      editItem={item}
    />
  );
}
