'use client'

import { Package, Wrench, RotateCcw, Plus, Calendar, TrendingUp, AlertCircle, 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 { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'

interface SupplyItem {
  id: string
  name: string
  type: 'product' | 'materials' | 'return'
  category: string
  quantity: number
  status: 'planned' | 'in-transit' | 'delivered' | 'processing'
  date: string
  supplier: string
  amount: number
}

const mockSupplies: SupplyItem[] = [
  {
    id: '1',
    name: 'Смартфоны iPhone 15',
    type: 'product',
    category: 'Электроника',
    quantity: 50,
    status: 'delivered',
    date: '2024-01-15',
    supplier: 'ООО "ТехноСнаб"',
    amount: 3750000,
  },
  {
    id: '2',
    name: 'Упаковочные коробки',
    type: 'materials',
    category: 'Расходники',
    quantity: 1000,
    status: 'in-transit',
    date: '2024-01-18',
    supplier: 'ИП Селлер Один',
    amount: 25000,
  },
  {
    id: '3',
    name: 'Товары с брагом (ПВЗ №5)',
    type: 'return',
    category: 'Возврат',
    quantity: 15,
    status: 'processing',
    date: '2024-01-20',
    supplier: 'ПВЗ Москва-5',
    amount: 185000,
  },
]

export function FulfillmentSuppliesTab() {
  const [activeFilter, setActiveFilter] = useState<'all' | 'product' | 'materials' | 'return'>('all')

  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 = {
      planned: { variant: 'outline' as const, color: 'text-blue-300 border-blue-400/30', label: 'Запланировано' },
      'in-transit': { variant: 'outline' as const, color: 'text-yellow-300 border-yellow-400/30', label: 'В пути' },
      delivered: { variant: 'outline' as const, color: 'text-green-300 border-green-400/30', label: 'Доставлено' },
      processing: { variant: 'outline' as const, color: 'text-orange-300 border-orange-400/30', label: 'Обработка' },
    }

    const config = statusConfig[status as keyof typeof statusConfig] || statusConfig.planned

    return (
      <Badge variant={config.variant} className={`glass-secondary ${config.color}`}>
        {config.label}
      </Badge>
    )
  }

  const getTypeIcon = (type: string) => {
    switch (type) {
      case 'product':
        return <Package className="h-4 w-4 text-blue-400" />
      case 'materials':
        return <Wrench className="h-4 w-4 text-purple-400" />
      case 'return':
        return <RotateCcw className="h-4 w-4 text-orange-400" />
      default:
        return <Package className="h-4 w-4 text-gray-400" />
    }
  }

  const filteredSupplies =
    activeFilter === 'all' ? mockSupplies : mockSupplies.filter((supply) => supply.type === activeFilter)

  const getTotalAmount = () => {
    return filteredSupplies.reduce((sum, supply) => sum + supply.amount, 0)
  }

  const getTotalQuantity = () => {
    return filteredSupplies.reduce((sum, supply) => sum + supply.quantity, 0)
  }

  return (
    <div className="h-full flex flex-col space-y-4 p-4">
      {/* Компактный заголовок и кнопка */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Building2 className="h-4 w-4 text-blue-400" />
          <span className="text-white font-medium text-sm">Фулфилмент</span>
        </div>
        <Button
          size="sm"
          className="bg-gradient-to-r from-blue-500 to-cyan-500 hover:from-blue-600 hover:to-cyan-600 text-white text-xs"
        >
          <Plus className="h-3 w-3 mr-1" />
          Создать
        </Button>
      </div>

      {/* Компактная статистика */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
        <Card className="glass-card p-3">
          <div className="flex items-center space-x-2">
            <div className="p-1.5 bg-blue-500/20 rounded">
              <Package className="h-3 w-3 text-blue-400" />
            </div>
            <div>
              <p className="text-white/60 text-xs">Поставок</p>
              <p className="text-lg font-bold text-white">{filteredSupplies.length}</p>
            </div>
          </div>
        </Card>

        <Card className="glass-card p-3">
          <div className="flex items-center space-x-2">
            <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(getTotalAmount())}</p>
            </div>
          </div>
        </Card>

        <Card className="glass-card p-3">
          <div className="flex items-center space-x-2">
            <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()}</p>
            </div>
          </div>
        </Card>

        <Card className="glass-card p-3">
          <div className="flex items-center space-x-2">
            <div className="p-1.5 bg-yellow-500/20 rounded">
              <Calendar className="h-3 w-3 text-yellow-400" />
            </div>
            <div>
              <p className="text-white/60 text-xs">В пути</p>
              <p className="text-lg font-bold text-white">
                {filteredSupplies.filter((s) => s.status === 'in-transit').length}
              </p>
            </div>
          </div>
        </Card>
      </div>

      {/* Компактные фильтры */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-1">
          <Button
            variant={activeFilter === 'all' ? 'secondary' : 'ghost'}
            size="sm"
            onClick={() => setActiveFilter('all')}
            className={`h-7 px-2 text-xs ${activeFilter === 'all' ? 'bg-white/20 text-white' : 'text-white/70 hover:bg-white/10'}`}
          >
            Все
          </Button>
          <Button
            variant={activeFilter === 'product' ? 'secondary' : 'ghost'}
            size="sm"
            onClick={() => setActiveFilter('product')}
            className={`h-7 px-2 text-xs ${activeFilter === 'product' ? 'bg-white/20 text-white' : 'text-white/70 hover:bg-white/10'} flex items-center gap-1`}
          >
            <Package className="h-3 w-3" />
            Товары
          </Button>
          <Button
            variant={activeFilter === 'materials' ? 'secondary' : 'ghost'}
            size="sm"
            onClick={() => setActiveFilter('materials')}
            className={`h-7 px-2 text-xs ${activeFilter === 'materials' ? 'bg-white/20 text-white' : 'text-white/70 hover:bg-white/10'} flex items-center gap-1`}
          >
            <Wrench className="h-3 w-3" />
            Расходники
          </Button>
          <Button
            variant={activeFilter === 'return' ? 'secondary' : 'ghost'}
            size="sm"
            onClick={() => setActiveFilter('return')}
            className={`h-7 px-2 text-xs ${activeFilter === 'return' ? 'bg-white/20 text-white' : 'text-white/70 hover:bg-white/10'} flex items-center gap-1`}
          >
            <RotateCcw className="h-3 w-3" />
            Возвраты
          </Button>
        </div>
      </div>

      {/* Компактная таблица */}
      <Card className="glass-card flex-1 overflow-hidden">
        <div className="p-3 h-full flex flex-col">
          <div className="overflow-x-auto flex-1">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-white/20">
                  <th className="text-left p-2 text-white font-medium text-xs">Тип</th>
                  <th className="text-left p-2 text-white font-medium text-xs">Наименование</th>
                  <th className="text-left p-2 text-white font-medium text-xs">Категория</th>
                  <th className="text-left p-2 text-white font-medium text-xs">Кол-во</th>
                  <th className="text-left p-2 text-white font-medium text-xs">Поставщик</th>
                  <th className="text-left p-2 text-white font-medium text-xs">Дата</th>
                  <th className="text-left p-2 text-white font-medium text-xs">Сумма</th>
                  <th className="text-left p-2 text-white font-medium text-xs">Статус</th>
                </tr>
              </thead>
              <tbody>
                {filteredSupplies.map((supply) => (
                  <tr key={supply.id} className="border-b border-white/10 hover:bg-white/5 transition-colors">
                    <td className="p-2">
                      <div className="flex items-center justify-center">{getTypeIcon(supply.type)}</div>
                    </td>
                    <td className="p-2">
                      <span className="text-white font-medium text-sm">{supply.name}</span>
                    </td>
                    <td className="p-2">
                      <span className="text-white/80 text-sm">{supply.category}</span>
                    </td>
                    <td className="p-2">
                      <span className="text-white font-semibold text-sm">{supply.quantity}</span>
                    </td>
                    <td className="p-2">
                      <span className="text-white/80 text-sm">{supply.supplier}</span>
                    </td>
                    <td className="p-2">
                      <span className="text-white/80 text-sm">{formatDate(supply.date)}</span>
                    </td>
                    <td className="p-2">
                      <span className="text-white font-semibold text-sm">{formatCurrency(supply.amount)}</span>
                    </td>
                    <td className="p-2">{getStatusBadge(supply.status)}</td>
                  </tr>
                ))}
              </tbody>
            </table>

            {filteredSupplies.length === 0 && (
              <div className="flex items-center justify-center p-8">
                <div className="text-center">
                  <Package className="h-12 w-12 text-white/20 mx-auto mb-4" />
                  <p className="text-white/60">Поставки не найдены</p>
                  <p className="text-white/40 text-sm mt-2">Измените фильтр или создайте новую поставку</p>
                </div>
              </div>
            )}
          </div>
        </div>
      </Card>
    </div>
  )
}
