'use client'

import { useQuery } from '@apollo/client'
import { Search, ShoppingBag, Package2, ArrowLeft } from 'lucide-react'
import { useState, useMemo } from 'react'

import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { GET_ALL_PRODUCTS } from '@/graphql/queries'

import { ProductCard } from './product-card'

interface Product {
  id: string
  name: string
  article: string
  description?: string
  price: number
  quantity: number
  category?: { id: string; name: string }
  brand?: string
  color?: string
  size?: string
  weight?: number
  dimensions?: string
  material?: string
  images: string[]
  mainImage?: string
  isActive: boolean
  createdAt: string
  organization: {
    id: string
    inn: string
    name?: string
    fullName?: string
    type: string
    address?: string
    phones?: Array<{ value: string }>
    emails?: Array<{ value: string }>
    users?: Array<{ id: string; avatar?: string; managerName?: string }>
  }
}

interface MarketProductsProps {
  selectedCategoryId?: string
  selectedCategoryName?: string
  onBackToCategories?: () => void
}

export function MarketProducts({ selectedCategoryId, selectedCategoryName, onBackToCategories }: MarketProductsProps) {
  const [searchTerm, setSearchTerm] = useState('')
  const [selectedCategory, setSelectedCategory] = useState<string>('')
  const [localSearch, setLocalSearch] = useState('')

  const { data, loading } = useQuery(GET_ALL_PRODUCTS, {
    variables: {
      search: searchTerm || null,
      category: selectedCategoryId || selectedCategory || null,
    },
  })

  const products: Product[] = useMemo(() => data?.allProducts || [], [data?.allProducts])

  // Получаем уникальные категории из товаров
  const categories = useMemo(() => {
    const allCategories = products
      .map((product) => product.category?.name)
      .filter(Boolean)
      .filter((category, index, arr) => arr.indexOf(category) === index)
      .sort()

    return allCategories
  }, [products])

  const handleSearch = () => {
    setSearchTerm(localSearch.trim())
  }

  // Фильтруем товары по доступности
  const availableProducts = products.filter((product) => product.isActive && product.quantity > 0)
  const totalProducts = products.length
  const availableCount = availableProducts.length

  return (
    <div className="h-full flex flex-col space-y-4 overflow-hidden p-6">
      {/* Кнопка назад и заголовок */}
      {selectedCategoryName && onBackToCategories && (
        <div className="flex items-center space-x-3 flex-shrink-0">
          <Button
            onClick={onBackToCategories}
            variant="outline"
            className="glass-secondary text-white hover:text-white border-white/20 hover:border-white/40"
          >
            <ArrowLeft className="h-4 w-4 mr-2" />
            Назад к категориям
          </Button>
          <div>
            <h2 className="text-xl font-bold text-white">{selectedCategoryName}</h2>
            <p className="text-white/60 text-sm">Товары выбранной категории</p>
          </div>
        </div>
      )}

      {/* Поиск */}
      <div className="flex space-x-4 flex-shrink-0">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-3 h-4 w-4 text-white/40" />
          <Input
            placeholder="Поиск товаров по названию, артикулу, бренду..."
            value={localSearch}
            onChange={(e) => setLocalSearch(e.target.value)}
            onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
            className="pl-10 glass-input text-white placeholder:text-white/40 h-10"
          />
        </div>

        <Button
          onClick={handleSearch}
          className="bg-purple-500/20 hover:bg-purple-500/30 text-purple-300 border-purple-500/30 cursor-pointer h-10"
        >
          <Search className="h-4 w-4 mr-2" />
          Найти
        </Button>
      </div>

      {/* Категории */}
      <div className="flex-shrink-0">
        <h4 className="text-white font-medium mb-3 flex items-center">
          <Package2 className="h-4 w-4 mr-2" />
          Категории
        </h4>

        <div className="flex flex-wrap gap-2">
          <Button
            onClick={() => setSelectedCategory('')}
            variant={selectedCategory === '' ? 'default' : 'outline'}
            className={`h-8 px-3 text-sm transition-all ${
              selectedCategory === ''
                ? 'bg-purple-500 hover:bg-purple-600 text-white'
                : 'bg-white/5 hover:bg-white/10 text-white/70 border-white/20'
            }`}
          >
            Все категории
          </Button>
          {categories.map((category) => (
            <Button
              key={category}
              onClick={() => setSelectedCategory(category!)}
              variant={selectedCategory === category ? 'default' : 'outline'}
              className={`h-8 px-3 text-sm transition-all ${
                selectedCategory === category
                  ? 'bg-purple-500 hover:bg-purple-600 text-white'
                  : 'bg-white/5 hover:bg-white/10 text-white/70 border-white/20'
              }`}
            >
              {category}
            </Button>
          ))}
        </div>
      </div>

      {/* Заголовок с статистикой */}
      <div className="flex items-center justify-between flex-shrink-0">
        <div className="flex items-center space-x-3">
          <ShoppingBag className="h-6 w-6 text-purple-400" />
          <div>
            <h3 className="text-lg font-semibold text-white">Товары поставщиков</h3>
            <p className="text-white/60 text-sm">
              Найдено {totalProducts} товаров, доступно {availableCount}
            </p>
          </div>
        </div>

        {/* Активные фильтры */}
        <div className="flex items-center space-x-2">
          {searchTerm && (
            <div className="bg-purple-500/20 px-3 py-1 rounded-full text-purple-300 text-sm flex items-center">
              <Search className="h-3 w-3 mr-1" />
              {searchTerm}
              <button
                onClick={() => {
                  setSearchTerm('')
                  setLocalSearch('')
                }}
                className="ml-2 hover:text-white"
              >
                ×
              </button>
            </div>
          )}
          {selectedCategory && (
            <div className="bg-purple-500/20 px-3 py-1 rounded-full text-purple-300 text-sm flex items-center">
              <Package2 className="h-3 w-3 mr-1" />
              {selectedCategory}
              <button onClick={() => setSelectedCategory('')} className="ml-2 hover:text-white">
                ×
              </button>
            </div>
          )}
        </div>
      </div>

      {/* Список товаров */}
      <div className="flex-1 overflow-auto min-h-0">
        {loading ? (
          <div className="flex items-center justify-center p-8">
            <div className="text-white/60">Загружаем товары...</div>
          </div>
        ) : products.length === 0 ? (
          <div className="glass-card p-8">
            <div className="text-center">
              <ShoppingBag className="h-12 w-12 text-white/20 mx-auto mb-4" />
              <p className="text-white/60">
                {searchTerm || selectedCategory ? 'Товары не найдены' : 'Пока нет товаров для отображения'}
              </p>
              <p className="text-white/40 text-sm mt-2">
                {searchTerm || selectedCategory
                  ? 'Попробуйте изменить условия поиска или фильтры'
                  : 'Поставщики еще не добавили свои товары'}
              </p>
            </div>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6 gap-4">
            {products.map((product) => (
              <ProductCard key={product.id} product={product} />
            ))}
          </div>
        )}
      </div>
      {/* Пагинация будет добавлена позже если понадобится */}
    </div>
  )
}
