import React, { useState, useEffect, useCallback } from 'react' import { useAuth } from './auth/AuthContext' import LoadingError from './LoadingError' import Toast from './Toast' import './WishlistDetail.css' const API_URL = '/api/wishlist' function WishlistDetail({ wishlistId, onNavigate, onRefresh }) { const { authFetch } = useAuth() const [wishlistItem, setWishlistItem] = useState(null) const [loading, setLoading] = useState(true) const [loadingWishlist, setLoadingWishlist] = useState(true) const [error, setError] = useState(null) const [isCompleting, setIsCompleting] = useState(false) const [isDeleting, setIsDeleting] = useState(false) const [toastMessage, setToastMessage] = useState(null) const fetchWishlistDetail = useCallback(async () => { try { setLoadingWishlist(true) setLoading(true) setError(null) const response = await authFetch(`${API_URL}/${wishlistId}`) if (!response.ok) { throw new Error('Ошибка загрузки желания') } const data = await response.json() setWishlistItem(data) } catch (err) { setError(err.message) console.error('Error fetching wishlist detail:', err) } finally { setLoading(false) setLoadingWishlist(false) } }, [wishlistId, authFetch]) useEffect(() => { if (wishlistId) { fetchWishlistDetail() } else { setWishlistItem(null) setLoading(true) setLoadingWishlist(true) setError(null) } }, [wishlistId, fetchWishlistDetail]) const handleEdit = () => { onNavigate?.('wishlist-form', { wishlistId: wishlistId }) } const handleComplete = async () => { if (!wishlistItem || !wishlistItem.unlocked) return setIsCompleting(true) try { const response = await authFetch(`${API_URL}/${wishlistId}/complete`, { method: 'POST', }) if (!response.ok) { throw new Error('Ошибка при завершении') } if (onRefresh) { onRefresh() } if (onNavigate) { onNavigate('wishlist') } } catch (err) { console.error('Error completing wishlist:', err) setToastMessage({ text: err.message || 'Ошибка при завершении', type: 'error' }) } finally { setIsCompleting(false) } } const handleUncomplete = async () => { if (!wishlistItem || !wishlistItem.completed) return setIsCompleting(true) try { const response = await authFetch(`${API_URL}/${wishlistId}/uncomplete`, { method: 'POST', }) if (!response.ok) { throw new Error('Ошибка при отмене завершения') } if (onRefresh) { onRefresh() } fetchWishlistDetail() } catch (err) { console.error('Error uncompleting wishlist:', err) setToastMessage({ text: err.message || 'Ошибка при отмене завершения', type: 'error' }) } finally { setIsCompleting(false) } } const handleDelete = async () => { if (!wishlistItem) return if (!window.confirm('Вы уверены, что хотите удалить это желание?')) { return } setIsDeleting(true) try { const response = await authFetch(`${API_URL}/${wishlistId}`, { method: 'DELETE', }) if (!response.ok) { throw new Error('Ошибка при удалении') } if (onRefresh) { onRefresh() } if (onNavigate) { onNavigate('wishlist') } } catch (err) { console.error('Error deleting wishlist:', err) setToastMessage({ text: err.message || 'Ошибка при удалении', type: 'error' }) } finally { setIsDeleting(false) } } const formatPrice = (price) => { return new Intl.NumberFormat('ru-RU', { style: 'currency', currency: 'RUB', minimumFractionDigits: 0, maximumFractionDigits: 0, }).format(price) } const renderUnlockConditions = () => { if (!wishlistItem || !wishlistItem.unlock_conditions || wishlistItem.unlock_conditions.length === 0) { return null } return (

Условия разблокировки:

{wishlistItem.unlock_conditions.map((condition, index) => { let conditionText = '' let progress = null if (condition.type === 'task_completion') { conditionText = condition.task_name || 'Задача' const isCompleted = condition.task_completed === true progress = { type: 'task', completed: isCompleted } } else { const requiredPoints = condition.required_points || 0 const currentPoints = condition.current_points || 0 const project = condition.project_name || 'Проект' let period = '' if (condition.period_type) { const periodLabels = { week: 'за неделю', month: 'за месяц', year: 'за год', } period = ' ' + periodLabels[condition.period_type] || '' } conditionText = `${requiredPoints} в ${project}${period}` progress = { type: 'points', current: currentPoints, required: requiredPoints, percentage: requiredPoints > 0 ? Math.min(100, (currentPoints / requiredPoints) * 100) : 0 } } const isMet = wishlistItem.unlocked || (progress?.type === 'task' && progress.completed) || (progress?.type === 'points' && progress.current >= progress.required) return (
{isMet ? ( ) : ( )} {conditionText}
{progress && progress.type === 'points' && !isMet && (
{Math.round(progress.current)} / {Math.round(progress.required)}
)}
) })}
) } if (loadingWishlist) { return (
Загрузка...
) } return (

{wishlistItem ? wishlistItem.name : 'Желание'}

{error && ( )} {!error && wishlistItem && ( <> {/* Изображение */} {wishlistItem.image_url && (
{wishlistItem.name}
)} {/* Цена */} {wishlistItem.price && (
{formatPrice(wishlistItem.price)}
)} {/* Ссылка */} {wishlistItem.link && (
Открыть ссылку
)} {/* Условия разблокировки */} {renderUnlockConditions()} {/* Кнопка завершения */} {wishlistItem.unlocked && !wishlistItem.completed && (
)} )}
{toastMessage && ( setToastMessage(null)} /> )}
) } export default WishlistDetail