"use client"

import React, { useState, useEffect } from 'react'
import { useQuery } from '@apollo/client'
import { gql } from '@apollo/client'
import { Card } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Checkbox } from '@/components/ui/checkbox'
import { Skeleton } from '@/components/ui/skeleton'
import { TrendingUp, Info, BarChart3, ChevronDown, ChevronUp } from 'lucide-react'
import {
  ChartConfig,
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
} from '@/components/ui/chart'
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  ResponsiveContainer,
} from 'recharts'

// GraphQL query для получения статистики WB
const GET_WILDBERRIES_STATISTICS = gql`
  query GetWildberriesStatistics(
    $period: String
    $startDate: String
    $endDate: String
  ) {
    getWildberriesStatistics(
      period: $period
      startDate: $startDate
      endDate: $endDate
    ) {
      success
      message
      data {
        date
        sales
        orders
        advertising
        refusals
        returns
        revenue
        buyoutPercentage
      }
    }
  }
`

interface SalesTabProps {
  selectedPeriod: string
  useCustomDates?: boolean
  startDate?: string
  endDate?: string
  onPeriodChange?: (period: string) => void
  onUseCustomDatesChange?: (useCustom: boolean) => void
}

// Mock данные для графиков
const mockChartData = [
  { date: '01.11', sales: 45, orders: 52, advertising: 32, refusals: 8, returns: 3 },
  { date: '02.11', sales: 35, orders: 41, advertising: 28, refusals: 6, returns: 2 },
  { date: '03.11', sales: 52, orders: 61, advertising: 39, refusals: 9, returns: 4 },
  { date: '04.11', sales: 38, orders: 45, advertising: 31, refusals: 7, returns: 2 },
  { date: '05.11', sales: 58, orders: 69, advertising: 45, refusals: 11, returns: 5 },
  { date: '06.11', sales: 47, orders: 55, advertising: 37, refusals: 8, returns: 3 },
  { date: '07.11', sales: 56, orders: 66, advertising: 42, refusals: 10, returns: 4 },
]

// Конфигурация chart
const chartConfig = {
  sales: {
    label: "Продажи",
    color: "#10b981", // зеленый
  },
  orders: {
    label: "Заказы", 
    color: "#3b82f6", // синий
  },
  advertising: {
    label: "Реклама",
    color: "#f59e0b", // оранжевый
  },
  refusals: {
    label: "Отказы",
    color: "#ef4444", // красный
  },
  returns: {
    label: "Возвраты",
    color: "#8b5cf6", // фиолетовый
  },
} satisfies ChartConfig

// Mock данные для таблицы
const mockTableData = [
  {
    date: '01.11.2024',
    salesUnits: 45,
    buyoutPercentage: 82.2,
    advertising: 320,
    orders: 52,
    refusals: 8,
    returns: 3,
    revenue: 1250
  },
  {
    date: '02.11.2024',
    salesUnits: 35,
    buyoutPercentage: 85.7,
    advertising: 280,
    orders: 41,
    refusals: 6,
    returns: 2,
    revenue: 980
  },
  {
    date: '03.11.2024',
    salesUnits: 52,
    buyoutPercentage: 78.8,
    advertising: 390,
    orders: 61,
    refusals: 9,
    returns: 4,
    revenue: 1450
  },
  {
    date: '04.11.2024',
    salesUnits: 38,
    buyoutPercentage: 84.4,
    advertising: 310,
    orders: 45,
    refusals: 7,
    returns: 2,
    revenue: 1120
  },
  {
    date: '05.11.2024',
    salesUnits: 58,
    buyoutPercentage: 80.6,
    advertising: 450,
    orders: 69,
    refusals: 11,
    returns: 5,
    revenue: 1680
  },
  {
    date: '06.11.2024',
    salesUnits: 47,
    buyoutPercentage: 83.0,
    advertising: 370,
    orders: 55,
    refusals: 8,
    returns: 3,
    revenue: 1350
  },
  {
    date: '07.11.2024',
    salesUnits: 56,
    buyoutPercentage: 81.2,
    advertising: 420,
    orders: 66,
    refusals: 10,
    returns: 4,
    revenue: 1580
  },
]

