'use client'

import { Truck, Package, Calendar, DollarSign, TrendingUp, CheckCircle, AlertTriangle, Clock } from 'lucide-react'
import React, { useMemo } from 'react'

import { Badge } from '@/components/ui/badge'
import { Card } from '@/components/ui/card'

import { DeliveryDetailsProps } from './types'

const DELIVERY_STATUS_CONFIG = {
  'in-stock': {
    label: 'На складе',
    color: 'bg-green-500/20 text-green-300',
    icon: CheckCircle,
  },
  'in-transit': {
    label: 'В пути',
    color: 'bg-blue-500/20 text-blue-300',
    icon: Truck,
  },
  confirmed: {
    label: 'Подтверждено',
    color: 'bg-cyan-500/20 text-cyan-300',
    icon: CheckCircle,
  },
  planned: {
    label: 'Запланировано',
    color: 'bg-yellow-500/20 text-yellow-300',
    icon: Clock,
  },
  // Обратная совместимость
  delivered: {
    label: 'Доставлено',
    color: 'bg-green-500/20 text-green-300',
    icon: CheckCircle,
  },
  pending: {
    label: 'Ожидание',
    color: 'bg-yellow-500/20 text-yellow-300',
    icon: Clock,
  },
  delayed: {
    label: 'Задержка',
    color: 'bg-red-500/20 text-red-300',
    icon: AlertTriangle,
  },
} as const

