'use client'

import { useQuery } from '@apollo/client'
import {
    Copy,
    Package,
    Plus,
    Search,
    Trash2,
} from 'lucide-react'
import { useState } from 'react'

import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { GET_WB_WAREHOUSE_DATA } from '@/graphql/queries'
import { useAuthContext } from '@/contexts/AuthContext'

interface WBStock {
  nmId: number
  vendorCode: string
  title: string
  brand: string
  price: number
  stocks: Array<{
    warehouseId: number
    warehouseName: string
    quantity: number
    quantityFull: number
    inWayToClient: number
    inWayFromClient: number
  }>
  totalQuantity: number
  totalReserved: number
  photos: any[]
  mediaFiles: any[]
  characteristics: any[]
  subjectName: string
  description: string
}

interface ExternalAd {
  id: string
  name: string
  url: string
  cost: number
  clicks?: number
}

interface ProductAdvertising {
  wbCampaigns: {
    campaignId: number
    views: number
    clicks: number
    cost: number
    orders: number
  }[]
  externalAds: ExternalAd[]
}

interface ProductData {
  nmId: number
  name: string
  totalViews: number
  totalClicks: number
  totalCost: number
  totalOrders: number
  totalRevenue: number
  advertising: ProductAdvertising
}

interface DailyAdvertisingData {
  date: string
  totalSum: number
  totalOrders: number
  totalRevenue: number
  products: ProductData[]
}

interface GeneratedLink {
  id: string
  adId: string
  adName: string
  targetUrl: string
  trackingUrl: string
  clicks: number
  createdAt: string
}

interface SimpleAdvertisingTableProps {
  dailyData: DailyAdvertisingData[]
  productPhotos?: Map<number, string>
  generatedLinksData?: Record<string, GeneratedLink[]>
  onAddExternalAd?: (date: string, ad: Omit<ExternalAd, 'id'>, nmId?: string) => void
  onRemoveExternalAd?: (date: string, adId: string) => void
  onUpdateExternalAd?: (date: string, adId: string, updates: Partial<ExternalAd>) => void
  onGenerateLink?: (date: string, adId: string, adName: string, adUrl: string) => void
}

