'use client'

import { useMutation } from '@apollo/client'
import { CheckCircle, Clock, Package, Calendar, User, Truck, Building2 } from 'lucide-react'
import { useState } from 'react'
import { toast } from 'sonner'

import { Avatar, AvatarFallback } from '@/components/ui/avatar'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { Separator } from '@/components/ui/separator'
import { UPDATE_SELLER_GOODS_SUPPLY_STATUS } from '@/graphql/mutations/seller-goods-v2'

import type { FulfillmentGoodsSupply, Employee, LogisticsPartner } from '../types/fulfillment-goods.types'

interface NewGoodsTabProps {
  supplies: FulfillmentGoodsSupply[]
  employees: Employee[]
  logisticsPartners: LogisticsPartner[]
  onRefetch: () => void
}

export function NewGoodsTab({ supplies, employees, logisticsPartners, onRefetch }: NewGoodsTabProps) {
  const [expandedSupplies, setExpandedSupplies] = useState<Set<string>>(new Set())
  const [selectedEmployee, setSelectedEmployee] = useState<{[supplyId: string]: string}>({})
  const [selectedLogistics, setSelectedLogistics] = useState<{[supplyId: string]: string}>({})
  
  // Мутация для принятия поставки
  const [updateSupplyStatus, { loading: updating }] = useMutation(UPDATE_SELLER_GOODS_SUPPLY_STATUS, {
    onCompleted: () => {
      toast.success('Товарная поставка принята в обработку!')
      onRefetch()
      // Сбрасываем выбранные значения
      setSelectedEmployee({})
      setSelectedLogistics({})
    },
    onError: (error) => {
      console.error('Error accepting goods supply:', error)
      toast.error('Ошибка при принятии поставки')
    },
  })
  
  const toggleExpansion = (supplyId: string) => {
    const newExpanded = new Set(expandedSupplies)
    if (newExpanded.has(supplyId)) {
      newExpanded.delete(supplyId)
    } else {
      newExpanded.add(supplyId)
    }
    setExpandedSupplies(newExpanded)
  }
  
  const handleAcceptSupply = async (supplyId: string) => {
    const employee = selectedEmployee[supplyId]
    const logistics = selectedLogistics[supplyId]
    
    if (!employee) {
      toast.error('Выберите ответственного сотрудника')
      return
    }
    
    // Логистика опциональна - может быть уже выбрана селлером
    try {
      await updateSupplyStatus({
        variables: {
          id: supplyId,
          status: 'CONFIRMED',
          notes: `Принято в обработку. Ответственный: ${employees.find(e => e.id === employee)?.managerName}${logistics ? `. Логистика: ${logisticsPartners.find(l => l.id === logistics)?.name}` : ''}`,
        },
      })
    } catch (error) {
      console.error('Error accepting supply:', error)
    }
  }
  
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('ru-RU', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
    })
  }
  
  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('ru-RU', {
      style: 'currency',
      currency: 'RUB',
    }).format(amount)
  }
  
  const getInitials = (name: string): string => {
    return name
      .split(' ')
      .map((word) => word.charAt(0))
      .join('')
      .toUpperCase()
      .slice(0, 2)
  }
  
  if (supplies.length === 0) {
    return (
      <Card className="bg-white/10 backdrop-blur border-white/20 p-8">
        <div className="text-center">
          <Clock className="h-12 w-12 text-purple-400 mx-auto mb-4" />
          <h3 className="text-lg font-semibold text-white mb-2">Нет новых товарных поставок</h3>
          <p className="text-white/60">
            Товарные поставки от селлеров после одобрения поставщиками будут отображаться здесь
          </p>
        </div>
      </Card>
    )
  }
  
  return (
    <div className="space-y-4">
      {supplies.map((supply, index) => (
        <Card
          key={supply.id}
          className="bg-white/10 backdrop-blur border-white/20 overflow-hidden hover:bg-white/15 transition-colors cursor-pointer"
          onClick={() => toggleExpansion(supply.id)}
        >
          {/* Основная информация */}
          <div className="p-4">
            <div className="flex items-center justify-between">
              {/* Левая часть - информация о поставке */}
              <div className="flex items-center space-x-4 flex-1 min-w-0">
                {/* Номер поставки */}
                <div className="flex items-center space-x-2">
                  <Package className="h-4 w-4 text-purple-400" />
                  <span className="text-white font-semibold">#{supplies.length - index}</span>
                  <span className="text-white/60 text-xs">({supply.id.slice(-8)})</span>
                </div>
                
                {/* Информация о селлере */}
                <div className="flex items-center space-x-3 min-w-0">
                  <Avatar className="w-8 h-8">
                    <AvatarFallback className="bg-blue-500 text-white text-sm">
                      {getInitials(supply.seller.name)}
                    </AvatarFallback>
                  </Avatar>
                  <div className="min-w-0">
                    <h3 className="text-white font-medium text-sm truncate">
                      {supply.seller.name}
                    </h3>
                    <p className="text-white/60 text-xs">Селлер • {supply.seller.inn}</p>
                  </div>
                </div>
                
                {/* Краткая информация */}
                <div className="hidden lg:flex items-center space-x-4">
                  <div className="flex items-center space-x-1">
                    <Calendar className="h-4 w-4 text-blue-400" />
                    <span className="text-white text-sm">{formatDate(supply.requestedDeliveryDate)}</span>
                  </div>
                  <div className="flex items-center space-x-1">
                    <Package className="h-4 w-4 text-green-400" />
                    <span className="text-white text-sm">{supply.recipeItems.length} поз.</span>
                  </div>
                  <div className="flex items-center space-x-1">
                    <Building2 className="h-4 w-4 text-purple-400" />
                    <span className="text-white text-sm">{supply.supplier.name}</span>
                  </div>
                </div>
              </div>
              
              {/* Правая часть - статус и действия */}
              <div className="flex items-center space-x-3 flex-shrink-0">
                <Badge className="bg-green-500/20 text-green-300 border-green-500/30 border flex items-center gap-1 text-xs">
                  <CheckCircle className="h-3 w-3" />
                  Готов к приёмке
                </Badge>
                
                {/* Кнопка принятия */}
                <Button
                  size="sm"
                  onClick={(e) => {
                    e.stopPropagation()
                    handleAcceptSupply(supply.id)
                  }}
                  className="bg-purple-500/20 hover:bg-purple-500/30 text-purple-300 border border-purple-500/30 text-xs px-3 py-1 h-7"
                  disabled={!selectedEmployee[supply.id] || updating}
                >
                  <CheckCircle className="h-3 w-3 mr-1" />
                  Принять
                </Button>
              </div>
            </div>
            
            {/* Развернутые детали */}
            {expandedSupplies.has(supply.id) && (
              <>
                <Separator className="my-4 bg-white/10" />
                
                {/* Форма назначения */}
                <div className="mb-4 p-4 bg-purple-500/5 rounded-lg border border-purple-500/20">
                  <h4 className="text-white font-semibold mb-3 flex items-center">
                    <User className="h-4 w-4 mr-2 text-purple-400" />
                    Параметры принятия поставки
                  </h4>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {/* Выбор ответственного сотрудника */}
                    <div>
                      <label className="block text-white/80 text-sm mb-2">
                        Ответственный сотрудник *
                      </label>
                      <select
                        value={selectedEmployee[supply.id] || ''}
                        onChange={(e) => setSelectedEmployee({...selectedEmployee, [supply.id]: e.target.value})}
                        className="w-full bg-white/10 border border-white/20 rounded-md px-3 py-2 text-white text-sm focus:outline-none focus:ring-1 focus:ring-purple-500 focus:border-transparent"
                        onClick={(e) => e.stopPropagation()}
                      >
                        <option value="">Выберите сотрудника</option>
                        {employees.map((employee) => (
                          <option key={employee.id} value={employee.id} className="bg-gray-800">
                            {employee.managerName}
                          </option>
                        ))}
                      </select>
                    </div>
                    
                    {/* Выбор логистики (опционально) */}
                    <div>
                      <label className="block text-white/80 text-sm mb-2">
                        Логистический партнер {supply.logisticsPartner ? '(уже выбран)' : '(опционально)'}
                      </label>
                      {supply.logisticsPartner ? (
                        <div className="w-full bg-green-500/10 border border-green-500/30 rounded-md px-3 py-2 text-green-300 text-sm">
                          ✅ {supply.logisticsPartner.name}
                        </div>
                      ) : (
                        <select
                          value={selectedLogistics[supply.id] || ''}
                          onChange={(e) => setSelectedLogistics({...selectedLogistics, [supply.id]: e.target.value})}
                          className="w-full bg-white/10 border border-white/20 rounded-md px-3 py-2 text-white text-sm focus:outline-none focus:ring-1 focus:ring-purple-500 focus:border-transparent"
                          onClick={(e) => e.stopPropagation()}
                        >
                          <option value="">Оставить на потом</option>
                          {logisticsPartners.map((partner) => (
                            <option key={partner.id} value={partner.id} className="bg-gray-800">
                              {partner.name || partner.fullName}
                            </option>
                          ))}
                        </select>
                      )}
                    </div>
                  </div>
                </div>
                
                {/* Информация о поставке */}
                <div className="mb-4 p-3 bg-white/5 rounded">
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                    <div>
                      <span className="text-white/60 block">Общая сумма:</span>
                      <span className="text-white font-semibold">
                        {formatCurrency(supply.totalCostWithDelivery)}
                      </span>
                    </div>
                    <div>
                      <span className="text-white/60 block">Дата создания:</span>
                      <span className="text-white">{formatDate(supply.createdAt)}</span>
                    </div>
                    <div>
                      <span className="text-white/60 block">Одобрено поставщиком:</span>
                      <span className="text-white">
                        {supply.supplierApprovedAt ? formatDate(supply.supplierApprovedAt) : 'Неизвестно'}
                      </span>
                    </div>
                    <div>
                      <span className="text-white/60 block">Упаковок:</span>
                      <span className="text-white">{supply.packagesCount || 'Не указано'}</span>
                    </div>
                  </div>
                </div>
                
                {/* Список товаров */}
                <div>
                  <h4 className="text-white font-semibold mb-3 flex items-center text-sm">
                    <Package className="h-4 w-4 mr-2 text-green-400" />
                    Товары в поставке ({supply.recipeItems.length})
                  </h4>
                  <div className="space-y-3">
                    {supply.recipeItems.map((item) => (
                      <div key={item.id} className="bg-white/5 rounded p-3">
                        <div className="flex items-center justify-between">
                          <div className="flex-1 min-w-0">
                            <h5 className="text-white font-medium text-sm">{item.product.name}</h5>
                            <p className="text-white/60 text-xs">Артикул: {item.product.article}</p>
                            <Badge 
                              variant="secondary" 
                              className="bg-purple-500/20 text-purple-300 text-xs mt-1"
                            >
                              {item.recipeType}
                            </Badge>
                          </div>
                          <div className="text-right flex-shrink-0 ml-4">
                            <p className="text-white font-semibold">{item.quantity} шт.</p>
                            <p className="text-white/60 text-xs">{formatCurrency(item.product.price)}</p>
                            <p className="text-green-400 font-semibold text-sm">
                              {formatCurrency(item.product.price * item.quantity)}
                            </p>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
                
                {/* Заметки */}
                {(supply.notes || supply.supplierNotes) && (
                  <div className="mt-4 p-3 bg-blue-500/10 rounded border border-blue-500/20">
                    <h5 className="text-blue-300 text-sm font-medium mb-2">Заметки:</h5>
                    {supply.notes && (
                      <p className="text-blue-200 text-xs mb-1">
                        <strong>Селлер:</strong> {supply.notes}
                      </p>
                    )}
                    {supply.supplierNotes && (
                      <p className="text-blue-200 text-xs">
                        <strong>Поставщик:</strong> {supply.supplierNotes}
                      </p>
                    )}
                  </div>
                )}
              </>
            )}
          </div>
        </Card>
      ))}
    </div>
  )
}