export function DeliveryDetails({ supply, deliveries, viewMode, getStatusConfig }: DeliveryDetailsProps) {
  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('ru-RU', {
      style: 'currency',
      currency: 'RUB',
      minimumFractionDigits: 0,
    }).format(amount)
  }

  const formatNumber = (num: number) => {
    return new Intl.NumberFormat('ru-RU').format(num)
  }

  const getDeliveryStatusConfig = (status: string) => {
    return DELIVERY_STATUS_CONFIG[status as keyof typeof DELIVERY_STATUS_CONFIG] || DELIVERY_STATUS_CONFIG.pending
  }

  const totalStats = useMemo(() => {
    const totalQuantity = deliveries.reduce((sum, d) => sum + d.quantity, 0)
    const totalStock = deliveries.reduce((sum, d) => sum + d.currentStock, 0)
    const totalCost = deliveries.reduce((sum, d) => sum + d.price * d.currentStock, 0)
    const avgPrice = deliveries.length > 0 ? deliveries.reduce((sum, d) => sum + d.price, 0) / deliveries.length : 0

    return { totalQuantity, totalStock, totalCost, avgPrice }
  }, [deliveries])

  if (viewMode === 'grid') {
    return (
      <div className="ml-6 mt-4 space-y-4">
        <div className="text-sm font-medium text-white/70 uppercase tracking-wider mb-3 flex items-center space-x-2">
          <Truck className="h-4 w-4" />
          <span>История поставок ({deliveries.length})</span>
        </div>

        {/* Общая статистика */}
        <Card className="glass-card p-4 bg-white/5 border-white/10">
          <h4 className="text-sm font-medium text-white mb-3 flex items-center space-x-2">
            <TrendingUp className="h-4 w-4" />
            <span>Общая статистика</span>
          </h4>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
            <div>
              <p className="text-white/60">Общий заказ</p>
              <p className="text-white font-medium">
                {formatNumber(totalStats.totalQuantity)} {supply.unit}
              </p>
            </div>
            <div>
              <p className="text-white/60">Общий остаток</p>
              <p className="text-white font-medium">
                {formatNumber(totalStats.totalStock)} {supply.unit}
              </p>
            </div>
            <div>
              <p className="text-white/60">Общая стоимость</p>
              <p className="text-white font-medium">{formatCurrency(totalStats.totalCost)}</p>
            </div>
            <div>
              <p className="text-white/60">Средняя цена</p>
              <p className="text-white font-medium">{formatCurrency(totalStats.avgPrice)}</p>
            </div>
          </div>
        </Card>

        {/* Список поставок */}
        <div className="space-y-3">
          {deliveries.map((delivery, index) => {
            const deliveryStatusConfig = getDeliveryStatusConfig(delivery.status)
            const DeliveryStatusIcon = deliveryStatusConfig.icon

            return (
              <Card key={`${delivery.id}-${index}`} className="glass-card p-4 bg-white/5 border-white/10">
                <div className="flex items-start justify-between mb-3">
                  <div className="flex items-center space-x-2">
                    <Badge className={`${deliveryStatusConfig.color} text-xs`}>
                      <DeliveryStatusIcon className="h-3 w-3 mr-1" />
                      {deliveryStatusConfig.label}
                    </Badge>
                    <span className="text-xs text-white/60">
                      {new Date(delivery.createdAt).toLocaleDateString('ru-RU', {
                        year: 'numeric',
                        month: 'short',
                        day: 'numeric',
                        hour: '2-digit',
                        minute: '2-digit',
                      })}
                    </span>
                  </div>
                </div>

                <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
                  <div>
                    <p className="text-white/60">Остаток</p>
                    <p className="text-white font-medium">
                      {formatNumber(delivery.currentStock)} {delivery.unit}
                    </p>
                  </div>
                  <div>
                    <p className="text-white/60">Заказано</p>
                    <p className="text-white font-medium">
                      {formatNumber(delivery.quantity)} {delivery.unit}
                    </p>
                  </div>
                  <div>
                    <p className="text-white/60">Цена</p>
                    <p className="text-white font-medium">{formatCurrency(delivery.price)}</p>
                  </div>
                  <div>
                    <p className="text-white/60">Стоимость</p>
                    <p className="text-white font-medium">{formatCurrency(delivery.price * delivery.currentStock)}</p>
                  </div>
                </div>

                {delivery.description !== supply.description && (
                  <div className="mt-3 pt-3 border-t border-white/10">
                    <p className="text-white/60 text-xs">Описание: {delivery.description}</p>
                  </div>
                )}
              </Card>
            )
          })}
        </div>
      </div>
    )
  }

  // List view - компактное отображение
  return (
    <div className="ml-6 mt-2 space-y-2">
      <div className="text-xs font-medium text-white/70 uppercase tracking-wider mb-3 flex items-center space-x-2">
        <Truck className="h-3 w-3" />
        <span>История поставок</span>
      </div>

      <div className="space-y-2">
        {deliveries.map((delivery, index) => {
          const deliveryStatusConfig = getDeliveryStatusConfig(delivery.status)
          const DeliveryStatusIcon = deliveryStatusConfig.icon

          return (
            <Card key={`${delivery.id}-${index}`} className="glass-card p-3 bg-white/5 border-white/10">
              <div className="grid grid-cols-8 gap-3 items-center text-xs">
                <div>
                  <p className="text-white/60">Дата</p>
                  <p className="text-white font-medium">
                    {new Date(delivery.createdAt).toLocaleDateString('ru-RU', {
                      month: 'short',
                      day: 'numeric',
                      hour: '2-digit',
                      minute: '2-digit',
                    })}
                  </p>
                </div>

                <div>
                  <p className="text-white/60">Заказано</p>
                  <p className="text-white font-medium">
                    {formatNumber(delivery.quantity)} {delivery.unit}
                  </p>
                </div>

                <div>
                  <p className="text-white/60">Поставлено</p>
                  <p className="text-white font-medium">
                    {formatNumber(delivery.quantity)} {delivery.unit}
                  </p>
                </div>

                <div>
                  <p className="text-white/60">Отправлено</p>
                  <p className="text-white font-medium">
                    {formatNumber(delivery.shippedQuantity || 0)} {delivery.unit}
                  </p>
                </div>

                <div>
                  <p className="text-white/60">Остаток</p>
                  <p className="text-white font-medium">
                    {formatNumber(delivery.quantity - (delivery.shippedQuantity || 0))} {delivery.unit}
                  </p>
                </div>

                <div>
                  <p className="text-white/60">Цена</p>
                  <p className="text-white font-medium">{formatCurrency(delivery.price)}</p>
                </div>

                <div>
                  <p className="text-white/60">Стоимость</p>
                  <p className="text-white font-medium">{formatCurrency(delivery.price * delivery.quantity)}</p>
                </div>

                <div className="flex items-center space-x-2">
                  <Badge className={`${deliveryStatusConfig.color} text-xs`}>
                    <DeliveryStatusIcon className="h-3 w-3 mr-1" />
                    {deliveryStatusConfig.label}
                  </Badge>
                </div>
              </div>

              {delivery.description !== supply.description && (
                <div className="mt-2 pt-2 border-t border-white/10">
                  <p className="text-white/60 text-xs">Описание: {delivery.description}</p>
                </div>
              )}
            </Card>
          )
        })}
      </div>
    </div>
  )
}