export function SimpleAdvertisingTable({
  dailyData,
  productPhotos = new Map(),
  generatedLinksData = {},
  onAddExternalAd,
  onRemoveExternalAd,
  onUpdateExternalAd,
  onGenerateLink,
}: SimpleAdvertisingTableProps) {
  const { user } = useAuthContext()
  const [showAddForm, setShowAddForm] = useState<string | null>(null)
  const [showProductList, setShowProductList] = useState<string | null>(null)
  const [searchTerm, setSearchTerm] = useState('')
  const [filteredProducts, setFilteredProducts] = useState<WBStock[]>([])
  const [newExternalAd, setNewExternalAd] = useState({
    name: '',
    url: '',
    cost: '',
  })
  const [selectedProduct, setSelectedProduct] = useState<WBStock | null>(null)

  // Получаем данные склада ВБ из кэша
  const {
    data: warehouseData,
    loading: warehouseLoading,
    error: warehouseError,
  } = useQuery(GET_WB_WAREHOUSE_DATA, {
    skip: !user,
    errorPolicy: 'all',
  })

  // Вычисляем общие итоги для результирующей строки
  const totalWbCost = dailyData.reduce(
    (sum, day) => sum + day.products.reduce((daySum, product) => daySum + product.totalCost, 0),
    0,
  )
  const totalExternalCost = dailyData.reduce(
    (sum, day) =>
      sum +
      day.products.reduce(
        (daySum, product) => daySum + product.advertising.externalAds.reduce((adSum, ad) => adSum + ad.cost, 0),
        0,
      ),
    0,
  )
  const totalCost = totalWbCost + totalExternalCost
  const totalOrders = dailyData.reduce((sum, day) => sum + day.totalOrders, 0)

  const formatCurrency = (value: number) => {
    if (value === 0) return '—'
    if (value < 100) {
      return `${value.toFixed(2)}₽`
    }
    return new Intl.NumberFormat('ru-RU', {
      style: 'currency',
      currency: 'RUB',
      minimumFractionDigits: 0,
      maximumFractionDigits: 0,
    }).format(value)
  }

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

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

  const handleAddExternalAdLocal = (productKey: string, date: string, nmId?: string) => {
    if (newExternalAd.name && newExternalAd.url && newExternalAd.cost && onAddExternalAd) {
      console.warn('Creating external ad for:', { productKey, date, nmId, selectedProduct })

      onAddExternalAd(
        date,
        {
          name: newExternalAd.name,
          url: newExternalAd.url,
          cost: parseFloat(newExternalAd.cost) || 0,
        },
        nmId,
      )
      setNewExternalAd({ name: '', url: '', cost: '' })
      setShowAddForm(null)
      setSelectedProduct(null)
      setShowProductList(null)
    }
  }

  // Получаем все товары из кэша ВБ
  const getAllProducts = (): WBStock[] => {
    if (!warehouseData?.getWBWarehouseData?.success || !warehouseData.getWBWarehouseData.cache?.data) {
      return []
    }

    try {
      const parsedData =
        typeof warehouseData.getWBWarehouseData.cache.data === 'string'
          ? JSON.parse(warehouseData.getWBWarehouseData.cache.data)
          : warehouseData.getWBWarehouseData.cache.data

      return parsedData.stocks || []
    } catch (error) {
      console.error('Error parsing warehouse data:', error)
      return []
    }
  }

  const filterProducts = (term: string) => {
    const allProducts = getAllProducts()

    if (!term.trim()) {
      setFilteredProducts(allProducts)
      return
    }

    const filtered = allProducts.filter(
      (product) =>
        product.title.toLowerCase().includes(term.toLowerCase()) ||
        product.brand.toLowerCase().includes(term.toLowerCase()) ||
        product.vendorCode.toLowerCase().includes(term.toLowerCase()) ||
        product.subjectName?.toLowerCase().includes(term.toLowerCase()) ||
        product.nmId.toString().includes(term),
    )
    setFilteredProducts(filtered)
  }

  const handleProductSelect = (product: WBStock, date: string) => {
    setSelectedProduct(product)
    setShowProductList(null)
    setShowAddForm(`new-product-${date}-${product.nmId}`)
  }

  const handleShowProductList = (date: string) => {
    setShowProductList(date)
    const allProducts = getAllProducts()
    setFilteredProducts(allProducts)
  }

  const getProductImage = (product: WBStock) => {
    // Генерируем fallback URL как в оригинальном компоненте
    const fallbackUrl = `https://basket-${String(product.nmId).slice(0, 2)}.wbbasket.ru/vol${String(product.nmId).slice(0, -5)}/part${String(product.nmId).slice(0, -3)}/${product.nmId}/images/big/1.webp`

    // Проверяем photos
    if (product.photos && product.photos.length > 0) {
      const photo = product.photos[0] as any
      return photo?.big || photo?.c516x688 || photo?.c246x328 || photo?.square || photo?.tm || fallbackUrl
    }

    // Проверяем mediaFiles
    if (product.mediaFiles && product.mediaFiles.length > 0) {
      const media = product.mediaFiles[0] as any
      return media?.big || media?.c516x688 || media?.c246x328 || media?.square || media?.tm || fallbackUrl
    }

    return fallbackUrl
  }

  return (
    <div className="bg-white/5 rounded-lg border border-white/10 overflow-hidden">
      {/* Заголовок таблицы */}
      <div className="bg-purple-600/20 border-b border-white/10">
        <div className="grid grid-cols-5 gap-4 p-3 text-white text-sm font-medium">
          <div>Дата</div>
          <div className="text-center">Сумма (руб)</div>
          <div className="text-center">Заказы (ед)</div>
          <div className="text-center">Реклама ВБ</div>
          <div className="text-center">Реклама внешняя</div>
        </div>
      </div>

      {/* Результирующая строка под шапкой */}
      <div className="bg-green-600/20 border-b border-white/10">
        <div className="grid grid-cols-5 gap-4 p-3 text-white text-sm font-bold">
          <div>ИТОГО</div>
          <div className="text-center">{formatCurrency(totalCost)}</div>
          <div className="text-center">{totalOrders}</div>
          <div className="text-center">{formatCurrency(totalWbCost)}</div>
          <div className="text-center">{formatCurrency(totalExternalCost)}</div>
        </div>
      </div>

      {/* Строки таблицы - 2 уровня: день -> товары (всегда открыто) */}
      <div className="max-h-96 overflow-y-auto">
        {dailyData.map((day) => {
          const dayWbCost = day.products.reduce((sum, product) => sum + product.totalCost, 0)
          const dayExternalCost = day.products.reduce(
            (sum, product) => sum + product.advertising.externalAds.reduce((adSum, ad) => adSum + ad.cost, 0),
            0,
          )
          const dayTotalCost = dayWbCost + dayExternalCost
          const dayOrders = day.totalOrders

          return (
            <div key={day.date}>
              {/* Основная строка дня */}
              <div className="grid grid-cols-5 gap-4 p-3 border-b border-white/5 bg-white/5 text-white/80 text-sm font-medium">
                <div className="flex items-center gap-2">
                  <span className="font-bold">{formatDate(day.date)}</span>
                </div>
                <div className="text-center">{formatCurrency(dayTotalCost)}</div>
                <div className="text-center">{dayOrders}</div>
                <div className="text-center">{formatCurrency(dayWbCost)}</div>
                <div className="text-center">{formatCurrency(dayExternalCost)}</div>
              </div>

              {/* Товары всегда видны - второй уровень */}
              <div className="border-b border-white/5">
                {day.products.map((product) => {
                  const productKey = `${day.date}-${product.nmId}`
                  const productExternalCost = product.advertising.externalAds.reduce((sum, ad) => sum + ad.cost, 0)
                  const productTotalCost = product.totalCost + productExternalCost

                  return (
                    <div key={productKey} className="ml-4">
                      {/* Строка товара с многострочными ячейками */}
                      <div className="grid grid-cols-5 gap-4 p-3 border-b border-white/5 text-white/70 text-sm">
                        {/* Карточка товара */}
                        <div className="flex items-start gap-2">
                          {productPhotos.has(product.nmId) && (
                            <img
                              src={productPhotos.get(product.nmId)}
                              alt={product.name}
                              className="w-8 h-8 rounded object-cover flex-shrink-0"
                            />
                          )}
                          <div>
                            <div className="text-white/90 text-xs font-medium">{product.name}</div>
                            <div className="text-white/60 text-xs">#{product.nmId}</div>
                          </div>
                        </div>

                        {/* Общая сумма */}
                        <div className="text-center self-start">{formatCurrency(productTotalCost)}</div>

                        {/* Заказы */}
                        <div className="text-center self-start">{product.totalOrders}</div>

                        {/* Реклама ВБ - многострочная ячейка */}
                        <div className="text-center">
                          {product.advertising.wbCampaigns.length > 0 ? (
                            <div className="space-y-1">
                              {product.advertising.wbCampaigns.map((campaign, index) => (
                                <div key={campaign.campaignId} className="text-xs bg-blue-500/10 rounded p-1">
                                  <div className="text-blue-400 font-medium">
                                    {index === 0
                                      ? 'Авто'
                                      : index === 1
                                        ? 'Фразы'
                                        : index === 2
                                          ? 'Предмет'
                                          : `Тип ${campaign.campaignId}`}
                                  </div>
                                  <div className="text-white/80">{formatCurrency(campaign.cost)}</div>
                                  <div className="text-white/60">{campaign.orders} зак.</div>
                                </div>
                              ))}
                            </div>
                          ) : (
                            <span className="text-white/40">—</span>
                          )}
                        </div>

                        {/* Реклама внешняя - многострочная ячейка с кнопками */}
                        <div className="text-center">
                          <div className="space-y-1">
                            {product.advertising.externalAds.map((ad) => {
                              const overlayClicks = generatedLinksData[day.date]?.find(
                                (link) => link.adId === ad.id,
                              )?.clicks
                              const displayClicks = overlayClicks ?? ad.clicks ?? 0
                              return (
                              <div key={ad.id} className="text-xs bg-purple-500/10 rounded p-1">
                                <div className="text-purple-400 font-medium truncate">{ad.name}</div>
                                <div className="text-white/80">{formatCurrency(ad.cost)}</div>
                                <div className="text-white/60">{displayClicks} кликов</div>
                                <div className="flex gap-1 justify-center mt-1">
                                  {onGenerateLink && (
                                    <Button
                                      size="sm"
                                      variant="ghost"
                                      onClick={(e) => {
                                        e.stopPropagation()
                                        onGenerateLink(day.date, ad.id, ad.name, ad.url)
                                      }}
                                      className="h-5 w-5 p-0 text-blue-400 hover:bg-blue-500/20"
                                      title="Скопировать ссылку"
                                    >
                                      <Copy className="h-3 w-3" />
                                    </Button>
                                  )}
                                  {onRemoveExternalAd && (
                                    <Button
                                      size="sm"
                                      variant="ghost"
                                      onClick={(e) => {
                                        e.stopPropagation()
                                        onRemoveExternalAd(day.date, ad.id)
                                      }}
                                      className="h-5 w-5 p-0 text-red-400 hover:bg-red-500/20"
                                      title="Удалить"
                                    >
                                      <Trash2 className="h-3 w-3" />
                                    </Button>
                                  )}
                                </div>
                              </div>
                              )
                            })}

                            {/* Инлайн форма добавления внешней рекламы */}
                            {onAddExternalAd && (
                              <div>
                                {showAddForm === productKey ? (
                                  <div className="bg-white/5 rounded p-2 space-y-2">
                                    <Input
                                      placeholder="Название"
                                      value={newExternalAd.name}
                                      onChange={(e) => setNewExternalAd((prev) => ({ ...prev, name: e.target.value }))}
                                      className="h-6 bg-white/10 border-white/20 text-white text-xs"
                                    />
                                    <Input
                                      placeholder="URL"
                                      value={newExternalAd.url}
                                      onChange={(e) => setNewExternalAd((prev) => ({ ...prev, url: e.target.value }))}
                                      className="h-6 bg-white/10 border-white/20 text-white text-xs"
                                    />
                                    <Input
                                      placeholder="Стоимость"
                                      type="number"
                                      value={newExternalAd.cost}
                                      onChange={(e) => setNewExternalAd((prev) => ({ ...prev, cost: e.target.value }))}
                                      className="h-6 bg-white/10 border-white/20 text-white text-xs"
                                    />
                                    <div className="flex gap-1">
                                      <Button
                                        size="sm"
                                        onClick={() => handleAddExternalAdLocal(productKey, day.date)}
                                        className="h-6 bg-green-600 hover:bg-green-700 text-white text-xs px-2 flex-1"
                                      >
                                        Добавить
                                      </Button>
                                      <Button
                                        size="sm"
                                        onClick={() => setShowAddForm(null)}
                                        variant="ghost"
                                        className="h-6 text-white/60 hover:bg-white/10 text-xs px-2"
                                      >
                                        ×
                                      </Button>
                                    </div>
                                  </div>
                                ) : (
                                  <button
                                    onClick={() => setShowAddForm(productKey)}
                                    className="w-full h-6 px-2 bg-gradient-to-r from-purple-500/20 to-purple-600/20 border border-purple-500/30 rounded text-purple-300 hover:from-purple-500/30 hover:to-purple-600/30 hover:border-purple-400/50 hover:text-purple-200 transition-all duration-200 text-xs flex items-center justify-center gap-1 backdrop-blur-sm"
                                  >
                                    <Plus className="h-3 w-3" />
                                    Добавить
                                  </button>
                                )}
                              </div>
                            )}
                          </div>
                        </div>
                      </div>
                    </div>
                  )
                })}

                {/* Кнопка добавления рекламы для нового товара */}
                {onAddExternalAd && (
                  <div className="ml-4 p-3 border-b border-white/5">
                    {showProductList === day.date ? (
                      <div className="bg-white/5 rounded p-3 space-y-3">
                        <div className="flex items-center justify-between">
                          <h4 className="text-white font-medium text-sm">Выберите товар для рекламы</h4>
                          <Button
                            size="sm"
                            onClick={() => {
                              setShowProductList(null)
                              setSearchTerm('')
                            }}
                            variant="ghost"
                            className="text-white/60 hover:bg-white/10 h-6 w-6 p-0"
                          >
                            ×
                          </Button>
                        </div>

                        {/* Поиск среди загруженных товаров */}
                        <div className="flex items-center gap-2">
                          <Search className="h-4 w-4 text-white/60" />
                          <Input
                            placeholder="Поиск среди товаров..."
                            value={searchTerm}
                            onChange={(e) => {
                              setSearchTerm(e.target.value)
                              filterProducts(e.target.value)
                            }}
                            className="bg-white/10 border-white/20 text-white text-sm"
                          />
                        </div>

                        {warehouseLoading ? (
                          <div className="text-center text-white/60 text-sm py-4">Загрузка товаров...</div>
                        ) : warehouseError ? (
                          <div className="text-center text-red-400 text-sm py-4">
                            Ошибка загрузки товаров: {warehouseError.message}
                          </div>
                        ) : filteredProducts.length > 0 ? (
                          <div className="max-h-64 overflow-y-auto space-y-1">
                            {filteredProducts.map((product) => (
                              <div
                                key={product.nmId}
                                onClick={() => handleProductSelect(product, day.date)}
                                className="flex items-center gap-3 p-3 bg-white/5 rounded hover:bg-white/10 cursor-pointer transition-colors border border-white/10"
                              >
                                {getProductImage(product) && (
                                  <img
                                    src={getProductImage(product)!}
                                    alt={product.title}
                                    className="w-12 h-12 rounded object-cover flex-shrink-0"
                                  />
                                )}
                                <div className="flex-1 min-w-0">
                                  <div className="text-white text-sm font-medium truncate mb-1">{product.title}</div>
                                  <div className="text-white/60 text-xs space-y-0.5">
                                    <div>
                                      {product.brand} • #{product.nmId}
                                    </div>
                                    <div>Артикул: {product.vendorCode}</div>
                                    <div className="text-green-400">На складе: {product.totalQuantity} шт.</div>
                                  </div>
                                </div>
                              </div>
                            ))}
                          </div>
                        ) : (
                          <div className="text-center text-white/60 text-sm py-4">
                            {searchTerm ? 'Товары не найдены' : 'Нет доступных товаров'}
                          </div>
                        )}
                      </div>
                    ) : showAddForm?.startsWith(`new-product-${day.date}`) ? (
                      <div className="bg-white/5 rounded p-3 space-y-3">
                        {selectedProduct && (
                          <div className="flex items-center gap-3 p-3 bg-white/10 rounded border border-white/20">
                            {getProductImage(selectedProduct) && (
                              <img
                                src={getProductImage(selectedProduct)!}
                                alt={selectedProduct.title}
                                className="w-12 h-12 rounded object-cover flex-shrink-0"
                              />
                            )}
                            <div className="flex-1 min-w-0">
                              <div className="text-white text-sm font-medium truncate mb-1">
                                {selectedProduct.title}
                              </div>
                              <div className="text-white/60 text-xs space-y-0.5">
                                <div>
                                  {selectedProduct.brand} • #{selectedProduct.nmId}
                                </div>
                                <div>Артикул: {selectedProduct.vendorCode}</div>
                              </div>
                            </div>
                          </div>
                        )}

                        <Input
                          placeholder="Название рекламы"
                          value={newExternalAd.name}
                          onChange={(e) => setNewExternalAd((prev) => ({ ...prev, name: e.target.value }))}
                          className="bg-white/10 border-white/20 text-white text-sm"
                        />
                        <Input
                          placeholder="URL рекламы"
                          value={newExternalAd.url}
                          onChange={(e) => setNewExternalAd((prev) => ({ ...prev, url: e.target.value }))}
                          className="bg-white/10 border-white/20 text-white text-sm"
                        />
                        <Input
                          placeholder="Стоимость"
                          type="number"
                          value={newExternalAd.cost}
                          onChange={(e) => setNewExternalAd((prev) => ({ ...prev, cost: e.target.value }))}
                          className="bg-white/10 border-white/20 text-white text-sm"
                        />

                        <div className="flex gap-2">
                          <Button
                            size="sm"
                            onClick={() =>
                              selectedProduct &&
                              handleAddExternalAdLocal(
                                `new-product-${day.date}-${selectedProduct.nmId}`,
                                day.date,
                                selectedProduct.nmId.toString(),
                              )
                            }
                            className="bg-green-600 hover:bg-green-700 text-white text-sm flex-1"
                          >
                            Создать рекламу
                          </Button>
                          <Button
                            size="sm"
                            onClick={() => {
                              setShowAddForm(null)
                              setSelectedProduct(null)
                              setNewExternalAd({ name: '', url: '', cost: '' })
                            }}
                            variant="ghost"
                            className="text-white/60 hover:bg-white/10 text-sm"
                          >
                            Отмена
                          </Button>
                        </div>
                      </div>
                    ) : (
                      <button
                        onClick={() => handleShowProductList(day.date)}
                        className="w-full h-8 px-3 bg-gradient-to-r from-green-500/20 to-green-600/20 border border-green-500/30 rounded text-green-300 hover:from-green-500/30 hover:to-green-600/30 hover:border-green-400/50 hover:text-green-200 transition-all duration-200 text-sm flex items-center justify-center gap-2 backdrop-blur-sm"
                      >
                        <Package className="h-4 w-4" />
                        Добавить рекламу для товара
                      </button>
                    )}
                  </div>
                )}
              </div>
            </div>
          )
        })}
      </div>
    </div>
  )
}
