'use client'

import { useQuery } from '@apollo/client'
import { Wrench, Plus, Search, TrendingUp, AlertCircle, Eye, Calendar, Package2, Building2 } from 'lucide-react'
import { useState } from 'react'

import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { GET_SUPPLY_ORDERS } from '@/graphql/queries'
import { useAuthContext } from '@/contexts/AuthContext'

// Интерфейс для заказа поставки от селлера
interface SellerSupplyOrder {
  id: string
  organizationId: string
  deliveryDate: string
  createdAt: string
  totalItems: number
  totalAmount: number
  status: string
  fulfillmentCenterId: string
  organization: {
    id: string
    name?: string
    fullName?: string
    type: string
  }
  partner: {
    id: string
    name?: string
    fullName?: string
  }
  items: {
    id: string
    quantity: number
    price: number
    totalPrice: number
    product: {
      name: string
      article: string
      category?: {
        name: string
      }
    }
  }[]
}

export function SellerMaterialsTab() {
  const { user } = useAuthContext()
  const [searchTerm, setSearchTerm] = useState('')
  const [statusFilter, setStatusFilter] = useState('all')

  // Загружаем реальные данные заказов поставок
  const { data, loading, error } = useQuery(GET_SUPPLY_ORDERS, {
    fetchPolicy: 'cache-and-network',
    notifyOnNetworkStatusChange: true,
  })

  // Получаем ID текущей организации (фулфилмент-центра)
  const currentOrganizationId = user?.organization?.id

  // "Расходники селлеров" = расходники, которые СЕЛЛЕРЫ заказали для доставки на наш склад
  // Критерии: создатель != мы И получатель = мы
  const sellerSupplyOrders: SellerSupplyOrder[] = (data?.supplyOrders || []).filter((order: SellerSupplyOrder) => {
    return (
      order.organizationId !== currentOrganizationId && // Создали НЕ мы (селлер)
      order.fulfillmentCenterId === currentOrganizationId // Получатель - мы
    )
  })

  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('ru-RU', {
      style: 'currency',
      currency: 'RUB',
      minimumFractionDigits: 0,
    }).format(amount)
  }

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('ru-RU', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
    })
  }

  const getStatusBadge = (status: string) => {
    const statusConfig = {
      PENDING: {
        color: 'text-blue-300 border-blue-400/30',
        label: 'Ожидает подтверждения',
      },
      CONFIRMED: {
        color: 'text-yellow-300 border-yellow-400/30',
        label: 'Подтверждено',
      },
      IN_TRANSIT: {
        color: 'text-orange-300 border-orange-400/30',
        label: 'В пути',
      },
      DELIVERED: {
        color: 'text-green-300 border-green-400/30',
        label: 'Доставлено',
      },
      CANCELLED: {
        color: 'text-red-300 border-red-400/30',
        label: 'Отменено',
      },
    }

    const config = statusConfig[status as keyof typeof statusConfig] || statusConfig.PENDING
    return <Badge className={`${config.color}`}>{config.label}</Badge>
  }

  // Фильтрация поставок
  const filteredOrders = sellerSupplyOrders.filter((order) => {
    const matchesSearch =
      order.organization.name?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      order.organization.fullName?.toLowerCase().includes(searchTerm.toLowerCase()) ||
      order.items.some((item) => item.product.name.toLowerCase().includes(searchTerm.toLowerCase()))

    const matchesStatus = statusFilter === 'all' || order.status === statusFilter

    return matchesSearch && matchesStatus
  })

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-2 border-white border-t-transparent"></div>
        <span className="ml-3 text-white/60">Загрузка расходников селлеров...</span>
      </div>
    )
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <Wrench className="h-12 w-12 text-red-400 mx-auto mb-4" />
          <p className="text-red-400 font-medium">Ошибка загрузки расходников селлеров</p>
          <p className="text-white/60 text-sm mt-2">{error.message}</p>
        </div>
      </div>
    )
  }

  const getTotalValue = () => {
    return filteredOrders.reduce((sum, order) => sum + order.totalAmount, 0)
  }

  const getTotalQuantity = () => {
    return filteredOrders.reduce((sum, order) => sum + order.totalItems, 0)
  }

  return (
    <div className="h-full flex flex-col space-y-4 p-4">
      {/* Статистика с кнопкой */}
      <div className="flex items-center justify-between gap-4">
        <div className="grid grid-cols-2 lg:grid-cols-3 gap-3 flex-1">
          <Card className="glass-card p-3 h-[60px]">
            <div className="flex items-center space-x-2 h-full">
              <div className="p-1.5 bg-orange-500/20 rounded">
                <Wrench className="h-3 w-3 text-orange-400" />
              </div>
              <div>
                <p className="text-white/60 text-xs">Поставок</p>
                <p className="text-lg font-bold text-white">{filteredOrders.length}</p>
              </div>
            </div>
          </Card>

          <Card className="glass-card p-3 h-[60px]">
            <div className="flex items-center space-x-2 h-full">
              <div className="p-1.5 bg-green-500/20 rounded">
                <TrendingUp className="h-3 w-3 text-green-400" />
              </div>
              <div>
                <p className="text-white/60 text-xs">Стоимость</p>
                <p className="text-lg font-bold text-white">{formatCurrency(getTotalValue())}</p>
              </div>
            </div>
          </Card>

          <Card className="glass-card p-3 h-[60px]">
            <div className="flex items-center space-x-2 h-full">
              <div className="p-1.5 bg-purple-500/20 rounded">
                <AlertCircle className="h-3 w-3 text-purple-400" />
              </div>
              <div>
                <p className="text-white/60 text-xs">Единиц</p>
                <p className="text-lg font-bold text-white">{getTotalQuantity().toLocaleString()}</p>
              </div>
            </div>
          </Card>
        </div>

        <Button
          size="sm"
          className="bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600 text-white text-sm px-6 h-[60px] whitespace-nowrap"
        >
          <Plus className="h-4 w-4 mr-2" />
          Заказать материалы
        </Button>
      </div>

      {/* Фильтры */}
      <div className="flex items-center gap-3">
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-white/40" />
          <Input
            placeholder="Поиск по материалам, селлерам..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="glass-input pl-10 text-white placeholder:text-white/40"
          />
        </div>

        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="glass-input text-white text-sm px-3 py-2 rounded-lg bg-white/5 border border-white/10"
        >
          <option value="all">Все статусы</option>
          <option value="PENDING">Ожидает подтверждения</option>
          <option value="CONFIRMED">Подтверждено</option>
          <option value="IN_TRANSIT">В пути</option>
          <option value="DELIVERED">Доставлено</option>
          <option value="CANCELLED">Отменено</option>
        </select>
      </div>

      {/* Список материалов */}
      <div className="flex-1 overflow-hidden">
        {filteredOrders.length === 0 ? (
          <Card className="bg-white/10 backdrop-blur border-white/20 p-8">
            <div className="text-center">
              <Wrench className="h-16 w-16 text-white/20 mx-auto mb-4" />
              <h3 className="text-lg font-semibold text-white mb-2">Нет поставок от селлеров</h3>
              <p className="text-white/60">
                Здесь будут отображаться расходники, которые селлеры заказывают для доставки на ваш склад.
              </p>
            </div>
          </Card>
        ) : (
          <div className="h-full overflow-y-auto space-y-3">
            {filteredOrders.map((order) => (
              <Card key={order.id} className="glass-card p-4 hover:bg-white/10 transition-colors">
                <div className="flex items-center justify-between">
                  <div className="flex-1">
                    <div className="flex items-center gap-3 mb-2">
                      <h3 className="text-white font-medium">
                        {order.organization.name || order.organization.fullName}
                      </h3>
                      {getStatusBadge(order.status)}
                    </div>

                    <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 text-sm">
                      <div>
                        <p className="text-white/60">Селлер</p>
                        <p className="text-white">{order.organization.name || order.organization.fullName}</p>
                      </div>
                      <div>
                        <p className="text-white/60">Дата доставки</p>
                        <p className="text-white">{formatDate(order.deliveryDate)}</p>
                      </div>
                      <div>
                        <p className="text-white/60">Количество</p>
                        <p className="text-white font-semibold">{order.totalItems.toLocaleString()} шт.</p>
                      </div>
                      <div>
                        <p className="text-white/60">Общая стоимость</p>
                        <p className="text-white font-semibold">{formatCurrency(order.totalAmount)}</p>
                      </div>
                    </div>

                    <div className="mt-3 flex items-center justify-between">
                      <div className="flex items-center gap-4 text-sm">
                        <span className="text-white/60">
                          Дата заказа: <span className="text-white">{formatDate(order.createdAt)}</span>
                        </span>
                      </div>
                    </div>

                    <div className="mt-2">
                      <p className="text-white/60 text-xs">
                        Статус: <span className="text-white/80">{order.status}</span>
                      </p>
                    </div>
                  </div>

                  <div className="flex items-center gap-2 ml-4">
                    <Button size="sm" variant="ghost" className="text-white/60 hover:text-white hover:bg-white/10">
                      <Eye className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </Card>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}
