'use client'

import { useQuery } from '@apollo/client'
import { Clock, CheckCircle, Settings, Truck, Package, Calendar, Search } from 'lucide-react'
import { useState, useMemo } 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 { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { GET_SUPPLY_ORDERS } from '@/graphql/queries'
import { useAuth } from '@/hooks/useAuth'

import { SupplierOrderCard } from './supplier-order-card'
import { SupplierOrderStats } from './supplier-order-stats'
import { SupplierOrdersSearch } from './supplier-orders-search'

interface SupplyOrder {
  id: string
  organizationId: string
  partnerId: string
  deliveryDate: string
  status:
    | 'PENDING'
    | 'SUPPLIER_APPROVED'
    | 'CONFIRMED'
    | 'LOGISTICS_CONFIRMED'
    | 'SHIPPED'
    | 'IN_TRANSIT'
    | 'DELIVERED'
    | 'CANCELLED'
  totalAmount: number
  totalItems: number
  createdAt: string
  organization: {
    id: string
    name?: string
    fullName?: string
    type: string
    inn?: string
  }
  partner?: {
    id: string
    name?: string
    fullName?: string
    inn?: string
    address?: string
    phones?: string[]
    emails?: string[]
  }
  fulfillmentCenter?: {
    id: string
    name?: string
    fullName?: string
    type: string
  }
  logisticsPartner?: {
    id: string
    name?: string
    fullName?: string
    type: string
  }
  items: Array<{
    id: string
    quantity: number
    price: number
    totalPrice: number
    product: {
      id: string
      name: string
      article: string
      description?: string
      category?: {
        id: string
        name: string
      }
    }
  }>
}

export function SupplierOrdersTabs() {
  const { user } = useAuth()
  const [activeTab, setActiveTab] = useState('new')
  const [searchQuery, setSearchQuery] = useState('')
  const [dateFilter, setDateFilter] = useState('')
  const [priceRange, setPriceRange] = useState({ min: '', max: '' })

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

  // Фильтруем заказы где текущая организация является поставщиком
  const supplierOrders: SupplyOrder[] = useMemo(() => {
    return (data?.supplyOrders || []).filter((order: SupplyOrder) => order.partnerId === user?.organization?.id)
  }, [data?.supplyOrders, user?.organization?.id])

  // Фильтрация заказов по поисковому запросу
  const filteredOrders = useMemo(() => {
    let filtered = supplierOrders

    // Поиск по номеру заявки, заказчику, товарам, ИНН
    if (searchQuery) {
      const query = searchQuery.toLowerCase()
      filtered = filtered.filter(
        (order) =>
          order.id.toLowerCase().includes(query) ||
          (order.organization.name || '').toLowerCase().includes(query) ||
          (order.organization.fullName || '').toLowerCase().includes(query) ||
          (order.organization.inn || '').toLowerCase().includes(query) ||
          order.items.some((item) => item.product.name.toLowerCase().includes(query)),
      )
    }

    // Фильтр по диапазону цены
    if (priceRange.min || priceRange.max) {
      filtered = filtered.filter((order) => {
        if (priceRange.min && order.totalAmount < parseFloat(priceRange.min)) return false
        if (priceRange.max && order.totalAmount > parseFloat(priceRange.max)) return false
        return true
      })
    }

    return filtered
  }, [supplierOrders, searchQuery, priceRange])

  // Разделение заказов по статусам согласно правилам
  const ordersByStatus = useMemo(() => {
    return {
      new: filteredOrders.filter((order) => order.status === 'PENDING'),
      approved: filteredOrders.filter((order) => order.status === 'SUPPLIER_APPROVED'),
      inProgress: filteredOrders.filter((order) => ['CONFIRMED', 'LOGISTICS_CONFIRMED'].includes(order.status)),
      shipping: filteredOrders.filter((order) => ['SHIPPED', 'IN_TRANSIT'].includes(order.status)),
      completed: filteredOrders.filter((order) => order.status === 'DELIVERED'),
      all: filteredOrders,
    }
  }, [filteredOrders])

  const getTabBadgeCount = (tabKey: string) => {
    return ordersByStatus[tabKey as keyof typeof ordersByStatus]?.length || 0
  }

  const getCurrentOrders = () => {
    return ordersByStatus[activeTab as keyof typeof ordersByStatus] || []
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-white/60">Загрузка заявок...</div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-red-400">Ошибка загрузки заявок: {error.message}</div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* Статистика - Модуль 2 согласно правилам */}
      <SupplierOrderStats orders={supplierOrders} />

      {/* Блок табов - отдельный блок согласно visual-design-rules.md */}
      <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl p-6">
        <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
          <TabsList className="bg-transparent p-0 space-x-2">
            {/* Уровень 2: Фильтрация по статусам */}
            <TabsTrigger
              value="new"
              className="h-9 bg-white/8 border-white/20 rounded-lg font-medium ml-0 data-[state=active]:bg-white/15 data-[state=active]:text-white"
            >
              <Clock className="h-4 w-4 mr-2" />
              Новые
              {getTabBadgeCount('new') > 0 && (
                <Badge className="ml-2 bg-red-500/20 text-red-300 border-red-400/30">{getTabBadgeCount('new')}</Badge>
              )}
            </TabsTrigger>

            <TabsTrigger
              value="approved"
              className="h-9 bg-white/8 border-white/20 rounded-lg font-medium ml-4 data-[state=active]:bg-white/15 data-[state=active]:text-white"
            >
              <CheckCircle className="h-4 w-4 mr-2" />
              Одобренные
              {getTabBadgeCount('approved') > 0 && (
                <Badge className="ml-2 bg-green-500/20 text-green-300 border-green-400/30">
                  {getTabBadgeCount('approved')}
                </Badge>
              )}
            </TabsTrigger>

            <TabsTrigger
              value="inProgress"
              className="h-9 bg-white/8 border-white/20 rounded-lg font-medium ml-4 data-[state=active]:bg-white/15 data-[state=active]:text-white"
            >
              <Settings className="h-4 w-4 mr-2" />В работе
              {getTabBadgeCount('inProgress') > 0 && (
                <Badge className="ml-2 bg-blue-500/20 text-blue-300 border-blue-400/30">
                  {getTabBadgeCount('inProgress')}
                </Badge>
              )}
            </TabsTrigger>

            <TabsTrigger
              value="shipping"
              className="h-9 bg-white/8 border-white/20 rounded-lg font-medium ml-4 data-[state=active]:bg-white/15 data-[state=active]:text-white"
            >
              <Truck className="h-4 w-4 mr-2" />
              Отгрузка
              {getTabBadgeCount('shipping') > 0 && (
                <Badge className="ml-2 bg-orange-500/20 text-orange-300 border-orange-400/30">
                  {getTabBadgeCount('shipping')}
                </Badge>
              )}
            </TabsTrigger>

            <TabsTrigger
              value="completed"
              className="h-9 bg-white/8 border-white/20 rounded-lg font-medium ml-4 data-[state=active]:bg-white/15 data-[state=active]:text-white"
            >
              <Package className="h-4 w-4 mr-2" />
              Завершенные
              {getTabBadgeCount('completed') > 0 && (
                <Badge className="ml-2 bg-emerald-500/20 text-emerald-300 border-emerald-400/30">
                  {getTabBadgeCount('completed')}
                </Badge>
              )}
            </TabsTrigger>

            <TabsTrigger
              value="all"
              className="h-9 bg-white/8 border-white/20 rounded-lg font-medium ml-4 data-[state=active]:bg-white/15 data-[state=active]:text-white"
            >
              Все заявки
              {getTabBadgeCount('all') > 0 && (
                <Badge className="ml-2 bg-white/20 text-white/70 border-white/30">{getTabBadgeCount('all')}</Badge>
              )}
            </TabsTrigger>
          </TabsList>
        </Tabs>
      </div>

      {/* Поиск и фильтры */}
      <SupplierOrdersSearch
        searchQuery={searchQuery}
        onSearchChange={setSearchQuery}
        priceRange={priceRange}
        onPriceRangeChange={setPriceRange}
        dateFilter={dateFilter}
        onDateFilterChange={setDateFilter}
      />

      {/* Рабочее пространство - отдельный блок */}
      <div className="bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl">
        <div className="p-6">
          {getCurrentOrders().length === 0 ? (
            <div className="text-center py-12">
              <Package className="h-12 w-12 text-white/40 mx-auto mb-4" />
              <h3 className="text-lg font-semibold text-white mb-2">
                {activeTab === 'new' ? 'Нет новых заявок' : 'Заявки не найдены'}
              </h3>
              <p className="text-white/60">
                {activeTab === 'new'
                  ? 'Новые заявки от заказчиков будут отображаться здесь'
                  : 'Попробуйте изменить фильтры поиска'}
              </p>
            </div>
          ) : (
            <div className="space-y-4">
              {getCurrentOrders().map((order) => (
                <SupplierOrderCard key={order.id} order={order} />
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
