'use client'

import { useLazyQuery, useMutation, useQuery } from '@apollo/client'
import {
    AlertCircle,
    BarChart3,
    Eye,
    Minimize2,
    TrendingUp
} from 'lucide-react'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
    Bar,
    BarChart,
    CartesianGrid,
    ResponsiveContainer,
    XAxis,
    YAxis
} from 'recharts'

import { Alert, AlertDescription } from '@/components/ui/alert'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { ChartTooltip } from '@/components/ui/chart'
import { Checkbox } from '@/components/ui/checkbox'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Skeleton } from '@/components/ui/skeleton'
import {
    CREATE_EXTERNAL_AD,
    DELETE_EXTERNAL_AD,
    UPDATE_EXTERNAL_AD,
    UPDATE_EXTERNAL_AD_CLICKS,
} from '@/graphql/mutations'
import { GET_EXTERNAL_ADS, GET_WILDBERRIES_CAMPAIGN_STATS, GET_WILDBERRIES_CAMPAIGNS_LIST } from '@/graphql/queries'
import { useAuth } from '@/hooks/useAuth'
import { WildberriesService } from '@/services/wildberries-service'

// Импортируем новую простую таблицу
import { SimpleAdvertisingTable } from './simple-advertising-table'

// Интерфейсы для новой структуры таблицы
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 CampaignStatsProps {
  selectedPeriod: string
  useCustomDates: boolean
  startDate: string
  endDate: string
  // Новые пропсы для работы с кэшем
  getCachedData?: () => any
  setCachedData?: (data: any) => void
  isLoadingData?: boolean
  setIsLoadingData?: (loading: boolean) => void
}

// Интерфейсы для API данных
interface GeneratedLink {
  id: string
  adId: string
  adName: string
  targetUrl: string
  trackingUrl: string
  clicks: number
  createdAt: string
}

interface CampaignProduct {
  views: number
  clicks: number
  ctr: number
  cpc: number
  sum: number
  atbs: number
  orders: number
  cr: number
  shks: number
  sum_price: number
  name: string
  nmId: number
}

interface CampaignApp {
  views: number
  clicks: number
  ctr: number
  cpc: number
  sum: number
  atbs: number
  orders: number
  cr: number
  shks: number
  sum_price: number
  appType: number
  nm: CampaignProduct[]
}

interface CampaignDay {
  date: string
  views: number
  clicks: number
  ctr: number
  cpc: number
  sum: number
  atbs: number
  orders: number
  cr: number
  shks: number
  sum_price: number
  apps: CampaignApp[]
}

interface BoosterStat {
  date: string
  nm: number
  avg_position: number
}

interface CampaignInterval {
  begin: string
  end: string
}

interface CampaignStats {
  advertId: number
  views: number
  clicks: number
  ctr: number
  cpc: number
  sum: number
  atbs: number
  orders: number
  cr: number
  shks: number
  sum_price: number
  interval?: CampaignInterval
  days: CampaignDay[]
  boosterStats: BoosterStat[]
}

interface CampaignListItem {
  advertId: number
  changeTime: string
}

interface CampaignGroup {
  type: number
  status: number
  count: number
  advert_list: CampaignListItem[]
}

interface CampaignsListData {
  adverts: CampaignGroup[]
  all: number
}

