'use client' import { useState, useEffect } from 'react' import { useQuery } from '@apollo/client' import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Badge } from '@/components/ui/badge' import { Tabs, TabsContent, TabsList, TabsTrigger, } from '@/components/ui/tabs' import { Package, Search, Loader2, AlertCircle, Eye, Filter, Grid, List } from 'lucide-react' import { GET_PARTSINDEX_CATALOG_ENTITIES, GET_PARTSAPI_ARTICLES, GET_CATEGORY_PRODUCTS } from '@/lib/graphql/queries' interface PartsIndexCategory { id: string name: string image?: string groups?: Array<{ id: string name: string image?: string subgroups?: Array<{ id: string name: string image?: string entityNames?: Array<{ id: string name: string }> }> entityNames?: Array<{ id: string name: string }> }> } interface PartsAPICategory { id: string name: string level: number parentId?: string children?: PartsAPICategory[] } interface KrajaCategoryItemsProps { category: PartsIndexCategory | PartsAPICategory group?: any categoryType: 'partsindex' | 'partsapi' isViewingSavedData?: boolean } interface PartsIndexEntity { id: string name: string image?: string brand?: string description?: string price?: number } interface PartsAPIArticle { supBrand: string supId: number productGroup: string ptId: number artSupBrand: string artArticleNr: string artId: string } export const KrajaCategoryItems = ({ category, group, categoryType, isViewingSavedData = false }: KrajaCategoryItemsProps) => { const [searchQuery, setSearchQuery] = useState('') const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid') const [currentPage, setCurrentPage] = useState(1) const itemsPerPage = isViewingSavedData ? 100 : 20 // Для PartsIndex const { data: partsIndexData, loading: partsIndexLoading, error: partsIndexError, refetch: refetchPartsIndex } = useQuery(GET_PARTSINDEX_CATALOG_ENTITIES, { variables: { catalogId: categoryType === 'partsindex' ? category.id : undefined, groupId: group?.id || undefined, lang: 'ru', limit: itemsPerPage, page: currentPage, q: searchQuery || undefined }, skip: categoryType !== 'partsindex' || !category.id, errorPolicy: 'all' }) // Для PartsAPI - используем strId (нужно преобразовать id в число) const { data: partsAPIData, loading: partsAPILoading, error: partsAPIError, refetch: refetchPartsAPI } = useQuery(GET_PARTSAPI_ARTICLES, { variables: { strId: categoryType === 'partsapi' ? parseInt(category.id) : undefined, carId: 9877, carType: 'PC' }, skip: categoryType !== 'partsapi' || !category.id || isViewingSavedData, errorPolicy: 'all' }) // Для просмотра сохраненных данных const { data: savedData, loading: savedLoading, error: savedError, refetch: refetchSaved } = useQuery(GET_CATEGORY_PRODUCTS, { variables: { categoryId: category.id, categoryType: categoryType.toUpperCase(), search: searchQuery || undefined, limit: itemsPerPage, offset: (currentPage - 1) * itemsPerPage }, skip: !isViewingSavedData, errorPolicy: 'all' }) // Обновляем поиск с задержкой useEffect(() => { const timeoutId = setTimeout(() => { if (isViewingSavedData) { refetchSaved() } else if (categoryType === 'partsindex') { refetchPartsIndex() } else { refetchPartsAPI() } }, 500) return () => clearTimeout(timeoutId) }, [searchQuery, categoryType, isViewingSavedData, refetchPartsIndex, refetchPartsAPI, refetchSaved]) const isLoading = isViewingSavedData ? savedLoading : (categoryType === 'partsindex' ? partsIndexLoading : partsAPILoading) const error = isViewingSavedData ? savedError : (categoryType === 'partsindex' ? partsIndexError : partsAPIError) const items = isViewingSavedData ? savedData?.getCategoryProducts?.products || [] : (categoryType === 'partsindex' ? partsIndexData?.partsIndexCatalogEntities?.list || [] : partsAPIData?.partsAPIArticles || []) const renderPartsIndexItem = (item: PartsIndexEntity) => ( {viewMode === 'grid' ? (
{item.image ? ( {item.name} ) : ( )}

{item.name}

{item.brand && ( {item.brand} )}
{item.description && (

{item.description}

)} {item.price && (
{item.price.toLocaleString('ru-RU')} ₽
)}
) : (
{item.image ? ( {item.name} ) : ( )}

{item.name}

{item.brand && ( {item.brand} )} {item.price && ( {item.price.toLocaleString('ru-RU')} ₽ )}
)}
) const renderSavedItem = (item: any) => ( {viewMode === 'grid' ? (
{item.image_url ? ( {item.name} ) : ( )}

{item.name}

{item.brand && ( {item.brand} )}
{item.description && (

{item.description}

)} {item.price && (
{parseFloat(item.price).toLocaleString('ru-RU')} ₽
)}
Сохранено: {new Date(item.created_at).toLocaleDateString('ru-RU')}
) : (
{item.image_url ? ( {item.name} ) : ( )}

{item.name}

{item.brand && ( {item.brand} )} {item.price && ( {parseFloat(item.price).toLocaleString('ru-RU')} ₽ )} {new Date(item.created_at).toLocaleDateString('ru-RU')}
)}
) const renderPartsAPIItem = (item: PartsAPIArticle, index: number) => ( {viewMode === 'grid' ? (

{item.artArticleNr}

{item.artSupBrand}

Группа: {item.productGroup}

Поставщик: {item.supBrand}

ID: {item.artId}

) : (

{item.artArticleNr}

{item.artSupBrand} {item.productGroup}
)}
) return (
{/* Панель управления */}
{/* Поиск */}
setSearchQuery(e.target.value)} className="pl-10" />
{/* Элементы управления */}
{items.length} товаров
{/* Содержимое */} {isLoading ? (
Загрузка товаров...
) : error ? (
Ошибка загрузки: {error.message}
) : items.length === 0 ? (

Товары не найдены

Попробуйте изменить критерии поиска

) : (
{isViewingSavedData ? items.map((item: any) => renderSavedItem(item)) : (categoryType === 'partsindex' ? items.map((item: PartsIndexEntity) => renderPartsIndexItem(item)) : items.map((item: PartsAPIArticle, index: number) => renderPartsAPIItem(item, index)) ) }
)} {/* Пагинация и статистика */} {isViewingSavedData && savedData?.getCategoryProducts && (
Показано {((currentPage - 1) * itemsPerPage) + 1}-{Math.min(currentPage * itemsPerPage, savedData.getCategoryProducts.total)} из {savedData.getCategoryProducts.total.toLocaleString()} сохраненных товаров
Страница {currentPage}
)} {/* Пагинация для обычного просмотра */} {!isViewingSavedData && items.length >= itemsPerPage && (
Страница {currentPage}
)}
) }