/**
 * TypeScript интерфейсы для модуля управления контрагентами
 * Модуляризовано согласно MODULAR_ARCHITECTURE_PATTERN.md
 */

// =============================================================================
// ОСНОВНЫЕ ДОМЕННЫЕ СУЩНОСТИ
// =============================================================================

export interface Organization {
  id: string
  inn: string
  name?: string
  fullName?: string
  type: 'FULFILLMENT' | 'SELLER' | 'LOGIST' | 'WHOLESALE'
  address?: string
  phones?: Array<{ value: string }>
  emails?: Array<{ value: string }>
  createdAt: string
  users?: Array<{ id: string; avatar?: string }>
  // Флаги для поиска
  isCounterparty?: boolean
  hasOutgoingRequest?: boolean
  isCurrentUser?: boolean
}

export interface CounterpartyRequest {
  id: string
  message?: string
  status: 'PENDING' | 'ACCEPTED' | 'REJECTED' | 'CANCELLED'
  createdAt: string
  sender: Organization
  receiver: Organization
}

export interface PartnerLink {
  id: string
  code: string
  url: string
  clickCount?: number
  registrationCount?: number
  createdAt: string
}

// =============================================================================
// ТИПЫ ДЛЯ ФИЛЬТРАЦИИ И СОРТИРОВКИ
// =============================================================================

export type SortField = 'name' | 'date' | 'inn' | 'type'
export type SortOrder = 'asc' | 'desc'
export type OrganizationType = 'all' | 'FULFILLMENT' | 'SELLER' | 'LOGIST' | 'WHOLESALE'

export interface FilterConfig {
  searchQuery: string
  typeFilter: OrganizationType
  sortField: SortField
  sortOrder: SortOrder
}

// =============================================================================
// PROPS ДЛЯ БЛОК-КОМПОНЕНТОВ
// =============================================================================

export interface CounterpartiesListBlockProps {
  counterparties: Organization[]
  loading: boolean
  onRemove: (id: string) => Promise<void>
  onViewDetails?: (organization: Organization) => void
  // Статистические данные
  incomingRequestsCount?: number
  outgoingRequestsCount?: number
  incomingLoading?: boolean
  outgoingLoading?: boolean
  // Партнерская ссылка
  partnerLink?: string | null
  onCopyPartnerLink?: (url: string) => void
  // Фильтрация существующих контрагентов
  searchQuery?: string
  onSearchChange?: (query: string) => void
  typeFilter?: OrganizationType
  onTypeFilterChange?: (type: OrganizationType) => void
  sortField?: SortField
  sortOrder?: SortOrder
  onSort?: (field: SortField) => void
  filteredCount?: number
  totalCount?: number
  // Поиск новых организаций (из старой вкладки "Поиск")
  searchResults?: Organization[]
  searchLoading?: boolean
  onSendRequest?: (organizationId: string, message?: string) => Promise<void>
  searchNewQuery?: string
  onSearchNewChange?: (query: string) => void
  searchNewTypeFilter?: OrganizationType
  onSearchNewTypeFilterChange?: (type: OrganizationType) => void
}

export interface IncomingRequestsBlockProps {
  requests: CounterpartyRequest[]
  loading: boolean
  onAccept: (requestId: string) => Promise<void>
  onReject: (requestId: string) => Promise<void>
}

export interface OutgoingRequestsBlockProps {
  requests: CounterpartyRequest[]
  loading: boolean
  onCancel: (requestId: string) => Promise<void>
}

export interface SearchOrganizationsBlockProps {
  searchResults: Organization[]
  loading: boolean
  onSendRequest: (organizationId: string, message?: string) => Promise<void>
  searchQuery: string
  onSearchChange: (query: string) => void
  typeFilter: OrganizationType
  onTypeFilterChange: (type: OrganizationType) => void
}

export interface PartnerLinksBlockProps {
  partnerLink: string | null
  loading: boolean
  onCopyLink: (url: string) => void
  onGenerateLink?: () => Promise<void>
}

export interface CounterpartyFiltersBlockProps {
  searchQuery: string
  onSearchChange: (query: string) => void
  typeFilter: OrganizationType
  onTypeFilterChange: (type: OrganizationType) => void
  sortField: SortField
  sortOrder: SortOrder
  onSort: (field: SortField) => void
  resultsCount: number
}

// =============================================================================
// ТИПЫ ДЛЯ HOOKS
// =============================================================================

export interface UseCounterpartyDataReturn {
  // Данные
  counterparties: Organization[]
  incomingRequests: CounterpartyRequest[]
  outgoingRequests: CounterpartyRequest[]
  searchResults: Organization[]
  partnerLink: PartnerLink | null
  
  // Состояние загрузки
  counterpartiesLoading: boolean
  incomingLoading: boolean
  outgoingLoading: boolean
  searchLoading: boolean
  partnerLinkLoading: boolean
  
  // Ошибки
  error: string | null
  
  // Методы
  refetchAll: () => Promise<void>
  searchOrganizations: (query: string, type?: OrganizationType) => Promise<void>
}

export interface UseCounterpartyActionsReturn {
  // Действия с заявками
  acceptRequest: (requestId: string) => Promise<void>
  rejectRequest: (requestId: string) => Promise<void>
  cancelRequest: (requestId: string) => Promise<void>
  sendRequest: (organizationId: string, message?: string) => Promise<void>
  
  // Действия с контрагентами
  removeCounterparty: (organizationId: string) => Promise<void>
  
  // Состояние
  loading: boolean
  error: string | null
}

export interface UseCounterpartyFiltersReturn {
  // Текущие фильтры
  searchQuery: string
  typeFilter: OrganizationType
  debouncedSearch: string
  
  // Методы обновления фильтров
  handleSearchChange: (query: string) => void
  handleTypeFilterChange: (type: OrganizationType) => void
}

export interface UsePartnerLinksReturn {
  // Данные
  partnerLink: PartnerLink | null
  loading: boolean
  error: string | null
  
  // Методы
  generateLink: () => Promise<void>
  copyToClipboard: (text: string) => Promise<boolean>
  refreshStats: () => Promise<void>
}

// =============================================================================
// ТИПЫ ДЛЯ GraphQL
// =============================================================================

export interface CounterpartyMutationVariables {
  requestId?: string
  organizationId?: string
  message?: string
}

export interface SearchOrganizationsVariables {
  type?: string
  search?: string
}

// =============================================================================
// УТИЛИТАРНЫЕ ТИПЫ
// =============================================================================

export interface TabConfig {
  key: string
  label: string
  count?: number
  icon?: React.ComponentType<{ className?: string }>
}

export interface ActionResult {
  success: boolean
  message?: string
  error?: string
}

// =============================================================================
// КОНСТАНТЫ И ЕНУМЫ
// =============================================================================

export const ORGANIZATION_TYPES = {
  FULFILLMENT: 'Фулфилмент',
  SELLER: 'Селлер',
  LOGIST: 'Логистика',
  WHOLESALE: 'Поставщик',
} as const

export const REQUEST_STATUSES = {
  PENDING: 'Ожидает',
  ACCEPTED: 'Принято',
  REJECTED: 'Отклонено',
  CANCELLED: 'Отменено',
} as const

export const SORT_FIELDS = {
  name: 'Название',
  date: 'Дата',
  inn: 'ИНН',
  type: 'Тип',
} as const