"use client"

import React from 'react'
import { WholesalerCard } from './wholesaler-card'
import { Input } from '@/components/ui/input'
import { Users, Search } from 'lucide-react'
import { WholesalerForCreation, CounterpartyWholesaler } from './types'

interface WholesalerGridProps {
  wholesalers: CounterpartyWholesaler[]
  onWholesalerSelect: (wholesaler: WholesalerForCreation) => void
  searchQuery: string
  onSearchChange: (query: string) => void
  loading?: boolean
}

export function WholesalerGrid({ 
  wholesalers, 
  onWholesalerSelect, 
  searchQuery, 
  onSearchChange,
  loading = false 
}: WholesalerGridProps) {
  // Фильтруем оптовиков по поисковому запросу
  const filteredWholesalers = wholesalers.filter((wholesaler) => 
    wholesaler.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
    wholesaler.fullName?.toLowerCase().includes(searchQuery.toLowerCase()) ||
    wholesaler.inn?.toLowerCase().includes(searchQuery.toLowerCase())
  )

  const handleWholesalerClick = (wholesaler: CounterpartyWholesaler) => {
    // Адаптируем данные под существующий интерфейс
    const adaptedWholesaler: WholesalerForCreation = {
      id: wholesaler.id,
      inn: wholesaler.inn || '',
      name: wholesaler.name || 'Неизвестная организация',
      fullName: wholesaler.fullName || wholesaler.name || 'Неизвестная организация',
      address: wholesaler.address || 'Адрес не указан',
      phone: wholesaler.phones?.[0]?.value,
      email: wholesaler.emails?.[0]?.value,
      rating: 4.5, // Временное значение
      productCount: 0, // Временное значение
      specialization: ['Оптовая торговля'] // Временное значение
    }
    onWholesalerSelect(adaptedWholesaler)
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center p-8">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-4 border-white border-t-transparent mx-auto mb-4"></div>
          <p className="text-white/60">Загружаем оптовиков...</p>
        </div>
      </div>
    )
  }

  return (
    <div>
      {/* Поиск */}
      <div className="mb-4">
        <div className="relative max-w-md">
          <Search className="absolute left-3 top-3 h-4 w-4 text-white/40" />
          <Input
            placeholder="Поиск оптовиков..."
            value={searchQuery}
            onChange={(e) => onSearchChange(e.target.value)}
            className="pl-10 glass-input text-white placeholder:text-white/40 h-10"
          />
        </div>
      </div>

      {filteredWholesalers.length === 0 ? (
        <div className="text-center p-8">
          <Users className="h-12 w-12 text-white/20 mx-auto mb-4" />
          <p className="text-white/60">
            {searchQuery ? 'Оптовики не найдены' : 'У вас нет контрагентов-оптовиков'}
          </p>
          <p className="text-white/40 text-sm mt-2">
            {searchQuery ? 'Попробуйте изменить условия поиска' : 'Добавьте оптовиков в разделе "Партнеры"'}
          </p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
          {filteredWholesalers.map((wholesaler) => {
            const adaptedWholesaler: WholesalerForCreation = {
              id: wholesaler.id,
              inn: wholesaler.inn || '',
              name: wholesaler.name || 'Неизвестная организация',
              fullName: wholesaler.fullName || wholesaler.name || 'Неизвестная организация',
              address: wholesaler.address || 'Адрес не указан',
              phone: wholesaler.phones?.[0]?.value,
              email: wholesaler.emails?.[0]?.value,
              rating: 4.5,
              productCount: 0,
              specialization: ['Оптовая торговля']
            }

            return (
              <WholesalerCard
                key={wholesaler.id}
                wholesaler={adaptedWholesaler}
                onClick={() => handleWholesalerClick(wholesaler)}
              />
            )
          })}
        </div>
      )}
    </div>
  )
} 