/**
 * Блок списка текущих контрагентов
 * Отображает карточки организаций с возможностью удаления
 */

'use client'

import {
  Users,
  ArrowDownCircle,
  TrendingUp,
  ArrowUpCircle,
  Building,
  X,
  Calendar,
  Gift,
  Copy,
  Search,
  SortAsc,
  SortDesc,
} from 'lucide-react'
import React from 'react'

import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { GlassInput } from '@/components/ui/input'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'

import { OrganizationAvatar } from '../../organization-avatar'
import { ORGANIZATION_TYPES, type CounterpartiesListBlockProps } from '../types'

export const CounterpartiesListBlock = React.memo(function CounterpartiesListBlock({
  counterparties,
  loading,
  onRemove,
  onViewDetails,
  incomingRequestsCount = 0,
  outgoingRequestsCount = 0,
  incomingLoading = false,
  outgoingLoading = false,
  partnerLink,
  onCopyPartnerLink,
  // Фильтрация существующих контрагентов
  searchQuery = '',
  onSearchChange,
  typeFilter = 'all',
  onTypeFilterChange,
  sortField = 'name',
  sortOrder = 'asc',
  onSort,
  filteredCount,
  totalCount,
}: CounterpartiesListBlockProps) {
  if (loading) {
    return (
      <div className="space-y-4">
        {Array.from({ length: 3 }).map((_, i) => (
          <Card key={i} className="glass-card p-6">
            <div className="animate-pulse">
              <div className="flex items-center space-x-4">
                <div className="h-12 w-12 bg-white/10 rounded-full"></div>
                <div className="flex-1 space-y-2">
                  <div className="h-4 bg-white/10 rounded w-3/4"></div>
                  <div className="h-3 bg-white/10 rounded w-1/2"></div>
                </div>
              </div>
            </div>
          </Card>
        ))}
      </div>
    )
  }

  // Состояние пустого списка (показываем после статистики)
  const emptyState = !counterparties.length && (
    <Card className="glass-card p-8 text-center">
      <div className="flex flex-col items-center space-y-4">
        <div className="h-16 w-16 bg-white/10 rounded-full flex items-center justify-center">
          <Building className="h-8 w-8 text-white/40" />
        </div>
        <div>
          <h3 className="text-lg font-medium text-white">Контрагенты не найдены</h3>
          <p className="text-white/60 mt-1">Начните отправлять заявки на партнерство другим организациям</p>
        </div>
      </div>
    </Card>
  )

  return (
    <div className="space-y-4">
      {/* Статистические карточки */}
      <div className="grid grid-cols-4 gap-3">
        {/* Партнеров */}
        <Card className="glass-card p-3 hover:bg-white/5 transition-all duration-200">
          <div className="flex items-center gap-2">
            <div className="p-1.5 rounded-lg bg-blue-500/20 border border-blue-500/30">
              <Users className="h-4 w-4 text-blue-400" />
            </div>
            <div>
              <p className="text-xs text-white/60 uppercase tracking-wide">Партнеров</p>
              <p className="text-xl font-bold text-white">
                {loading ? (
                  <span className="inline-block h-6 w-8 bg-white/10 rounded animate-pulse" />
                ) : (
                  counterparties.length
                )}
              </p>
            </div>
          </div>
        </Card>

        {/* Заявок */}
        <Card className="glass-card p-3 hover:bg-white/5 transition-all duration-200">
          <div className="flex items-center gap-2">
            <div className="p-1.5 rounded-lg bg-yellow-500/20 border border-yellow-500/30">
              <ArrowDownCircle className="h-4 w-4 text-yellow-400" />
            </div>
            <div>
              <p className="text-xs text-white/60 uppercase tracking-wide">Заявок</p>
              <p className="text-xl font-bold text-white">
                {incomingLoading ? (
                  <span className="inline-block h-6 w-8 bg-white/10 rounded animate-pulse" />
                ) : (
                  incomingRequestsCount
                )}
              </p>
            </div>
          </div>
        </Card>

        {/* За месяц */}
        <Card className="glass-card p-3 hover:bg-white/5 transition-all duration-200">
          <div className="flex items-center gap-2">
            <div className="p-1.5 rounded-lg bg-green-500/20 border border-green-500/30">
              <TrendingUp className="h-4 w-4 text-green-400" />
            </div>
            <div>
              <p className="text-xs text-white/60 uppercase tracking-wide">За месяц</p>
              <p className="text-xl font-bold text-white">
                {loading ? (
                  <span className="inline-block h-6 w-8 bg-white/10 rounded animate-pulse" />
                ) : (
                  counterparties.filter((org) => {
                    const monthAgo = new Date()
                    monthAgo.setMonth(monthAgo.getMonth() - 1)
                    return new Date(org.createdAt) > monthAgo
                  }).length
                )}
              </p>
            </div>
          </div>
        </Card>

        {/* Исходящих */}
        <Card className="glass-card p-3 hover:bg-white/5 transition-all duration-200">
          <div className="flex items-center gap-2">
            <div className="p-1.5 rounded-lg bg-orange-500/20 border border-orange-500/30">
              <ArrowUpCircle className="h-4 w-4 text-orange-400" />
            </div>
            <div>
              <p className="text-xs text-white/60 uppercase tracking-wide">Исходящих</p>
              <p className="text-xl font-bold text-white">
                {outgoingLoading ? (
                  <span className="inline-block h-6 w-8 bg-white/10 rounded animate-pulse" />
                ) : (
                  outgoingRequestsCount
                )}
              </p>
            </div>
          </div>
        </Card>
      </div>

      {/* Компактная партнерская ссылка */}
      {partnerLink && (
        <Card className="glass-card p-4">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <div className="p-1.5 rounded-lg bg-yellow-500/20 border border-yellow-500/30">
                <Gift className="h-4 w-4 text-yellow-400" />
              </div>
              <h3 className="text-base font-semibold text-white">Партнерская ссылка</h3>
            </div>
            <div className="text-xs text-white/60">Прямое деловое сотрудничество с автоматическим добавлением</div>
          </div>
          <div className="flex items-center gap-3">
            <div className="flex-1 px-3 py-2 glass-input rounded-lg text-white/60 font-mono text-sm truncate">
              {partnerLink || 'Загрузка...'}
            </div>
            <Button
              size="sm"
              onClick={() => onCopyPartnerLink && onCopyPartnerLink(partnerLink || '')}
              className="glass-button hover:bg-white/20 transition-all duration-200 px-3"
            >
              <Copy className="h-4 w-4 mr-1" />
              Копировать
            </Button>
          </div>
        </Card>
      )}

      {/* Фильтры и поиск */}
      <Card className="glass-card p-3">
        <div className="flex flex-col xl:flex-row gap-3">
          {/* Поиск */}
          <div className="flex-1">
            <GlassInput
              placeholder="Поиск по названию, ИНН или адресу..."
              value={searchQuery}
              onChange={(e) => onSearchChange?.(e.target.value)}
              icon={Search}
            />
          </div>

          {/* Фильтр по типу */}
          <div className="w-full xl:w-48">
            <Select value={typeFilter} onValueChange={onTypeFilterChange}>
              <SelectTrigger className="glass-input">
                <SelectValue placeholder="Тип организации" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Все типы</SelectItem>
                <SelectItem value="FULFILLMENT">Фулфилмент</SelectItem>
                <SelectItem value="SELLER">Селлеры</SelectItem>
                <SelectItem value="LOGIST">Логистика</SelectItem>
                <SelectItem value="WHOLESALE">Поставщики</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* Сортировка */}
          <div className="w-full xl:w-48">
            <Select value={sortField} onValueChange={onSort}>
              <SelectTrigger className="glass-input">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="name">По названию</SelectItem>
                <SelectItem value="date">По дате</SelectItem>
                <SelectItem value="inn">По ИНН</SelectItem>
                <SelectItem value="type">По типу</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* Порядок сортировки */}
          <Button variant="outline" size="sm" onClick={() => onSort?.(sortField)} className="glass-button">
            {sortOrder === 'asc' ? <SortAsc className="h-4 w-4" /> : <SortDesc className="h-4 w-4" />}
          </Button>

          {/* Сброс фильтров */}
          {(searchQuery || typeFilter !== 'all') && (
            <Button
              variant="outline"
              size="sm"
              onClick={() => {
                onSearchChange?.('')
                onTypeFilterChange?.('all')
              }}
              className="glass-button text-red-400 hover:text-red-300"
            >
              <X className="h-4 w-4" />
            </Button>
          )}
        </div>

        {/* Статистика и быстрые фильтры */}
        <div className="flex items-center justify-between text-xs text-white/60 mt-3">
          <div>
            {filteredCount !== undefined && totalCount !== undefined ? (
              <>
                Показано {filteredCount} из {totalCount} контрагентов
              </>
            ) : (
              <>Показано {counterparties.length} контрагентов</>
            )}
          </div>

          {/* Быстрые фильтры по типам */}
          <div className="flex gap-1">
            {(['FULFILLMENT', 'SELLER', 'LOGIST', 'WHOLESALE'] as const).map((type) => {
              const count = counterparties.filter((org) => org.type === type).length
              return count > 0 ? (
                <Button
                  key={type}
                  variant="ghost"
                  size="sm"
                  onClick={() => onTypeFilterChange?.(type)}
                  className={`text-xs px-2 py-1 ${
                    typeFilter === type ? 'bg-blue-500/20 text-blue-300' : 'text-white/40 hover:text-white/70'
                  }`}
                >
                  {ORGANIZATION_TYPES[type]} ({count})
                </Button>
              ) : null
            })}
          </div>
        </div>
      </Card>

      {/* Пустое состояние */}
      {emptyState}

      {/* Список контрагентов */}
      {counterparties.map((org) => (
        <Card key={org.id} className="glass-card p-6 hover:bg-white/5 transition-all duration-200">
          <div className="flex items-start justify-between">
            <div className="flex items-start space-x-4 flex-1">
              {/* Аватар организации */}
              <OrganizationAvatar organization={org} size="lg" className="flex-shrink-0" />

              {/* Основная информация */}
              <div className="flex-1 min-w-0">
                <div className="flex items-center space-x-2 mb-2">
                  <h3 className="text-lg font-semibold text-white truncate">{org.name || org.fullName}</h3>
                  <Badge variant="outline" className="border-white/20 text-white/80 flex-shrink-0">
                    {ORGANIZATION_TYPES[org.type]}
                  </Badge>
                </div>

                {/* ИНН */}
                <p className="text-sm text-white/70 mb-2">ИНН: {org.inn}</p>

                {/* Дата добавления */}
                <div className="flex items-center space-x-2 text-xs text-white/50 mt-2">
                  <Calendar className="h-3 w-3" />
                  <span>Партнеры с {new Date(org.createdAt).toLocaleDateString('ru-RU')}</span>
                </div>
              </div>
            </div>

            {/* Действия */}
            <div className="flex items-center space-x-2 flex-shrink-0 ml-4">
              {onViewDetails && (
                <Button variant="outline" size="sm" onClick={() => onViewDetails(org)} className="glass-button">
                  Подробнее
                </Button>
              )}

              <Button
                variant="outline"
                size="sm"
                onClick={() => onRemove(org.id)}
                className="bg-red-500/20 hover:bg-red-500/30 text-red-300 border-red-500/30 hover:border-red-400/50"
              >
                <X className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </Card>
      ))}

      {/* Статистика */}
      {counterparties.length > 0 && (
        <div className="text-center text-sm text-white/60 pt-4">
          Показано {counterparties.length} контрагент
          {counterparties.length === 1 ? '' : counterparties.length < 5 ? 'а' : 'ов'}
        </div>
      )}
    </div>
  )
})

CounterpartiesListBlock.displayName = 'CounterpartiesListBlock'
