/**
 * Блок поиска организаций для отправки заявок на партнерство
 * Включает поиск, фильтрацию и отправку заявок
 */

'use client'

import { Search, Send } from 'lucide-react'
import React, { useState } 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 { Textarea } from '@/components/ui/textarea'

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

export const SearchOrganizationsBlock = React.memo(function SearchOrganizationsBlock({
  searchResults,
  loading,
  onSendRequest,
  searchQuery,
  onSearchChange,
  typeFilter,
  onTypeFilterChange,
}: SearchOrganizationsBlockProps) {
  const [sendingTo, setSendingTo] = useState<string | null>(null)
  const [customMessage, setCustomMessage] = useState('')
  const [showMessageForm, setShowMessageForm] = useState<string | null>(null)

  const handleSendRequest = async (organizationId: string) => {
    setSendingTo(organizationId)
    try {
      await onSendRequest(organizationId, customMessage || undefined)
      setCustomMessage('')
      setShowMessageForm(null)
    } catch (error) {
      console.error('Error sending request:', error)
    } finally {
      setSendingTo(null)
    }
  }

  const handleShowMessageForm = (organizationId: string) => {
    setShowMessageForm(organizationId)
    setCustomMessage('Предлагаем партнерское сотрудничество')
  }

  return (
    <div className="space-y-6">
      {/* Фильтры поиска */}
      <Card className="p-4">
        <div className="flex flex-col md:flex-row gap-4">
          <div className="flex-1">
            <GlassInput
              placeholder="Поиск по названию, ИНН или адресу..."
              value={searchQuery}
              onChange={(e) => onSearchChange(e.target.value)}
              icon={Search}
            />
          </div>
          
          <div className="w-full md:w-48">
            <Select value={typeFilter} onValueChange={onTypeFilterChange}>
              <SelectTrigger>
                <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>
      </Card>

      {/* Результаты поиска */}
      {loading && (
        <div className="space-y-4">
          {Array.from({ length: 3 }).map((_, i) => (
            <Card key={i} className="p-6">
              <div className="animate-pulse">
                <div className="flex items-center space-x-4">
                  <div className="h-12 w-12 bg-gray-200 rounded-full"></div>
                  <div className="flex-1 space-y-2">
                    <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                    <div className="h-3 bg-gray-200 rounded w-1/2"></div>
                  </div>
                  <div className="h-8 w-20 bg-gray-200 rounded"></div>
                </div>
              </div>
            </Card>
          ))}
        </div>
      )}

      {!loading && searchQuery && !searchResults.length && (
        <Card className="p-8 text-center">
          <div className="flex flex-col items-center space-y-4">
            <div className="h-16 w-16 bg-gray-100 rounded-full flex items-center justify-center">
              <Search className="h-8 w-8 text-gray-400" />
            </div>
            <div>
              <h3 className="text-lg font-medium text-gray-900">Организации не найдены</h3>
              <p className="text-gray-500 mt-1">
                Попробуйте изменить параметры поиска
              </p>
            </div>
          </div>
        </Card>
      )}

      {!searchQuery && (
        <Card className="p-8 text-center">
          <div className="flex flex-col items-center space-y-4">
            <div className="h-16 w-16 bg-blue-100 rounded-full flex items-center justify-center">
              <Search className="h-8 w-8 text-blue-500" />
            </div>
            <div>
              <h3 className="text-lg font-medium text-gray-900">Поиск партнеров</h3>
              <p className="text-gray-500 mt-1">
                Введите название, ИНН или адрес организации для поиска
              </p>
            </div>
          </div>
        </Card>
      )}

      {/* Список найденных организаций */}
      {!loading && searchResults.length > 0 && (
        <div className="space-y-4">
          {searchResults.map((org) => (
            <Card key={org.id} className="p-6">
              <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-gray-900 truncate">
                        {org.name || org.fullName}
                      </h3>
                      <Badge variant="outline">
                        {ORGANIZATION_TYPES[org.type]}
                      </Badge>
                      
                      {/* Статусы */}
                      {org.isCounterparty && (
                        <Badge variant="secondary" className="bg-green-100 text-green-800">
                          Уже партнер
                        </Badge>
                      )}
                      {org.hasOutgoingRequest && (
                        <Badge variant="secondary" className="bg-yellow-100 text-yellow-800">
                          Заявка отправлена
                        </Badge>
                      )}
                    </div>

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

                    {org.address && (
                      <p className="text-sm text-gray-600 truncate">
                        {org.address}
                      </p>
                    )}
                  </div>
                </div>

                {/* Действия */}
                <div className="flex items-center space-x-2 flex-shrink-0 ml-4">
                  {!org.isCounterparty && !org.hasOutgoingRequest && (
                    <>
                      {showMessageForm === org.id ? (
                        <div className="w-80 space-y-3">
                          <Textarea
                            placeholder="Сообщение для заявки (необязательно)"
                            value={customMessage}
                            onChange={(e) => setCustomMessage(e.target.value)}
                            rows={3}
                            className="resize-none"
                          />
                          <div className="flex justify-end space-x-2">
                            <Button
                              variant="outline"
                              size="sm"
                              onClick={() => setShowMessageForm(null)}
                            >
                              Отмена
                            </Button>
                            <Button
                              size="sm"
                              onClick={() => handleSendRequest(org.id)}
                              disabled={sendingTo === org.id}
                            >
                              {sendingTo === org.id ? (
                                'Отправка...'
                              ) : (
                                <>
                                  <Send className="h-4 w-4 mr-1" />
                                  Отправить
                                </>
                              )}
                            </Button>
                          </div>
                        </div>
                      ) : (
                        <Button
                          size="sm"
                          onClick={() => handleShowMessageForm(org.id)}
                        >
                          <Send className="h-4 w-4 mr-1" />
                          Отправить заявку
                        </Button>
                      )}
                    </>
                  )}
                </div>
              </div>
            </Card>
          ))}

          {/* Статистика поиска */}
          <div className="text-center text-sm text-gray-500 pt-4">
            Найдено {searchResults.length} организаци{searchResults.length === 1 ? 'я' : 
              searchResults.length < 5 ? 'и' : 'й'}
          </div>
        </div>
      )}
    </div>
  )
})

SearchOrganizationsBlock.displayName = 'SearchOrganizationsBlock'