export function SalesTab({ selectedPeriod, useCustomDates, startDate, endDate, onPeriodChange, onUseCustomDatesChange }: SalesTabProps) {
  // Состояния для чекбоксов фильтрации
  const [visibleMetrics, setVisibleMetrics] = useState({
    sales: true,
    orders: true,
    advertising: true, // Включаем, теперь используем двухосевой график
    refusals: true,
    returns: true,
  })

  // Получаем данные из WB API
  const { data: wbData, loading, error } = useQuery(GET_WILDBERRIES_STATISTICS, {
    variables: useCustomDates 
      ? { startDate, endDate }
      : { period: selectedPeriod },
    errorPolicy: 'all',
    skip: useCustomDates && (!startDate || !endDate) // Не запрашиваем пока не выбраны обе даты
  })

  // Данные для графика и таблицы
  const [chartData, setChartData] = useState<typeof mockChartData>([])
  const [tableData, setTableData] = useState<typeof mockTableData>([])

  useEffect(() => {
    if (wbData?.getWildberriesStatistics?.success && wbData.getWildberriesStatistics.data) {
      const realData = wbData.getWildberriesStatistics.data

      // Улучшенная агрегация с более надежной обработкой дат
      const aggregateByDate = (data: Array<{
        date: string;
        sales: number;
        orders: number;
        advertising: number;
        refusals: number;
        returns: number;
        revenue: number;
        buyoutPercentage: number;
      }>) => {
        const grouped = new Map<string, {
          date: string;
          sales: number;
          orders: number;
          advertising: number;
          refusals: number;
          returns: number;
          revenue: number;
          buyoutPercentages: number[];
        }>()

        data.forEach((item) => {
          // Улучшенная нормализация даты - убираем время и часовой пояс
          let normalizedDate: string
          if (item.date.includes('T')) {
            // Формат: 2025-07-19T03:00:00+03:00 или 2025-07-19T03:00:00
            normalizedDate = item.date.split('T')[0]
          } else if (item.date.includes(' ')) {
            // Формат: 2025-07-19 03:00:00
            normalizedDate = item.date.split(' ')[0]
          } else {
            // Формат: 2025-07-19
            normalizedDate = item.date
          }

          // Дополнительная проверка на корректность формата YYYY-MM-DD
          if (!/^\d{4}-\d{2}-\d{2}$/.test(normalizedDate)) {
            console.warn(`Invalid date format: ${item.date}, normalized: ${normalizedDate}`)
            return
          }

          if (!grouped.has(normalizedDate)) {
            grouped.set(normalizedDate, {
              date: normalizedDate,
              sales: 0,
              orders: 0,
              advertising: 0,
              refusals: 0,
              returns: 0,
              revenue: 0,
              buyoutPercentages: []
            })
          }

          const group = grouped.get(normalizedDate)!
          group.sales += Number(item.sales) || 0
          group.orders += Number(item.orders) || 0
          group.advertising += Number(item.advertising) || 0
          group.refusals += Number(item.refusals) || 0
          group.returns += Number(item.returns) || 0
          group.revenue += Number(item.revenue) || 0
          
          // Собираем все процента выкупа для корректного усреднения
          if (item.buyoutPercentage && item.buyoutPercentage > 0) {
            group.buyoutPercentages.push(Number(item.buyoutPercentage))
          }
        })

        // Преобразуем в финальный формат
        return Array.from(grouped.values()).map(group => ({
          date: group.date,
          sales: group.sales,
          orders: group.orders,
          advertising: group.advertising,
          refusals: group.refusals,
          returns: group.returns,
          revenue: group.revenue,
          buyoutPercentage: group.buyoutPercentages.length > 0 
            ? Math.round(group.buyoutPercentages.reduce((a, b) => a + b, 0) / group.buyoutPercentages.length * 10) / 10
            : group.orders > 0 ? Math.round((group.sales / group.orders) * 100 * 10) / 10 : 0
        }))
      }

      const aggregatedData = aggregateByDate(realData)
      
      // Сортируем по дате (новые сверху)
      const sortedData = aggregatedData.sort((a, b) => 
        new Date(b.date).getTime() - new Date(a.date).getTime()
      )

      // Обновляем данные для графика
      const newChartData = sortedData.map((item) => ({
        date: new Date(item.date).toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit' }),
        sales: item.sales,
        orders: item.orders,
        advertising: Math.round(item.advertising),
        refusals: item.refusals,
        returns: item.returns
      }))

      // Обновляем данные для таблицы
      const newTableData = sortedData.map((item) => ({
        date: new Date(item.date).toLocaleDateString('ru-RU'),
        salesUnits: item.sales,
        buyoutPercentage: item.buyoutPercentage,
        advertising: Math.round(item.advertising),
        orders: item.orders,
        refusals: item.refusals,
        returns: item.returns,
        revenue: Math.round(item.revenue)
      }))
      
      setChartData(newChartData.reverse()) // Для графика - старые даты слева
      setTableData(newTableData) // Для таблицы - новые даты сверху
    }
  }, [wbData])

  // Функция для переключения видимости метрики
  const toggleMetric = (metric: keyof typeof visibleMetrics) => {
    setVisibleMetrics(prev => ({
      ...prev,
      [metric]: !prev[metric]
    }))
  }

  // Проверяем состояние загрузки и данных
  const isLoading = loading || (useCustomDates && (!startDate || !endDate))
  const hasData = tableData.length > 0

  // Состояние для сортировки
  const [sortField, setSortField] = useState<string>('')
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('desc')

  // Состояние для сворачивания графика
  const [isChartCollapsed, setIsChartCollapsed] = useState(false)

  // Функция сортировки
  const handleSort = (field: string) => {
    if (sortField === field) {
      setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc')
    } else {
      setSortField(field)
      setSortDirection('desc')
    }
  }

  // Отсортированные данные таблицы
  const sortedTableData = React.useMemo(() => {
    if (!sortField) return tableData

    return [...tableData].sort((a, b) => {
      let aValue: string | number = a[sortField as keyof typeof a] as string | number
      let bValue: string | number = b[sortField as keyof typeof b] as string | number

      // Для даты используем особую логику
      if (sortField === 'date') {
        aValue = new Date(aValue).getTime()
        bValue = new Date(bValue).getTime()
      }

      if (sortDirection === 'asc') {
        return aValue > bValue ? 1 : -1
      } else {
        return aValue < bValue ? 1 : -1
      }
    })
  }, [tableData, sortField, sortDirection])

  // Вычисляем итоги
  const totals = React.useMemo(() => {
    if (!hasData) {
      return {
        salesUnits: 0,
        buyoutPercentage: 0,
        advertising: 0,
        orders: 0,
        refusals: 0,
        returns: 0,
        revenue: 0
      }
    }

    const totalSales = tableData.reduce((sum, row) => sum + row.salesUnits, 0)
    const totalOrders = tableData.reduce((sum, row) => sum + row.orders, 0)
    
    // ПРАВИЛЬНЫЙ расчёт % выкупа: общие продажи / общие заказы * 100
    const correctBuyoutPercentage = totalOrders > 0 
      ? Math.round((totalSales / totalOrders) * 100 * 10) / 10
      : 0

    return {
      salesUnits: totalSales,
      buyoutPercentage: correctBuyoutPercentage,
      advertising: tableData.reduce((sum, row) => sum + row.advertising, 0),
      orders: totalOrders,
      refusals: tableData.reduce((sum, row) => sum + row.refusals, 0),
      returns: tableData.reduce((sum, row) => sum + row.returns, 0),
      revenue: tableData.reduce((sum, row) => sum + row.revenue, 0)
    }
  }, [tableData, hasData])
  const hasAnyActivity = hasData && tableData.some(row => 
    row.salesUnits > 0 || row.orders > 0 || row.advertising > 0 || row.refusals > 0 || row.returns > 0
  )

  // Если загружается
  if (isLoading) {
    return (
      <div className="h-full flex flex-col space-y-2">
        <Card className="glass-card p-4 flex-shrink-0" style={{ height: '380px' }}>
          <div className="h-full flex flex-col">
            <Skeleton className="h-6 w-48 mb-4" />
            <div className="flex flex-wrap gap-2 mb-4">
              {[1,2,3,4,5].map(i => (
                <Skeleton key={i} className="h-8 w-20" />
              ))}
            </div>
            <Skeleton className="flex-1 w-full" />
          </div>
        </Card>
        <Card className="glass-card p-4 flex-1">
          <Skeleton className="h-6 w-40 mb-4" />
          <div className="space-y-2">
            {[1,2,3,4,5].map(i => (
              <Skeleton key={i} className="h-8 w-full" />
            ))}
          </div>
        </Card>
      </div>
    )
  }

  // Если нет данных или активности
  if (!hasData || !hasAnyActivity) {
    return (
      <div className="h-full flex items-center justify-center">
        <Card className="glass-card p-8 text-center max-w-md">
                          <div className="mb-4 flex justify-center">
                  <TrendingUp className="h-16 w-16 text-white/30" />
                </div>
          <h3 className="text-xl font-semibold text-white mb-2">
            {!hasData ? 'Нет данных' : 'Нет активности'}
          </h3>
          <p className="text-white/60 text-sm">
            {!hasData 
              ? 'За выбранный период данные отсутствуют'
              : 'За выбранный период не было продаж, заказов или рекламной активности'
            }
          </p>
          {error && (
            <div className="mt-4 p-3 bg-red-500/20 border border-red-500/30 rounded-lg">
              <p className="text-red-400 text-xs">Ошибка: {error.message}</p>
            </div>
          )}
        </Card>
      </div>
    )
  }

  return (
    <div className="h-full flex flex-col space-y-2">
      {/* График с фильтрами */}
      <Card 
        className="glass-card p-3 flex-shrink-0 overflow-hidden transition-all duration-300" 
        style={{ height: isChartCollapsed ? 'auto' : '380px' }}
      >
        <div className="h-full flex flex-col min-h-0">
          {/* Заголовок с переключателями периода */}
          <div className="flex items-center justify-between mb-2">
            <div className="flex items-center gap-2">
              <h3 className="text-white font-semibold">Динамика показателей</h3>
              <button
                onClick={() => setIsChartCollapsed(!isChartCollapsed)}
                className="text-white/60 hover:text-white/80 hover:bg-white/10 p-1 rounded transition-all"
                title={isChartCollapsed ? "Развернуть график" : "Свернуть график"}
              >
                {isChartCollapsed ? (
                  <ChevronDown className="w-4 h-4" />
                ) : (
                  <ChevronUp className="w-4 h-4" />
                )}
              </button>
            </div>
            
            {/* Переключатели периода */}
            <div className="flex items-center gap-2">
              <div className="flex gap-1 bg-white/5 backdrop-blur border border-white/10 rounded-lg p-0.5">
                <button
                  onClick={() => {
                    onPeriodChange?.('week')
                    onUseCustomDatesChange?.(false)
                  }}
                  className={`px-2 py-1 rounded text-xs font-medium transition-all duration-200 ${
                    selectedPeriod === 'week' && !useCustomDates
                      ? 'bg-white/20 text-white shadow-sm'
                      : 'text-white/60 hover:bg-white/10 hover:text-white/80'
                  }`}
                >
                  Неделя
                </button>
                <button
                  onClick={() => {
                    onPeriodChange?.('month')
                    onUseCustomDatesChange?.(false)
                  }}
                  className={`px-2 py-1 rounded text-xs font-medium transition-all duration-200 ${
                    selectedPeriod === 'month' && !useCustomDates
                      ? 'bg-white/20 text-white shadow-sm'
                      : 'text-white/60 hover:bg-white/10 hover:text-white/80'
                  }`}
                >
                  Месяц
                </button>
                <button
                  onClick={() => {
                    onPeriodChange?.('quarter')
                    onUseCustomDatesChange?.(false)
                  }}
                  className={`px-2 py-1 rounded text-xs font-medium transition-all duration-200 ${
                    selectedPeriod === 'quarter' && !useCustomDates
                      ? 'bg-white/20 text-white shadow-sm'
                      : 'text-white/60 hover:bg-white/10 hover:text-white/80'
                  }`}
                >
                  Квартал
                </button>
              </div>
              
              {error && (
                <div className="text-red-400 text-xs">Ошибка: {error.message}</div>
              )}
            </div>
          </div>
          
          {/* Контент графика - показывается только если не свернут */}
          {!isChartCollapsed && (
            <>
              {/* Компактные чекбоксы для фильтрации */}
              <div className="mb-2 pb-2 border-b border-white/10">
            <div className="flex items-center justify-between mb-1">
              <span className="text-xs text-white/60">Показать на графике:</span>
                              <span className="text-xs text-blue-400 flex items-center gap-1">
                  <BarChart3 className="w-3 h-3" />
                  Реклама показана на правой оси
                </span>
            </div>
            <div className="grid grid-cols-2 md:grid-cols-5 gap-2">
              {Object.entries(chartConfig).map(([key, config]) => {
                const isVisible = visibleMetrics[key as keyof typeof visibleMetrics]
                return (
                  <div 
                    key={key}
                    className={`flex items-center space-x-1.5 p-1.5 rounded-lg transition-all duration-200 cursor-pointer ${
                      isVisible
                        ? 'bg-white/10 border border-white/20 shadow-sm'
                        : 'bg-white/5 border border-white/10 hover:bg-white/8'
                    }`}
                    onClick={() => toggleMetric(key as keyof typeof visibleMetrics)}
                  >
                    <Checkbox
                      id={key}
                      checked={isVisible}
                      onCheckedChange={() => toggleMetric(key as keyof typeof visibleMetrics)}
                      className="border-white/30 data-[state=checked]:bg-white/20 data-[state=checked]:border-white/50"
                    />
                                        <label
                      htmlFor={key}
                      className={`text-xs cursor-pointer select-none flex items-center gap-1.5 transition-colors duration-200 ${
                        isVisible ? 'text-white font-medium' : 'text-white/60'
                      }`}
                    >
                      <div
                        className={`w-2.5 h-2.5 rounded-sm transition-all duration-200 ${
                          isVisible ? 'opacity-100 scale-100' : 'opacity-50 scale-90'
                        }`}
                        style={{ backgroundColor: config.color }}
                      />
                      {config.label}
                    </label>
                  </div>
                )
              })}
            </div>
          </div>

          <div className="flex-1 min-h-0">
            <ChartContainer config={chartConfig} className="min-h-[200px] h-full w-full">
              <BarChart accessibilityLayer data={chartData}>
                <CartesianGrid vertical={false} />
                <XAxis
                  dataKey="date"
                  tickLine={false}
                  tickMargin={10}
                  axisLine={false}
                  tickFormatter={(value) => value.slice(0, 5)}
                />
                
                {/* Левая ось для основных метрик */}
                <YAxis 
                  yAxisId="left"
                  orientation="left"
                  tickLine={false}
                  axisLine={false}
                  className="text-white/60 text-xs"
                />
                
                {/* Правая ось для рекламы */}
                <YAxis 
                  yAxisId="right"
                  orientation="right"
                  tickLine={false}
                  axisLine={false}
                  className="text-white/60 text-xs"
                />
                
                <ChartTooltip
                  cursor={false}
                  content={<ChartTooltipContent indicator="dashed" />}
                />
                
                {/* Основные метрики на левой оси */}
                {visibleMetrics.sales && (
                  <Bar
                    yAxisId="left"
                    dataKey="sales"
                    fill={chartConfig.sales.color}
                    radius={4}
                  />
                )}
                {visibleMetrics.orders && (
                  <Bar
                    yAxisId="left"
                    dataKey="orders"
                    fill={chartConfig.orders.color}
                    radius={4}
                  />
                )}
                {visibleMetrics.refusals && (
                  <Bar
                    yAxisId="left"
                    dataKey="refusals"
                    fill={chartConfig.refusals.color}
                    radius={4}
                  />
                )}
                {visibleMetrics.returns && (
                  <Bar
                    yAxisId="left"
                    dataKey="returns"
                    fill={chartConfig.returns.color}
                    radius={4}
                  />
                )}
                
                {/* Реклама на правой оси */}
                {visibleMetrics.advertising && (
                  <Bar
                    yAxisId="right"
                    dataKey="advertising"
                    fill={chartConfig.advertising.color}
                    radius={4}
                  />
                )}
              </BarChart>
            </ChartContainer>
          </div>
            </>
          )}
        </div>
      </Card>

      {/* Таблица данных */}
      <Card className="glass-card flex-1 overflow-hidden">
        <div className="p-3 h-full flex flex-col">
          <h3 className="text-white font-semibold mb-2 text-sm">Детальная статистика</h3>
          
          <div className="overflow-x-auto flex-1">
            <table className="w-full">
                              <thead>
                  <tr className="border-b border-white/20">
                    <th className="text-left p-2 text-white font-semibold text-xs">
                      <button 
                        onClick={() => handleSort('date')}
                        className="flex items-center gap-1 hover:text-white/80 hover:bg-white/10 px-1 py-0.5 rounded transition-all cursor-pointer"
                        title="Нажмите для сортировки"
                      >
                        Дата
                        <span className="text-xs opacity-50">
                          {sortField === 'date' ? (
                            sortDirection === 'asc' ? '↑' : '↓'
                          ) : '⇅'}
                        </span>
                      </button>
                    </th>
                    <th className="text-left p-2 text-white font-semibold text-xs">
                      <button 
                        onClick={() => handleSort('salesUnits')}
                        className="flex items-center gap-1 hover:text-white/80 hover:bg-white/10 px-1 py-0.5 rounded transition-all cursor-pointer"
                        title="Нажмите для сортировки"
                      >
                        Продажи, шт
                        <span className="text-xs opacity-50">
                          {sortField === 'salesUnits' ? (
                            sortDirection === 'asc' ? '↑' : '↓'
                          ) : '⇅'}
                        </span>
                      </button>
                    </th>
                    <th className="text-left p-2 text-white font-semibold text-xs">
                      <button 
                        onClick={() => handleSort('buyoutPercentage')}
                        className="flex items-center gap-1 hover:text-white/80 hover:bg-white/10 px-1 py-0.5 rounded transition-all cursor-pointer"
                        title="Нажмите для сортировки"
                      >
                        % выкупов
                        <span className="text-xs opacity-50">
                          {sortField === 'buyoutPercentage' ? (
                            sortDirection === 'asc' ? '↑' : '↓'
                          ) : '⇅'}
                        </span>
                      </button>
                    </th>
                    <th className="text-left p-2 text-white font-semibold text-xs">
                      <button 
                        onClick={() => handleSort('advertising')}
                        className="flex items-center gap-1 hover:text-white/80 hover:bg-white/10 px-1 py-0.5 rounded transition-all cursor-pointer"
                        title="Нажмите для сортировки"
                      >
                        Реклама, ₽
                        <span className="text-xs opacity-50">
                          {sortField === 'advertising' ? (
                            sortDirection === 'asc' ? '↑' : '↓'
                          ) : '⇅'}
                        </span>
                      </button>
                    </th>
                    <th className="text-left p-2 text-white font-semibold text-xs">
                      <button 
                        onClick={() => handleSort('orders')}
                        className="flex items-center gap-1 hover:text-white/80 hover:bg-white/10 px-1 py-0.5 rounded transition-all cursor-pointer"
                        title="Нажмите для сортировки"
                      >
                        Заказы
                        <span className="text-xs opacity-50">
                          {sortField === 'orders' ? (
                            sortDirection === 'asc' ? '↑' : '↓'
                          ) : '⇅'}
                        </span>
                      </button>
                    </th>
                    <th className="text-left p-2 text-white font-semibold text-xs">
                      <button 
                        onClick={() => handleSort('refusals')}
                        className="flex items-center gap-1 hover:text-white/80 hover:bg-white/10 px-1 py-0.5 rounded transition-all cursor-pointer"
                        title="Нажмите для сортировки"
                      >
                        Отказы
                        <span className="text-xs opacity-50">
                          {sortField === 'refusals' ? (
                            sortDirection === 'asc' ? '↑' : '↓'
                          ) : '⇅'}
                        </span>
                      </button>
                    </th>
                    <th className="text-left p-2 text-white font-semibold text-xs">
                      <button 
                        onClick={() => handleSort('returns')}
                        className="flex items-center gap-1 hover:text-white/80 hover:bg-white/10 px-1 py-0.5 rounded transition-all cursor-pointer"
                        title="Нажмите для сортировки"
                      >
                        Возвраты
                        <span className="text-xs opacity-50">
                          {sortField === 'returns' ? (
                            sortDirection === 'asc' ? '↑' : '↓'
                          ) : '⇅'}
                        </span>
                      </button>
                    </th>
                    <th className="text-left p-2 text-white font-semibold text-xs">
                      <button 
                        onClick={() => handleSort('revenue')}
                        className="flex items-center gap-1 hover:text-white/80 hover:bg-white/10 px-1 py-0.5 rounded transition-all cursor-pointer"
                        title="Нажмите для сортировки"
                      >
                        Выручка, ₽
                        <span className="text-xs opacity-50">
                          {sortField === 'revenue' ? (
                            sortDirection === 'asc' ? '↑' : '↓'
                          ) : '⇅'}
                        </span>
                      </button>
                    </th>
                  </tr>
                </thead>
              <tbody>
                {/* Итоговая строка сверху */}
                <tr className="border-b-2 border-white/30 bg-white/10 font-semibold">
                  <td className="p-2 text-white text-xs font-bold">ИТОГО</td>
                  <td className="p-2 text-white text-xs font-bold">{totals.salesUnits}</td>
                  <td className="p-2 text-xs">
                  <Badge 
                    variant="secondary" 
                    className={`${
                      totals.buyoutPercentage >= 80 
                        ? 'bg-green-500/20 text-green-400' 
                        : 'bg-yellow-500/20 text-yellow-400'
                    } font-bold`}
                  >
                    {totals.buyoutPercentage.toFixed(1)}%
                  </Badge>
                </td>
                <td className="p-2 text-white text-xs font-bold">{totals.advertising.toLocaleString('ru-RU')}</td>
                <td className="p-2 text-white text-xs font-bold">{totals.orders}</td>
                <td className="p-2 text-xs">
                  <Badge variant="secondary" className="bg-red-500/20 text-red-400 font-bold text-xs px-2 py-0.5">
                    {totals.refusals}
                  </Badge>
                </td>
                <td className="p-2 text-xs">
                  <Badge variant="secondary" className="bg-orange-500/20 text-orange-400 font-bold text-xs px-2 py-0.5">
                    {totals.returns}
                  </Badge>
                </td>
                <td className="p-2 text-white text-xs font-bold">
                  {totals.revenue.toLocaleString('ru-RU')} ₽
                </td>
                </tr>
                                  
                  {sortedTableData.map((row, index) => (
                    <tr key={index} className="border-b border-white/10 hover:bg-white/5 transition-colors">
                      <td className="p-2 text-white/80 text-xs">{row.date}</td>
                      <td className="p-2 text-white text-xs font-medium">{row.salesUnits}</td>
                      <td className="p-2 text-xs">
                      <Badge 
                        variant="secondary" 
                        className={`${
                          row.buyoutPercentage >= 80 
                            ? 'bg-green-500/20 text-green-400' 
                            : 'bg-yellow-500/20 text-yellow-400'
                        }`}
                      >
                        {row.buyoutPercentage}%
                      </Badge>
                    </td>
                                          <td className="p-2 text-white/80 text-xs">{row.advertising.toLocaleString('ru-RU')}</td>
                      <td className="p-2 text-white/80 text-xs">{row.orders}</td>
                      <td className="p-2 text-xs">
                        <Badge variant="secondary" className="bg-red-500/20 text-red-400 text-xs px-2 py-0.5">
                          {row.refusals}
                        </Badge>
                      </td>
                      <td className="p-2 text-xs">
                        <Badge variant="secondary" className="bg-orange-500/20 text-orange-400 text-xs px-2 py-0.5">
                          {row.returns}
                        </Badge>
                      </td>
                      <td className="p-2 text-white text-xs font-medium">
                        {row.revenue.toLocaleString('ru-RU')} ₽
                      </td>
                  </tr>
                ))}
              </tbody>
                            </table>
              </div>
              <div className="mt-2 text-xs text-white/50 flex items-center gap-1">
                <Info className="w-3 h-3" />
                <span>Нажмите на заголовок столбца для сортировки</span>
              </div>
            </div>
          </Card>
    </div>
  )
} 