// Компонент компактного селектора кампаний
const CompactCampaignSelector = ({
  onCampaignsSelected,
  selectedCampaigns,
  loading: statsLoading,
}: {
  onCampaignsSelected: (ids: number[]) => void
  selectedCampaigns: number[]
  loading: boolean
}) => {
  const [isExpanded, setIsExpanded] = useState(true) // Автоматически разворачиваем для удобства
  const [showManualInput, setShowManualInput] = useState(false)
  const [manualIds, setManualIds] = useState('')
  const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set(selectedCampaigns))
  const [filterType, setFilterType] = useState<number | 'all'>('all')
  const [filterStatus, setFilterStatus] = useState<number | 'all'>('all')

  const {
    data: campaignsData,
    loading,
    error,
  } = useQuery(GET_WILDBERRIES_CAMPAIGNS_LIST, {
    errorPolicy: 'all',
  })

  const campaigns = campaignsData?.getWildberriesCampaignsList?.data?.adverts || []

  // Автоматически выбираем все доступные кампании при загрузке данных
  useEffect(() => {
    if (campaigns.length > 0 && selectedIds.size === 0) {
      const allCampaigns = campaigns.flatMap((group: CampaignGroup) =>
        group.advert_list.map((item: CampaignListItem) => item.advertId),
      )

      if (allCampaigns.length > 0) {
        setSelectedIds(new Set(allCampaigns))
        // Автоматически загружаем статистику для всех кампаний
        onCampaignsSelected(allCampaigns)
      }
    }
  }, [campaigns, onCampaignsSelected])

  // Функции для получения названий типов и статусов
  const getCampaignTypeName = (type: number) => {
    const types: Record<number, string> = {
      4: 'Авто',
      5: 'Фразы',
      6: 'Предмет',
      7: 'Бренд',
      8: 'Медиа',
      9: 'Карусель',
    }
    return types[type] || `Тип ${type}`
  }

  const getCampaignStatusName = (status: number) => {
    const statuses: Record<number, string> = {
      7: 'Завершена',
      8: 'Отклонена',
      9: 'Активна',
      11: 'На паузе',
    }
    return statuses[status] || `Статус ${status}`
  }

  const getStatusColor = (status: number) => {
    const colors: Record<number, string> = {
      9: 'text-green-400',
      11: 'text-yellow-400',
      7: 'text-gray-400',
      8: 'text-red-400',
    }
    return colors[status] || 'text-white'
  }

  // Фильтрация кампаний
  const filteredCampaigns = campaigns.filter(
    (group: CampaignGroup) =>
      (filterType === 'all' || group.type === filterType) && (filterStatus === 'all' || group.status === filterStatus),
  )

  const handleCampaignToggle = (campaignId: number) => {
    const newSelected = new Set(selectedIds)
    if (newSelected.has(campaignId)) {
      newSelected.delete(campaignId)
    } else {
      newSelected.add(campaignId)
    }
    setSelectedIds(newSelected)
  }

  const handleSelectAll = (group: CampaignGroup) => {
    const newSelected = new Set(selectedIds)
    const groupIds = group.advert_list.map((item: CampaignListItem) => item.advertId)
    const allSelected = groupIds.every((id: number) => newSelected.has(id))

    if (allSelected) {
      groupIds.forEach((id) => newSelected.delete(id))
    } else {
      groupIds.forEach((id) => newSelected.add(id))
    }
    setSelectedIds(newSelected)
  }

  const handleApplySelection = () => {
    if (showManualInput && manualIds.trim()) {
      const ids = manualIds
        .split(',')
        .map((id) => parseInt(id.trim()))
        .filter((id) => !isNaN(id))
      onCampaignsSelected(ids)
    } else {
      onCampaignsSelected(Array.from(selectedIds))
    }
  }

  const uniqueTypes = [...new Set(campaigns.map((group: CampaignGroup) => group.type))] as number[]
  const uniqueStatuses = [...new Set(campaigns.map((group: CampaignGroup) => group.status))] as number[]

  return (
    <Card className="glass-card p-3">
      <div className="space-y-3">
        {/* Компактный заголовок */}
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setIsExpanded(!isExpanded)}
              className="h-7 px-2 text-white hover:bg-white/10"
            >
              {isExpanded ? <Minimize2 className="h-3 w-3" /> : <BarChart3 className="h-3 w-3" />}
              <span className="ml-1 text-sm">Кампании</span>
            </Button>
            <Badge variant="outline" className="border-white/20 text-white text-xs">
              {selectedIds.size}
            </Badge>
          </div>

          <div className="flex items-center gap-1">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setShowManualInput(!showManualInput)}
              className="h-7 px-2 text-xs text-white/60 hover:bg-white/10"
            >
              {showManualInput ? 'Список' : 'Ручной'}
            </Button>
            <Button
              onClick={handleApplySelection}
              disabled={statsLoading || (showManualInput ? !manualIds.trim() : selectedIds.size === 0)}
              size="sm"
              className="h-7 px-3 bg-blue-600 hover:bg-blue-700 text-white text-xs"
            >
              {statsLoading ? (
                <div className="animate-spin rounded-full h-3 w-3 border-b border-white" />
              ) : (
                <>
                  <Eye className="h-3 w-3 mr-1" />
                  {selectedIds.size > 0 ? `Загрузить (${selectedIds.size})` : 'Выбрать'}
                </>
              )}
            </Button>
          </div>
        </div>

        {/* Развернутый контент */}
        {isExpanded && (
          <div className="space-y-3">
            {showManualInput ? (
              <Input
                placeholder="ID через запятую: 12345, 67890"
                value={manualIds}
                onChange={(e) => setManualIds(e.target.value)}
                className="h-8 bg-white/5 border-white/20 text-white placeholder:text-white/40 text-xs"
              />
            ) : (
              <div className="space-y-3">
                {/* Компактные фильтры */}
                <div className="flex items-center gap-2 text-xs">
                  <select
                    value={filterType}
                    onChange={(e) => setFilterType(e.target.value === 'all' ? 'all' : parseInt(e.target.value))}
                    className="h-7 bg-white/5 border border-white/20 rounded px-2 text-white text-xs"
                  >
                    <option value="all">Все типы</option>
                    {uniqueTypes.map((type: number) => (
                      <option key={type} value={type}>
                        {getCampaignTypeName(type)}
                      </option>
                    ))}
                  </select>

                  <select
                    value={filterStatus}
                    onChange={(e) => setFilterStatus(e.target.value === 'all' ? 'all' : parseInt(e.target.value))}
                    className="h-7 bg-white/5 border border-white/20 rounded px-2 text-white text-xs"
                  >
                    <option value="all">Все статусы</option>
                    {uniqueStatuses.map((status: number) => (
                      <option key={status} value={status}>
                        {getCampaignStatusName(status)}
                      </option>
                    ))}
                  </select>
                </div>

                {/* Компактный список кампаний */}
                {loading ? (
                  <Skeleton className="h-20 bg-white/10" />
                ) : error ? (
                  <Alert className="bg-red-500/10 border-red-500/30 text-red-400 py-2">
                    <AlertCircle className="h-3 w-3" />
                    <AlertDescription className="text-xs">Ошибка: {error.message}</AlertDescription>
                  </Alert>
                ) : (
                  <div className="max-h-32 overflow-y-auto space-y-2">
                    {filteredCampaigns.map((group: CampaignGroup) => (
                      <div key={`${group.type}-${group.status}`} className="bg-white/5 rounded p-2">
                        <div className="flex items-center justify-between mb-1">
                          <div className="flex items-center gap-2">
                            <Checkbox
                              checked={group.advert_list.every((item) => selectedIds.has(item.advertId))}
                              onCheckedChange={() => handleSelectAll(group)}
                              className="h-3 w-3"
                            />
                            <span className="text-xs font-medium text-white">{getCampaignTypeName(group.type)}</span>
                            <span className={`text-xs ${getStatusColor(group.status)}`}>
                              {getCampaignStatusName(group.status)}
                            </span>
                            <Badge variant="outline" className="border-white/20 text-white text-xs px-1 py-0">
                              {group.count}
                            </Badge>
                          </div>
                        </div>

                        <div className="grid grid-cols-4 gap-1 ml-4">
                          {group.advert_list.map((campaign) => (
                            <div
                              key={campaign.advertId}
                              className="flex items-center gap-1 p-1 bg-white/5 rounded cursor-pointer hover:bg-white/10 text-xs"
                              onClick={() => handleCampaignToggle(campaign.advertId)}
                            >
                              <Checkbox
                                checked={selectedIds.has(campaign.advertId)}
                                onCheckedChange={() => handleCampaignToggle(campaign.advertId)}
                                className="h-3 w-3"
                              />
                              <span className="text-white truncate">#{campaign.advertId}</span>
                            </div>
                          ))}
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            )}
          </div>
        )}
      </div>
    </Card>
  )
}

const AdvertisingTab = React.memo(({ 
  selectedPeriod,
  useCustomDates,
  startDate,
  endDate,
  getCachedData,
  setCachedData,
  isLoadingData,
  setIsLoadingData,
}: CampaignStatsProps) => {
  const { user } = useAuth()

  // Состояния для раскрытия строк
  const [expandedDays, setExpandedDays] = useState<Set<string>>(new Set())
  const [expandedProducts, setExpandedProducts] = useState<Set<string>>(new Set())
  const [expandedCampaigns, setExpandedCampaigns] = useState<Set<number>>(new Set())

  // Состояния для фильтрации графика
  const [showWbAds, setShowWbAds] = useState(true)
  const [showExternalAds, setShowExternalAds] = useState(true)

  // Состояние для формы добавления внешней рекламы
  const [showAddForm, setShowAddForm] = useState<string | null>(null)
  const [newExternalAd, setNewExternalAd] = useState({
    name: '',
    url: '',
    cost: '',
  })

  const [campaignStats, setCampaignStats] = useState<CampaignStats[]>([])
  const [productPhotos, setProductPhotos] = useState<Map<number, string>>(new Map())
  const [dailyData, setDailyData] = useState<DailyAdvertisingData[]>([])
  const [generatedLinksData, setGeneratedLinksData] = useState<Record<string, GeneratedLink[]>>({})
  const prevCampaignStats = useRef<CampaignStats[]>([])

  // Проверяем кэш при изменении периода
  useEffect(() => {
    if (getCachedData) {
      const cachedData = getCachedData()
      if (cachedData) {
        setDailyData(cachedData.dailyData || [])
        setCampaignStats(cachedData.campaignStats || [])
        console.warn('Advertising: Using cached data')
        return
      }
    }
  }, [selectedPeriod, useCustomDates, startDate, endDate, getCachedData])

  // Вычисляем диапазон дат для запроса внешней рекламы
  const getDateRange = () => {
    if (useCustomDates && startDate && endDate) {
      return { dateFrom: startDate, dateTo: endDate }
    }

    const endDateCalc = new Date()
    const startDateCalc = new Date()

    switch (selectedPeriod) {
      case 'week':
        startDateCalc.setDate(endDateCalc.getDate() - 7)
        break
      case 'month':
        startDateCalc.setMonth(endDateCalc.getMonth() - 1)
        break
      case 'quarter':
        startDateCalc.setMonth(endDateCalc.getMonth() - 3)
        break
    }

    return {
      dateFrom: startDateCalc.toISOString().split('T')[0],
      dateTo: endDateCalc.toISOString().split('T')[0],
    }
  }

  const { dateFrom, dateTo } = getDateRange()

  // GraphQL запросы и мутации
  const {
    data: externalAdsData,
    loading: externalAdsLoading,
    error: externalAdsError,
    refetch: refetchExternalAds,
  } = useQuery(GET_EXTERNAL_ADS, {
    variables: { dateFrom, dateTo },
    skip: !user,
    fetchPolicy: 'cache-and-network',
  })

  const [createExternalAd] = useMutation(CREATE_EXTERNAL_AD, {
    onCompleted: () => {
      refetchExternalAds()
    },
    onError: (error) => {
      console.error('Error creating external ad:', error)
    },
  })

  const [deleteExternalAd] = useMutation(DELETE_EXTERNAL_AD, {
    onCompleted: () => {
      refetchExternalAds()
    },
    onError: (error) => {
      console.error('Error deleting external ad:', error)
    },
  })

  const [updateExternalAd] = useMutation(UPDATE_EXTERNAL_AD, {
    onCompleted: () => {
      refetchExternalAds()
    },
    onError: (error) => {
      console.error('Error updating external ad:', error)
    },
  })

  const [updateExternalAdClicks] = useMutation(UPDATE_EXTERNAL_AD_CLICKS, {
    onError: (error) => {
      console.error('Error updating external ad clicks:', error)
    },
  })

  // Загружаем данные из localStorage только для ссылок (они остаются локальными)
  useEffect(() => {
    if (typeof window !== 'undefined') {
      const savedLinksData = localStorage.getItem('advertisingLinksData')

      if (savedLinksData) {
        try {
          const linksData = JSON.parse(savedLinksData)

          // Удаляем дубликаты ссылок
          const cleanedLinksData: Record<string, GeneratedLink[]> = {}
          Object.keys(linksData).forEach((date) => {
            const uniqueLinks = new Map<string, GeneratedLink>()
            linksData[date].forEach((link: GeneratedLink) => {
              const key = `${link.adId}-${link.adName}`
              if (!uniqueLinks.has(key) || link.clicks > (uniqueLinks.get(key)?.clicks || 0)) {
                uniqueLinks.set(key, link)
              }
            })
            cleanedLinksData[date] = Array.from(uniqueLinks.values())
          })

          setGeneratedLinksData(cleanedLinksData)
          localStorage.setItem('advertisingLinksData', JSON.stringify(cleanedLinksData))
        } catch (error) {
          console.error('Error loading links data:', error)
        }
      }
    }
  }, [])

  // Загружаем статистику кликов
  const loadClickStatistics = async () => {
    try {
      const response = await fetch('/api/track-click')
      const clickStats = await response.json()

      // Получаем свежие данные из localStorage
      const savedLinksData = localStorage.getItem('advertisingLinksData')
      const currentLinksData = savedLinksData ? JSON.parse(savedLinksData) : {}

      // Обновляем счетчики кликов в ссылках
      setGeneratedLinksData((prev) => {
        const updated = { ...prev }
        Object.keys(updated).forEach((date) => {
          updated[date] = updated[date].map((link) => ({
            ...link,
            clicks: clickStats[link.id] || link.clicks,
          }))
        })

        // Сохраняем обновленные ссылки
        localStorage.setItem('advertisingLinksData', JSON.stringify(updated))
        return updated
      })

      // Обновляем клики в базе данных для внешней рекламы
      if (externalAdsData?.getExternalAds?.success && externalAdsData.getExternalAds.externalAds) {
        const promises = (externalAdsData.getExternalAds.externalAds as Array<{ id: string; clicks: number }>).map(
          (ad) => {
            // Находим соответствующую ссылку для этой рекламы
            const allLinks: GeneratedLink[] = Object.values(currentLinksData).flat() as GeneratedLink[]
            const adLink = allLinks.find((link) => link.adId === ad.id)

            if (adLink && clickStats[adLink.id] && clickStats[adLink.id] !== ad.clicks) {
              // Обновляем клики в БД только если они изменились
              return updateExternalAdClicks({
                variables: {
                  id: ad.id,
                  clicks: clickStats[adLink.id],
                },
              }).catch((error: unknown) => {
                console.error(`Error updating clicks for ad ${ad.id}:`, error)
              })
            }
            return Promise.resolve()
          },
        )

        await Promise.all(promises)

        // Обновляем данные внешней рекламы после синхронизации
        refetchExternalAds()
      }
    } catch (error) {
      console.error('Error loading click statistics:', error)
    }
  }

  // Загружаем статистику кликов периодически
  useEffect(() => {
    loadClickStatistics()
    const interval = setInterval(loadClickStatistics, 10000) // каждые 10 секунд
    return () => clearInterval(interval)
  }, [])

  const { data: campaignsData, loading: campaignsLoading } = useQuery(GET_WILDBERRIES_CAMPAIGNS_LIST, {
    errorPolicy: 'all',
  })

  const [getCampaignStats, { loading, error }] = useLazyQuery(GET_WILDBERRIES_CAMPAIGN_STATS, {
    onCompleted: (data) => {
      if (data.getWildberriesCampaignStats.success) {
        setCampaignStats(data.getWildberriesCampaignStats.data)
      }
    },
    onError: (error) => {
      console.error('Campaign stats error:', error)
    },
  })

  // Загрузка фотографий товаров (точно как на складе WB)
  const loadProductPhotos = async (nmIds: number[]) => {
    if (!user?.organization?.apiKeys?.find((key) => key.marketplace === 'WILDBERRIES')?.isActive) {
      return
    }

    try {
      const wbApiKey = user?.organization?.apiKeys?.find((key) => key.marketplace === 'WILDBERRIES')

      if (!wbApiKey?.isActive) {
        console.error('Advertising: API ключ Wildberries не настроен')
        return
      }

      const validationData = wbApiKey.validationData as Record<string, string>
      const apiToken =
        validationData?.token ||
        validationData?.apiKey ||
        validationData?.key ||
        (wbApiKey as { apiKey?: string }).apiKey

      if (!apiToken) {
        console.error('Advertising: Токен API не найден')
        return
      }

      console.warn('Advertising: Loading product photos...')

      // Используем точно тот же метод что и на складе
      const cards = await WildberriesService.getAllCards(apiToken).catch(() => [])
      console.warn('Advertising: Loaded cards:', cards.length)

      if (cards.length === 0) {
        console.error('Advertising: Нет карточек товаров в WB')
        return
      }

      const newPhotos = new Map<number, string>()
      const uniqueNmIds = [...new Set(nmIds)]

      cards.forEach((card) => {
        if (uniqueNmIds.includes(card.nmID) && card.photos && Array.isArray(card.photos) && card.photos.length > 0) {
          const photo = card.photos[0]
          const photoUrl = photo.big || photo.c516x688 || photo.c246x328 || photo.tm || photo.square
          if (photoUrl) {
            newPhotos.set(card.nmID, photoUrl)
            console.warn(`Advertising: Found photo for ${card.nmID}: ${photoUrl}`)
          }
        }
      })

      console.warn(`Advertising: Loaded ${newPhotos.size} product photos`)
      setProductPhotos((prev) => new Map([...prev, ...newPhotos]))
    } catch (error) {
      console.error('Advertising: Error loading product photos:', error)
    }
  }

  // Функция запуска загрузки статистики кампаний (стабилизирована)
  const handleCampaignsSelected = useCallback((ids: number[]) => {
    if (ids.length === 0) return

    let campaigns
    if (useCustomDates && startDate && endDate) {
      campaigns = ids.map((id) => ({
        id,
        interval: {
          begin: startDate,
          end: endDate,
        },
      }))
    } else {
      const endDateCalc = new Date()
      const startDateCalc = new Date()

      switch (selectedPeriod) {
        case 'week':
          startDateCalc.setDate(endDateCalc.getDate() - 7)
          break
        case 'month':
          startDateCalc.setMonth(endDateCalc.getMonth() - 1)
          break
        case 'quarter':
          startDateCalc.setMonth(endDateCalc.getMonth() - 3)
          break
      }

      campaigns = ids.map((id) => ({
        id,
        interval: {
          begin: startDateCalc.toISOString().split('T')[0],
          end: endDateCalc.toISOString().split('T')[0],
        },
      }))
    }

    getCampaignStats({
      variables: {
        input: { campaigns },
      },
    })
  }, [useCustomDates, startDate, endDate, selectedPeriod, getCampaignStats])

  // Ключ загрузки для защиты от повторов
  const loadKey = useMemo(
    () => (useCustomDates && startDate && endDate ? `custom_${startDate}_${endDate}` : selectedPeriod),
    [useCustomDates, startDate, endDate, selectedPeriod],
  )
  const fetchingRef = useRef(false)
  const lastLoadedKeyRef = useRef<string | null>(null)

  // Автозагрузка всех кампаний для выбранного периода (однократно на ключ)
  useEffect(() => {
    const adverts = campaignsData?.getWildberriesCampaignsList?.data?.adverts
    if (!adverts) return
    if (fetchingRef.current) return
    if (lastLoadedKeyRef.current === loadKey) return

    const allCampaignIds = adverts.flatMap((group: CampaignGroup) =>
      group.advert_list.map((item: CampaignListItem) => item.advertId),
    )
    if (allCampaignIds.length === 0) return

    fetchingRef.current = true
    handleCampaignsSelected(allCampaignIds)
    lastLoadedKeyRef.current = loadKey
    fetchingRef.current = false
  }, [campaignsData, loadKey, handleCampaignsSelected])

  // Преобразование данных кампаний в новый формат таблицы
  const convertCampaignDataToDailyData = (campaigns: CampaignStats[]): DailyAdvertisingData[] => {
    const dailyMap = new Map<string, DailyAdvertisingData>()

    campaigns.forEach((campaign) => {
      campaign.days.forEach((day) => {
        const dateKey = day.date.split('T')[0] // Получаем только дату без времени

        if (!dailyMap.has(dateKey)) {
          dailyMap.set(dateKey, {
            date: dateKey,
            totalSum: 0,
            totalOrders: 0,
            totalRevenue: 0,
            products: [],
          })
        }

        const dailyRecord = dailyMap.get(dateKey)!

        // Добавляем товары с их рекламными кампаниями
        if (day.apps) {
          day.apps.forEach((app) => {
            if (app.nm) {
              app.nm.forEach((product) => {
                let existingProduct = dailyRecord.products.find((p) => p.nmId === product.nmId)

                if (!existingProduct) {
                  // Создаем новый товар
                  existingProduct = {
                    nmId: product.nmId,
                    name: product.name,
                    totalViews: 0,
                    totalClicks: 0,
                    totalCost: 0,
                    totalOrders: 0,
                    totalRevenue: 0,
                    advertising: {
                      wbCampaigns: [],
                      externalAds: [],
                    },
                  }
                  dailyRecord.products.push(existingProduct)
                }

                // Суммируем данные товара
                existingProduct.totalViews += product.views
                existingProduct.totalClicks += product.clicks
                existingProduct.totalCost += product.sum
                existingProduct.totalOrders += product.orders
                existingProduct.totalRevenue += product.sum_price

                // Добавляем данные ВБ кампании для этого товара
                const existingCampaign = existingProduct.advertising.wbCampaigns.find(
                  (c) => c.campaignId === campaign.advertId,
                )
                if (existingCampaign) {
                  existingCampaign.views += product.views
                  existingCampaign.clicks += product.clicks
                  existingCampaign.cost += product.sum
                  existingCampaign.orders += product.orders
                } else {
                  existingProduct.advertising.wbCampaigns.push({
                    campaignId: campaign.advertId,
                    views: product.views,
                    clicks: product.clicks,
                    cost: product.sum,
                    orders: product.orders,
                  })
                }
              })
            }
          })
        }
      })
    })

    // После создания структуры товаров, добавляем внешнюю рекламу из GraphQL данных
    const result = Array.from(dailyMap.values())

    if (externalAdsData?.getExternalAds?.success && externalAdsData.getExternalAds.externalAds) {
      // Сначала обрабатываем существующие дни
      result.forEach((day) => {
        const externalAdsForDay = externalAdsData.getExternalAds.externalAds.filter(
          (ad: ExternalAd & { date: string; nmId: string }) => ad.date === day.date,
        )

        if (externalAdsForDay.length > 0) {
          // Группируем внешнюю рекламу по nmId товара
          const adsByProduct = externalAdsForDay.reduce(
            (acc: Record<string, ExternalAd[]>, ad: ExternalAd & { date: string; nmId: string }) => {
              if (!acc[ad.nmId]) acc[ad.nmId] = []
              acc[ad.nmId].push({
                id: ad.id,
                name: ad.name,
                url: ad.url,
                cost: ad.cost,
                clicks: ad.clicks || 0,
              })
              return acc
            },
            {},
          )

          // Добавляем внешнюю рекламу к соответствующим товарам или создаем новые товары
          Object.keys(adsByProduct).forEach((nmIdStr) => {
            const nmId = parseInt(nmIdStr)
            let existingProduct = day.products.find((p) => p.nmId === nmId)

            if (!existingProduct) {
              // Создаем новый товар только с внешней рекламой
              existingProduct = {
                nmId: nmId,
                name: `Товар ${nmId}`, // Будет обновлено при загрузке фотографий
                totalViews: 0,
                totalClicks: 0,
                totalCost: 0,
                totalOrders: 0,
                totalRevenue: 0,
                advertising: {
                  wbCampaigns: [],
                  externalAds: [],
                },
              }
              day.products.push(existingProduct)
            }

            existingProduct.advertising.externalAds = adsByProduct[nmIdStr]
          })
        }
      })

      // Теперь обрабатываем дни, которых нет в ВБ кампаниях, но есть внешняя реклама
      const existingDates = new Set(result.map((day) => day.date))
      const externalAdsByDate = externalAdsData.getExternalAds.externalAds.reduce(
        (
          acc: Record<string, Array<ExternalAd & { date: string; nmId: string }>>,
          ad: ExternalAd & { date: string; nmId: string },
        ) => {
          if (!acc[ad.date]) acc[ad.date] = []
          acc[ad.date].push(ad)
          return acc
        },
        {},
      )

      Object.keys(externalAdsByDate).forEach((dateStr) => {
        if (!existingDates.has(dateStr)) {
          // Создаем новый день только с товарами, у которых есть внешняя реклама
          const newDay: DailyAdvertisingData = {
            date: dateStr,
            totalSum: 0,
            totalOrders: 0,
            totalRevenue: 0,
            products: [],
          }

          // Группируем внешнюю рекламу по nmId товара
          const adsByProduct = externalAdsByDate[dateStr].reduce((acc: Record<string, ExternalAd[]>, ad) => {
            if (!acc[ad.nmId]) acc[ad.nmId] = []
            acc[ad.nmId].push({
              id: ad.id,
              name: ad.name,
              url: ad.url,
              cost: ad.cost,
              clicks: ad.clicks || 0,
            })
            return acc
          }, {})

          // Создаем товары с внешней рекламой
          Object.keys(adsByProduct).forEach((nmIdStr) => {
            const nmId = parseInt(nmIdStr)
            const product: ProductData = {
              nmId: nmId,
              name: `Товар ${nmId}`, // Будет обновлено при загрузке фотографий
              totalViews: 0,
              totalClicks: 0,
              totalCost: 0,
              totalOrders: 0,
              totalRevenue: 0,
              advertising: {
                wbCampaigns: [],
                externalAds: adsByProduct[nmIdStr],
              },
            }
            newDay.products.push(product)
          })

          result.push(newDay)
        }
      })
    }

    // Обновляем общие суммы дня (ВБ реклама + внешняя реклама)
    result.forEach((day) => {
      day.totalSum = day.products.reduce(
        (sum, product) =>
          sum + product.totalCost + product.advertising.externalAds.reduce((adSum, ad) => adSum + ad.cost, 0),
        0,
      )
      day.totalOrders = day.products.reduce((sum, product) => sum + product.totalOrders, 0)
      day.totalRevenue = day.products.reduce((sum, product) => sum + product.totalRevenue, 0)
    })

    return result.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
  }

  // Загружаем фотографии когда получаем статистику кампаний
  useEffect(() => {
    if (campaignStats.length > 0) {
      const nmIds = campaignStats
        .flatMap((campaign) => campaign.days)
        .flatMap((day) => day.apps?.flatMap((app) => app.nm) || [])
        .map((product) => product.nmId)

      // Проверяем, есть ли новые nmIds, которых еще нет в productPhotos
      const newNmIds = nmIds.filter((nmId) => !productPhotos.has(nmId))

      if (newNmIds.length > 0) {
        console.warn('Loading photos for new products:', newNmIds.length)
        loadProductPhotos(newNmIds)
      }

      // Преобразуем данные в новый формат только если это первая загрузка или изменились кампании/внешняя реклама
      if (
        dailyData.length === 0 ||
        JSON.stringify(campaignStats) !== JSON.stringify(prevCampaignStats.current) ||
        externalAdsData
      ) {
        const newDailyData = convertCampaignDataToDailyData(campaignStats)
        setDailyData(newDailyData)
        prevCampaignStats.current = campaignStats

        // Сохраняем данные в кэш (через ref, чтобы не зациклиться на изменении ссылки функции)
        if (setCachedDataRef.current) {
          const cacheData = {
            dailyData: newDailyData,
            campaignStats: campaignStats,
            totalCost: newDailyData.reduce((sum, day) => sum + day.totalSum, 0),
            totalViews: newDailyData.reduce(
              (sum, day) => sum + day.products.reduce((daySum, product) => daySum + product.totalViews, 0),
              0,
            ),
            totalClicks: newDailyData.reduce(
              (sum, day) => sum + day.products.reduce((daySum, product) => daySum + product.totalClicks, 0),
              0,
            ),
          }
          setCachedDataRef.current(cacheData)
          console.warn('Advertising: Data cached successfully')
        }
      }
    }
  }, [campaignStats, externalAdsData])

  // Храним setCachedData в ref, чтобы не триггерить эффект из-за смены ссылки на функцию в родителе
  const setCachedDataRef = useRef<typeof setCachedData | undefined>(setCachedData)
  useEffect(() => {
    setCachedDataRef.current = setCachedData
  }, [setCachedData])

  

  const toggleCampaignExpanded = (campaignId: number) => {
    const newExpanded = new Set(expandedCampaigns)
    if (newExpanded.has(campaignId)) {
      newExpanded.delete(campaignId)
    } else {
      newExpanded.add(campaignId)
    }
    setExpandedCampaigns(newExpanded)
  }

  // Обработчики для внешней рекламы
  const handleAddExternalAd = async (date: string, ad: Omit<ExternalAd, 'id'>, nmId?: string) => {
    console.warn('handleAddExternalAd called:', { date, ad, nmId })

    try {
      // Используем переданный nmId или находим из первого товара дня как fallback
      const targetNmId = nmId || dailyData.find((d) => d.date === date)?.products[0]?.nmId?.toString() || '0'

      await createExternalAd({
        variables: {
          input: {
            name: ad.name,
            url: ad.url,
            cost: ad.cost,
            date: date,
            nmId: targetNmId,
          },
        },
      })

      console.warn('External ad created successfully for nmId:', targetNmId)
    } catch (error) {
      console.error('Error creating external ad:', error)
    }
  }

  const handleRemoveExternalAd = async (date: string, adId: string) => {
    console.warn('handleRemoveExternalAd called:', { date, adId })

    try {
      await deleteExternalAd({
        variables: { id: adId },
      })

      console.warn('External ad deleted successfully')
    } catch (error) {
      console.error('Error deleting external ad:', error)
    }
  }

  const handleUpdateExternalAd = async (date: string, adId: string, updates: Partial<ExternalAd>) => {
    console.warn('handleUpdateExternalAd called:', { date, adId, updates })

    try {
      // Находим текущую рекламу для получения полных данных
      const currentAd = dailyData
        .find((d) => d.date === date)
        ?.products.flatMap((p) => p.advertising.externalAds)
        .find((ad) => ad.id === adId)

      if (!currentAd) {
        console.error('External ad not found')
        return
      }

      // Находим nmId из товара, к которому привязана реклама
      const dayData = dailyData.find((d) => d.date === date)
      const product = dayData?.products.find((p) => p.advertising.externalAds.some((ad) => ad.id === adId))
      const nmId = product?.nmId?.toString() || '0'

      await updateExternalAd({
        variables: {
          id: adId,
          input: {
            name: updates.name || currentAd.name,
            url: updates.url || currentAd.url,
            cost: updates.cost || currentAd.cost,
            date: date,
            nmId: nmId,
          },
        },
      })

      console.warn('External ad updated successfully')
    } catch (error) {
      console.error('Error updating external ad:', error)
    }
  }

  // Обработчики для ссылок-кликеров
  const handleGenerateLink = (date: string, adId: string, adName: string, adUrl: string) => {
    // Проверяем, есть ли уже ссылка для этой рекламы в этот день
    const existingLinks = generatedLinksData[date] || []
    const existingLink = existingLinks.find((link) => link.adId === adId && link.adName === adName)

    if (existingLink) {
      // Если ссылка уже существует, просто копируем её
      navigator.clipboard.writeText(existingLink.trackingUrl).then(() => {
        alert(`Ссылка уже существует и скопирована!\nПользователи будут переходить на: ${existingLink.targetUrl}`)
      })
      return
    }

    // Валидируем URL
    let validUrl = adUrl.trim()
    if (!validUrl.startsWith('http://') && !validUrl.startsWith('https://')) {
      validUrl = 'https://' + validUrl
    }

    const linkId = `link-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
    const trackedUrl = `${window.location.origin}/track/${linkId}?redirect=${encodeURIComponent(validUrl)}`

    console.warn('Generating link:', {
      linkId,
      originalUrl: adUrl,
      validUrl,
      trackedUrl,
      encodedUrl: encodeURIComponent(validUrl),
    })

    const newLink: GeneratedLink = {
      id: linkId,
      adId,
      adName,
      targetUrl: validUrl,
      trackingUrl: trackedUrl,
      clicks: 0,
      createdAt: new Date().toISOString(),
    }

    setGeneratedLinksData((prev) => {
      const newData = {
        ...prev,
        [date]: [...(prev[date] || []), newLink],
      }
      // Сохраняем данные в localStorage
      localStorage.setItem('advertisingLinksData', JSON.stringify(newData))
      return newData
    })

    // Копируем ссылку в буфер обмена
    navigator.clipboard.writeText(trackedUrl).then(() => {
      console.warn('Ссылка-кликер скопирована в буфер обмена:', trackedUrl)
      alert(`Ссылка скопирована! Вставьте её в рекламу.\nПользователи будут переходить на: ${validUrl}`)
    })
  }

  const handleCopyLink = (linkId: string) => {
    // Найдем ссылку во всех датах
    let linkToCopy: GeneratedLink | undefined
    Object.values(generatedLinksData).forEach((links) => {
      const found = links.find((link) => link.id === linkId)
      if (found) linkToCopy = found
    })

    if (linkToCopy) {
      navigator.clipboard.writeText(linkToCopy.trackingUrl).then(() => {
        console.warn('Ссылка-кликер скопирована в буфер обмена:', linkToCopy!.trackingUrl)
        alert(`Ссылка скопирована! Люди будут переходить на: ${linkToCopy!.targetUrl}`)
      })
    }
  }

  const formatCurrency = (value: number) => {
    return new Intl.NumberFormat('ru-RU', {
      style: 'currency',
      currency: 'RUB',
      minimumFractionDigits: 0,
      maximumFractionDigits: 0,
    }).format(value)
  }

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

  const formatPercent = (value: number) => {
    return `${value.toFixed(2)}%`
  }

  // Подготовка данных для графика с включением внешней рекламы
  const chartData = React.useMemo(() => {
    if (dailyData.length === 0) return []

    return dailyData
      .map((day) => {
        const dayViews = day.products.reduce((sum, product) => sum + product.totalViews, 0)
        const dayClicks = day.products.reduce((sum, product) => sum + product.totalClicks, 0)
        const dayExternalClicks = day.products.reduce(
          (sum, product) => sum + product.advertising.externalAds.reduce((adSum, ad) => adSum + (ad.clicks || 0), 0),
          0,
        )
        const dayOrders = day.totalOrders
        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,
        )

        return {
          date: new Date(day.date).toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit' }),
          views: dayViews,
          clicks: dayClicks + dayExternalClicks,
          wbClicks: dayClicks,
          externalClicks: dayExternalClicks,
          sum: dayWbCost + dayExternalCost,
          wbSum: dayWbCost,
          externalSum: dayExternalCost,
          orders: dayOrders,
        }
      })
      .reverse() // График показывает от старых к новым датам
  }, [dailyData])

  // Подготовка данных для графика расходов с разделением ВБ и внешней рекламы
  const spendingChartData = React.useMemo(() => {
    if (dailyData.length === 0) return []

    return dailyData
      .map((day) => {
        const wbSum = day.products.reduce((sum, product) => sum + product.totalCost, 0)
        const externalSum = day.products.reduce(
          (sum, product) => sum + product.advertising.externalAds.reduce((adSum, ad) => adSum + ad.cost, 0),
          0,
        )

        return {
          date: new Date(day.date).toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit' }),
          wbSum: wbSum,
          externalSum: externalSum,
          sum: wbSum + externalSum, // Общая сумма для совместимости
          fullDate: day.date,
        }
      })
      .sort((a, b) => a.fullDate.localeCompare(b.fullDate))
  }, [dailyData])

  const chartConfig = {
    views: {
      label: 'Показы',
      color: '#8b5cf6',
    },
    clicks: {
      label: 'Клики (общие)',
      color: '#06b6d4',
    },
    wbClicks: {
      label: 'Клики ВБ',
      color: '#06b6d4',
    },
    externalClicks: {
      label: 'Клики внешние',
      color: '#f59e0b',
    },
    sum: {
      label: 'Затраты (общие) ₽',
      color: '#f59e0b',
    },
    wbSum: {
      label: 'Затраты ВБ ₽',
      color: '#3b82f6',
    },
    externalSum: {
      label: 'Затраты внешние ₽',
      color: '#ec4899',
    },
    orders: {
      label: 'Заказы',
      color: '#10b981',
    },
  }

  return (
    <div className="h-full flex flex-col space-y-3 overflow-hidden">
      {/* Ошибки */}
      {error && (
        <Alert className="bg-red-500/10 border-red-500/30 text-red-400 py-2">
          <AlertCircle className="h-3 w-3" />
          <AlertDescription className="text-xs">{error.message}</AlertDescription>
        </Alert>
      )}

      {externalAdsError && (
        <Alert className="bg-red-500/10 border-red-500/30 text-red-400 mb-4">
          <AlertCircle className="h-3 w-3" />
          <AlertDescription className="text-xs">
            Ошибка загрузки внешней рекламы: {externalAdsError.message}
          </AlertDescription>
        </Alert>
      )}

      {/* Результаты */}
      <div className="flex-1 overflow-auto">
        {loading || campaignsLoading || externalAdsLoading ? (
          <div className="space-y-2">
            {[1, 2, 3].map((i) => (
              <Skeleton key={i} className="h-16 bg-white/10" />
            ))}
          </div>
        ) : campaignStats.length > 0 ? (
          <div className="space-y-3">
            {/* График расходов */}
            {spendingChartData.length > 0 && (
              <Card className="glass-card p-3">
                <div className="flex items-center justify-between mb-3">
                  <h3 className="text-sm font-semibold text-white flex items-center gap-2">
                    <BarChart3 className="h-4 w-4" />
                    Расходы на рекламу
                  </h3>
                  <div className="text-xs text-white/60">
                    <div>Общие: {formatCurrency(spendingChartData.reduce((sum, day) => sum + day.sum, 0))}</div>
                    <div className="flex gap-3 mt-1">
                      <span className="flex items-center gap-1">
                        <div className="w-2 h-2 bg-blue-500 rounded"></div>
                        ВБ: {formatCurrency(spendingChartData.reduce((sum, day) => sum + day.wbSum, 0))}
                      </span>
                      <span className="flex items-center gap-1">
                        <div className="w-2 h-2 bg-pink-500 rounded"></div>
                        Внешняя: {formatCurrency(spendingChartData.reduce((sum, day) => sum + day.externalSum, 0))}
                      </span>
                    </div>
                  </div>
                </div>

                {/* Чекбоксы для переключения типов рекламы */}
                <div className="flex items-center gap-4 mb-3 p-2 bg-white/5 rounded">
                  <div className="flex items-center gap-2">
                    <Checkbox id="wb-ads" checked={showWbAds} onCheckedChange={setShowWbAds} className="h-4 w-4" />
                    <Label htmlFor="wb-ads" className="text-xs text-white cursor-pointer flex items-center gap-1">
                      <div className="w-3 h-3 bg-blue-500 rounded"></div>
                      Реклама ВБ
                    </Label>
                  </div>
                  <div className="flex items-center gap-2">
                    <Checkbox
                      id="external-ads"
                      checked={showExternalAds}
                      onCheckedChange={setShowExternalAds}
                      className="h-4 w-4"
                    />
                    <Label htmlFor="external-ads" className="text-xs text-white cursor-pointer flex items-center gap-1">
                      <div className="w-3 h-3 bg-pink-500 rounded"></div>
                      Внешняя реклама
                    </Label>
                  </div>
                </div>

                <div className="h-48">
                  <ResponsiveContainer width="100%" height="100%">
                    <BarChart data={spendingChartData}>
                      <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.1)" />
                      <XAxis dataKey="date" tick={{ fill: 'rgba(255,255,255,0.6)', fontSize: 10 }} axisLine={false} />
                      <YAxis
                        tick={{ fill: 'rgba(255,255,255,0.6)', fontSize: 10 }}
                        axisLine={false}
                        tickFormatter={(value) => `${(value / 1000).toFixed(0)}K₽`}
                      />
                      <ChartTooltip
                        content={({ active, payload, label }) => {
                          if (active && payload && payload.length) {
                            return (
                              <div className="bg-black/80 p-2 rounded border border-white/20">
                                <p className="text-white text-xs">{`Дата: ${label}`}</p>
                                {payload.map((entry, index) => (
                                  <p key={index} className="text-xs" style={{ color: entry.color }}>
                                    {`${entry.name}: ${formatCurrency(entry.value as number)}`}
                                  </p>
                                ))}
                                <p className="text-white text-xs border-t border-white/20 pt-1 mt-1">
                                  {`Общие расходы: ${formatCurrency(
                                    payload.reduce((sum, entry) => sum + (entry.value as number), 0),
                                  )}`}
                                </p>
                              </div>
                            )
                          }
                          return null
                        }}
                      />
                      {showWbAds && (
                        <Bar dataKey="wbSum" fill="#3b82f6" name="ВБ реклама" radius={[2, 2, 0, 0]} opacity={0.8} />
                      )}
                      {showExternalAds && (
                        <Bar
                          dataKey="externalSum"
                          fill="#ec4899"
                          name="Внешняя реклама"
                          radius={[2, 2, 0, 0]}
                          opacity={0.8}
                        />
                      )}
                    </BarChart>
                  </ResponsiveContainer>
                </div>
              </Card>
            )}

            {/* Новая таблица рекламы */}
            <Card className="glass-card p-3">
              <div className="flex items-center justify-between mb-3">
                <h3 className="text-sm font-semibold text-white flex items-center gap-2">
                  <BarChart3 className="h-4 w-4" />
                  Статистика рекламы
                </h3>
                <div className="text-xs text-white/60">{dailyData.length} дней данных</div>
              </div>

              <SimpleAdvertisingTable
                dailyData={dailyData}
                productPhotos={productPhotos}
                generatedLinksData={generatedLinksData}
                onAddExternalAd={handleAddExternalAd}
                onRemoveExternalAd={handleRemoveExternalAd}
                onUpdateExternalAd={handleUpdateExternalAd}
                onGenerateLink={handleGenerateLink}
              />
            </Card>
          </div>
        ) : (
          <Card className="glass-card h-full overflow-hidden p-6">
            <div className="flex items-center justify-center h-full">
              <div className="text-center">
                <TrendingUp className="h-12 w-12 text-white/40 mx-auto mb-4" />
                <h3 className="text-lg font-semibold text-white mb-2">Статистика рекламных кампаний</h3>
                <p className="text-white/60 mb-4">Загружаем статистику по всем доступным кампаниям...</p>
                <p className="text-white/40 text-sm">Поддерживается API Wildberries /adv/v2/fullstats</p>
              </div>
            </div>
          </Card>
        )}
      </div>
    </div>
  )
})

AdvertisingTab.displayName = 'AdvertisingTab'

export { AdvertisingTab }
