'use client'

import { useQuery, useMutation } from '@apollo/client'
import { BarChart3, PieChart, TrendingUp, Calendar } from 'lucide-react'
import React, { useState, useEffect, useRef, useMemo, useCallback } from 'react'

import { Sidebar } from '@/components/dashboard/sidebar'
import { AdvertisingTab } from '@/components/seller-statistics/advertising-tab'
import { SalesTab } from '@/components/seller-statistics/sales-tab'
import { Card } from '@/components/ui/card'
import { DateRangePicker } from '@/components/ui/date-picker'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { useAuthContext } from '@/contexts/AuthContext'
import { SAVE_SELLER_STATS_CACHE } from '@/graphql/mutations'
import { GET_SELLER_STATS_CACHE } from '@/graphql/queries'
import { useSidebar } from '@/hooks/useSidebar'

const SellerStatisticsDashboard = React.memo(() => {
  const { getSidebarMargin } = useSidebar()
  const { user } = useAuthContext()
  const [selectedPeriod, setSelectedPeriod] = useState('week')
  const [useCustomDates, setUseCustomDates] = useState(false)
  const [startDate, setStartDate] = useState('')
  const [endDate, setEndDate] = useState('')
  const [activeTab, setActiveTab] = useState('sales')

  // Кэш для данных разных периодов и табов
  const [salesCache, setSalesCache] = useState<Map<string, any>>(new Map())
  const [advertisingCache, setAdvertisingCache] = useState<Map<string, any>>(new Map())
  const [isLoadingData, setIsLoadingData] = useState(false)

  // Мутация для сохранения кэша
  const [saveCache] = useMutation(SAVE_SELLER_STATS_CACHE)

  // Создаём ключ для кэша на основе периода и дат
  const getCacheKey = useCallback(() => {
    if (useCustomDates && startDate && endDate) {
      return `custom_${startDate}_${endDate}`
    }
    return selectedPeriod
  }, [useCustomDates, startDate, endDate, selectedPeriod])

  // Проверяем есть ли данные в локальном кэше
  const getCachedData = useCallback((type: 'sales' | 'advertising') => {
    const cache = type === 'sales' ? salesCache : advertisingCache
    const cacheKey = getCacheKey()
    return cache.get(cacheKey)
  }, [salesCache, advertisingCache, getCacheKey])

  // Сохраняем данные в локальный кэш
  const setCachedData = useCallback((type: 'sales' | 'advertising', data: any) => {
    const cacheKey = getCacheKey()
    if (type === 'sales') {
      setSalesCache(new Map(salesCache.set(cacheKey, data)))
    } else {
      setAdvertisingCache(new Map(advertisingCache.set(cacheKey, data)))
    }
  }, [salesCache, advertisingCache, getCacheKey])

  // Запрос кэша из БД
  const { data: cacheData, refetch: refetchCache } = useQuery(GET_SELLER_STATS_CACHE, {
    variables: {
      period: useCustomDates ? 'custom' : selectedPeriod,
      dateFrom: useCustomDates ? startDate : undefined,
      dateTo: useCustomDates ? endDate : undefined,
    },
    skip: !user?.organization,
    fetchPolicy: 'cache-first',
    errorPolicy: 'ignore',
  })

  // Загружаем данные из кэша БД при изменении периода
  useEffect(() => {
    if (cacheData?.getSellerStatsCache?.success && cacheData.getSellerStatsCache.cache) {
      const cache = cacheData.getSellerStatsCache.cache
      const cacheKey = getCacheKey()

      // Проверяем не истёк ли кэш (24 часа)
      const expiresAt = new Date(cache.expiresAt)
      const now = new Date()

      if (expiresAt > now) {
        // Кэш актуален, загружаем данные
        if (cache.productsData) {
          setSalesCache(new Map(salesCache.set(cacheKey, JSON.parse(cache.productsData))))
        }
        if (cache.advertisingData) {
          setAdvertisingCache(new Map(advertisingCache.set(cacheKey, JSON.parse(cache.advertisingData))))
        }
      }
    }
  }, [cacheData, selectedPeriod, useCustomDates, startDate, endDate])

  // Сохраняем данные в БД кэш
  const saveToCacheDB = useCallback(async (type: 'sales' | 'advertising', data: any) => {
    try {
      const cacheKey = getCacheKey()
      const expiresAt = new Date()
      expiresAt.setHours(expiresAt.getHours() + 24) // 24 часа

      const input: any = {
        period: useCustomDates ? 'custom' : selectedPeriod,
        dateFrom: useCustomDates ? startDate : null,
        dateTo: useCustomDates ? endDate : null,
        expiresAt: expiresAt.toISOString(),
      }

      if (type === 'sales') {
        input.productsData = JSON.stringify(data)
        input.productsTotalSales = data.totalSales || 0
        input.productsTotalOrders = data.totalOrders || 0
        input.productsCount = data.productsCount || 0
      } else {
        input.advertisingData = JSON.stringify(data)
        input.advertisingTotalCost = data.totalCost || 0
        input.advertisingTotalViews = data.totalViews || 0
        input.advertisingTotalClicks = data.totalClicks || 0
      }

      await saveCache({ variables: { input } })
      console.warn(`Cached ${type} data saved to DB for period ${cacheKey}`)
    } catch (error) {
      console.error(`Error saving ${type} cache:`, error)
    }
  }, [saveCache, getCacheKey, useCustomDates, selectedPeriod, startDate, endDate])

  return (
    <div className="h-screen flex overflow-hidden">
      {/* Sidebar рендерится через AppShell, не дублируем здесь */}
      <main className={`flex-1 ${getSidebarMargin()} px-4 py-4 overflow-hidden transition-all duration-300`}>
        <div className="h-full w-full flex flex-col">
          {/* Убираем ограничение по ширине для полного использования экрана */}

          {/* Основной контент с табами */}
          <div className="flex-1 overflow-hidden">
            <Tabs value={activeTab} onValueChange={setActiveTab} className="h-full flex flex-col">
              <TabsList className="grid w-full grid-cols-3 bg-white/5 backdrop-blur border border-white/10 rounded-xl flex-shrink-0 h-11">
                <TabsTrigger
                  value="sales"
                  className="data-[state=active]:bg-white/20 data-[state=active]:text-white text-white/60 flex items-center gap-2 text-sm rounded-lg"
                >
                  <BarChart3 className="h-4 w-4" />
                  Продажи
                </TabsTrigger>
                <TabsTrigger
                  value="advertising"
                  className="data-[state=active]:bg-white/20 data-[state=active]:text-white text-white/60 flex items-center gap-2 text-sm rounded-lg"
                >
                  <TrendingUp className="h-4 w-4" />
                  Реклама
                </TabsTrigger>
                <TabsTrigger
                  value="other"
                  className="data-[state=active]:bg-white/20 data-[state=active]:text-white text-white/60 flex items-center gap-2 text-sm rounded-lg"
                >
                  <PieChart className="h-4 w-4" />
                  Иное
                </TabsTrigger>
              </TabsList>

              {/* Контент вкладок */}
              <div className="flex-1 overflow-hidden mt-3">
                <TabsContent value="sales" className="h-full m-0 overflow-hidden">
                  <SalesTab
                    selectedPeriod={selectedPeriod}
                    useCustomDates={useCustomDates}
                    startDate={startDate}
                    endDate={endDate}
                    onPeriodChange={setSelectedPeriod}
                    onUseCustomDatesChange={setUseCustomDates}
                    // Передаём функции для работы с кэшем
                    getCachedData={useCallback(() => getCachedData('sales'), [getCachedData])}
                    setCachedData={useCallback((data) => {
                      setCachedData('sales', data)
                      saveToCacheDB('sales', data)
                    }, [setCachedData, saveToCacheDB])}
                    isLoadingData={isLoadingData}
                    setIsLoadingData={setIsLoadingData}
                  />
                </TabsContent>

                <TabsContent value="advertising" className="h-full m-0 overflow-hidden">
                  <AdvertisingTab
                    selectedPeriod={selectedPeriod}
                    useCustomDates={useCustomDates}
                    startDate={startDate}
                    endDate={endDate}
                    // Передаём функции для работы с кэшем
                    getCachedData={useCallback(() => getCachedData('advertising'), [getCachedData])}
                    setCachedData={useCallback((data) => {
                      setCachedData('advertising', data)
                      saveToCacheDB('advertising', data)
                    }, [setCachedData, saveToCacheDB])}
                    isLoadingData={isLoadingData}
                    setIsLoadingData={setIsLoadingData}
                  />
                </TabsContent>

                <TabsContent value="other" className="h-full m-0 overflow-hidden">
                  <Card className="glass-card h-full overflow-hidden p-6">
                    <div className="flex items-center justify-center h-full">
                      <div className="text-center">
                        <PieChart 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">Раздел в разработке</p>
                      </div>
                    </div>
                  </Card>
                </TabsContent>
              </div>
            </Tabs>
          </div>
        </div>
      </main>
    </div>
  )
})

SellerStatisticsDashboard.displayName = 'SellerStatisticsDashboard'

export { SellerStatisticsDashboard }
