"use client"

import React, { useState } from 'react'
import { Card } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Truck, Package, Clock, AlertCircle, Search, Plus } from 'lucide-react'

interface FulfillmentOrder {
  id: string
  orderId: string
  customerName: string
  items: Array<{
    name: string
    quantity: number
    sku: string
  }>
  status: 'pending' | 'processing' | 'shipped' | 'delivered' | 'cancelled'
  priority: 'low' | 'medium' | 'high'
  createdAt: string
  shippingAddress: string
  totalValue: number
}

interface FulfillmentStats {
  totalOrders: number
  pendingOrders: number
  processingOrders: number
  shippedOrders: number
  averageProcessingTime: number
}

export function FulfillmentWarehouseTab() {
  const [searchTerm, setSearchTerm] = useState('')
  const [selectedStatus, setSelectedStatus] = useState<string>('all')
  
  const [orders, setOrders] = useState<FulfillmentOrder[]>([
    {
      id: '1',
      orderId: 'FL-2024-001',
      customerName: 'Иван Петров',
      items: [
        { name: 'Товар A', quantity: 2, sku: 'SKU-001' },
        { name: 'Товар B', quantity: 1, sku: 'SKU-002' }
      ],
      status: 'pending',
      priority: 'high',
      createdAt: '2024-01-15T10:30:00',
      shippingAddress: 'Москва, ул. Ленина, 10',
      totalValue: 3500
    },
    {
      id: '2',
      orderId: 'FL-2024-002',
      customerName: 'Анна Сидорова',
      items: [
        { name: 'Товар C', quantity: 1, sku: 'SKU-003' }
      ],
      status: 'processing',
      priority: 'medium',
      createdAt: '2024-01-14T15:20:00',
      shippingAddress: 'СПб, пр. Невский, 25',
      totalValue: 1200
    },
    {
      id: '3',
      orderId: 'FL-2024-003',
      customerName: 'Олег Козлов',
      items: [
        { name: 'Товар D', quantity: 3, sku: 'SKU-004' },
        { name: 'Товар E', quantity: 2, sku: 'SKU-005' }
      ],
      status: 'shipped',
      priority: 'low',
      createdAt: '2024-01-13T09:15:00',
      shippingAddress: 'Екатеринбург, ул. Мира, 45',
      totalValue: 5600
    }
  ])

  const stats: FulfillmentStats = {
    totalOrders: orders.length,
    pendingOrders: orders.filter(o => o.status === 'pending').length,
    processingOrders: orders.filter(o => o.status === 'processing').length,
    shippedOrders: orders.filter(o => o.status === 'shipped').length,
    averageProcessingTime: 2.5
  }

  const filteredOrders = orders.filter(order => {
    const matchesSearch = !searchTerm || 
      order.orderId.toLowerCase().includes(searchTerm.toLowerCase()) ||
      order.customerName.toLowerCase().includes(searchTerm.toLowerCase())
    
    const matchesStatus = selectedStatus === 'all' || order.status === selectedStatus
    
    return matchesSearch && matchesStatus
  })

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'pending': return 'bg-yellow-500/20 text-yellow-400 border-yellow-500/30'
      case 'processing': return 'bg-blue-500/20 text-blue-400 border-blue-500/30'
      case 'shipped': return 'bg-green-500/20 text-green-400 border-green-500/30'
      case 'delivered': return 'bg-emerald-500/20 text-emerald-400 border-emerald-500/30'
      case 'cancelled': return 'bg-red-500/20 text-red-400 border-red-500/30'
      default: return 'bg-gray-500/20 text-gray-400 border-gray-500/30'
    }
  }

  const getStatusText = (status: string) => {
    switch (status) {
      case 'pending': return 'Ожидает'
      case 'processing': return 'Обрабатывается'
      case 'shipped': return 'Отправлен'
      case 'delivered': return 'Доставлен'
      case 'cancelled': return 'Отменён'
      default: return status
    }
  }

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'high': return 'text-red-400'
      case 'medium': return 'text-yellow-400'
      case 'low': return 'text-green-400'
      default: return 'text-white/60'
    }
  }

  const getPriorityText = (priority: string) => {
    switch (priority) {
      case 'high': return 'Высокий'
      case 'medium': return 'Средний'
      case 'low': return 'Низкий'
      default: return priority
    }
  }

  return (
    <div className="h-full flex flex-col space-y-6">
      {/* Статистика */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <Card className="glass-card border-white/10 p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-white/60 text-sm">Всего заказов</p>
              <p className="text-2xl font-bold text-white">{stats.totalOrders}</p>
            </div>
            <Package className="h-8 w-8 text-blue-400" />
          </div>
        </Card>

        <Card className="glass-card border-white/10 p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-white/60 text-sm">Ожидают обработки</p>
              <p className="text-2xl font-bold text-yellow-400">{stats.pendingOrders}</p>
            </div>
            <Clock className="h-8 w-8 text-yellow-400" />
          </div>
        </Card>

        <Card className="glass-card border-white/10 p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-white/60 text-sm">В обработке</p>
              <p className="text-2xl font-bold text-blue-400">{stats.processingOrders}</p>
            </div>
            <AlertCircle className="h-8 w-8 text-blue-400" />
          </div>
        </Card>

        <Card className="glass-card border-white/10 p-4">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-white/60 text-sm">Отправлено</p>
              <p className="text-2xl font-bold text-green-400">{stats.shippedOrders}</p>
            </div>
            <Truck className="h-8 w-8 text-green-400" />
          </div>
        </Card>
      </div>

      {/* Панель управления */}
      <div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between">
        <div className="flex gap-4 flex-1">
          <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="pl-10 bg-white/5 border-white/10 text-white placeholder:text-white/40"
            />
          </div>
          
          <select 
            value={selectedStatus}
            onChange={(e) => setSelectedStatus(e.target.value)}
            className="px-3 py-2 bg-white/5 border border-white/10 rounded-md text-white text-sm"
          >
            <option value="all">Все статусы</option>
            <option value="pending">Ожидает</option>
            <option value="processing">Обрабатывается</option>
            <option value="shipped">Отправлен</option>
            <option value="delivered">Доставлен</option>
            <option value="cancelled">Отменён</option>
          </select>
        </div>
        
        <Button className="bg-blue-600 hover:bg-blue-700">
          <Plus className="h-4 w-4 mr-2" />
          Новый заказ
        </Button>
      </div>

      {/* Список заказов */}
      <div className="flex-1 overflow-hidden">
        {filteredOrders.length === 0 ? (
          <Card className="glass-card border-white/10 p-8 text-center">
            <Package className="h-12 w-12 text-white/40 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-white mb-2">
              {searchTerm ? 'Заказы не найдены' : 'Нет заказов'}
            </h3>
            <p className="text-white/60 mb-4">
              {searchTerm ? 'Попробуйте изменить параметры поиска' : 'Здесь будут отображаться заказы фулфилмент'}
            </p>
          </Card>
        ) : (
          <div className="overflow-y-auto pr-2 max-h-full space-y-3">
            {filteredOrders.map((order) => (
              <Card key={order.id} className="glass-card border-white/10 p-4 hover:bg-white/5 transition-colors">
                <div className="flex items-start justify-between mb-3">
                  <div className="flex items-center gap-3">
                    <h3 className="text-white font-semibold">{order.orderId}</h3>
                    <Badge className={getStatusColor(order.status)}>
                      {getStatusText(order.status)}
                    </Badge>
                    <span className={`text-xs font-medium ${getPriorityColor(order.priority)}`}>
                      {getPriorityText(order.priority)}
                    </span>
                  </div>
                  <div className="text-right">
                    <p className="text-white font-bold">{order.totalValue.toLocaleString()} ₽</p>
                    <p className="text-white/60 text-xs">
                      {new Date(order.createdAt).toLocaleDateString('ru-RU')}
                    </p>
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div>
                    <p className="text-white/60 text-xs mb-1">Клиент</p>
                    <p className="text-white text-sm">{order.customerName}</p>
                  </div>
                  
                  <div>
                    <p className="text-white/60 text-xs mb-1">Товары</p>
                    <div className="space-y-1">
                      {order.items.map((item, index) => (
                        <p key={index} className="text-white text-xs">
                          {item.name} × {item.quantity}
                        </p>
                      ))}
                    </div>
                  </div>
                  
                  <div>
                    <p className="text-white/60 text-xs mb-1">Адрес доставки</p>
                    <p className="text-white text-xs">{order.shippingAddress}</p>
                  </div>
                </div>

                <div className="flex justify-end gap-2 mt-4">
                  <Button size="sm" variant="outline" className="border-white/10 text-white/60 hover:bg-white/5">
                    Подробнее
                  </Button>
                  {order.status === 'pending' && (
                    <Button size="sm" className="bg-blue-600 hover:bg-blue-700">
                      Начать обработку
                    </Button>
                  )}
                </div>
              </Card>
            ))}
          </div>
        )}
      </div>
    </div>
  )
} 