"use client"

import { useState, useEffect } from 'react'
import { useQuery, useLazyQuery } from '@apollo/client'
import { Card } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Skeleton } from '@/components/ui/skeleton'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { GET_WILDBERRIES_CAMPAIGN_STATS } from '@/graphql/queries'
import { TrendingUp, Search, Calendar, Eye, MousePointer, ShoppingCart, DollarSign, Percent, AlertCircle } from 'lucide-react'
import { 
  ChartContainer, 
  ChartTooltip, 
  ChartTooltipContent,
  ChartLegend,
  ChartLegendContent,
  type ChartConfig 
} from '@/components/ui/chart'
import { LineChart, Line, XAxis, YAxis, CartesianGrid, ResponsiveContainer } from 'recharts'

interface CampaignStatsProps {
  selectedPeriod: string
  useCustomDates: boolean
  startDate: string
  endDate: 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
  dates: string[]
  days: Array<{
    date: string
    views: number
    clicks: number
    ctr: number
    cpc: number
    sum: number
    atbs: number
    orders: number
    cr: number
    shks: number
    sum_price: number
  }>
  boosterStats: Array<{
    date: string
    views: number
    clicks: number
    ctr: number
    cpc: number
    sum: number
    atbs: number
    orders: number
    cr: number
    shks: number
    sum_price: number
  }>
}

export function AdvertisingTab({ selectedPeriod, useCustomDates, startDate, endDate }: CampaignStatsProps) {
  const [campaignIds, setCampaignIds] = useState('')
  const [campaignStats, setCampaignStats] = useState<CampaignStats[]>([])
  
  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)
    }
  })

  const handleGetStats = () => {
    if (!campaignIds.trim()) return

    const ids = campaignIds.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id))
    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 }
      }
    })
  }

  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 = campaignStats.length > 0 ? campaignStats[0]?.days?.map(day => ({
    date: new Date(day.date).toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit' }),
    views: day.views,
    clicks: day.clicks,
    sum: day.sum,
    orders: day.orders
  })) || [] : []

  const chartConfig = {
    views: {
      label: "Показы",
      color: "#8b5cf6",
    },
    clicks: {
      label: "Клики",
      color: "#06b6d4",
    },
    sum: {
      label: "Затраты (₽)",
      color: "#f59e0b",
    },
    orders: {
      label: "Заказы",
      color: "#10b981",
    },
  }

  return (
    <div className="h-full flex flex-col space-y-4 overflow-hidden">
      {/* Форма поиска кампаний */}
      <Card className="glass-card flex-shrink-0 p-4">
        <div className="flex items-center gap-4">
          <div className="flex-1">
            <label className="block text-sm font-medium text-white/80 mb-2">
              ID кампаний (через запятую)
            </label>
            <Input
              placeholder="Например: 12345, 67890, 11111"
              value={campaignIds}
              onChange={(e) => setCampaignIds(e.target.value)}
              className="bg-white/5 border-white/20 text-white placeholder:text-white/40"
            />
          </div>
          <Button 
            onClick={handleGetStats}
            disabled={loading || !campaignIds.trim()}
            className="bg-white/10 hover:bg-white/20 border border-white/20 text-white flex items-center gap-2 mt-6"
          >
            {loading ? (
              <>
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white" />
                Загрузка...
              </>
            ) : (
              <>
                <Search className="h-4 w-4" />
                Получить статистику
              </>
            )}
          </Button>
        </div>
      </Card>

      {/* Ошибки */}
      {error && (
        <Alert className="bg-red-500/10 border-red-500/30 text-red-400">
          <AlertCircle className="h-4 w-4" />
          <AlertDescription>
            {error.message}
          </AlertDescription>
        </Alert>
      )}

      {/* Результаты */}
      <div className="flex-1 overflow-auto">
        {loading ? (
          <div className="space-y-4">
            {[1, 2, 3].map((i) => (
              <Card key={i} className="glass-card p-6">
                <Skeleton className="h-8 w-48 mb-4 bg-white/10" />
                <div className="grid grid-cols-4 gap-4">
                  {[1, 2, 3, 4].map((j) => (
                    <Skeleton key={j} className="h-16 bg-white/5" />
                  ))}
                </div>
              </Card>
            ))}
          </div>
        ) : campaignStats.length > 0 ? (
          <div className="space-y-6">
            {/* Общая статистика по всем кампаниям */}
            <Card className="glass-card p-6">
              <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
                <TrendingUp className="h-5 w-5" />
                Общая статистика ({campaignStats.length} кампаний)
              </h3>
              
              <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-8 gap-4 mb-6">
                {/* Показы */}
                <div className="bg-white/5 rounded-lg p-4">
                  <div className="flex items-center gap-2 mb-1">
                    <Eye className="h-4 w-4 text-purple-400" />
                    <span className="text-sm text-white/60">Показы</span>
                  </div>
                  <div className="text-xl font-bold text-white">
                    {formatNumber(campaignStats.reduce((sum, stat) => sum + stat.views, 0))}
                  </div>
                </div>

                {/* Клики */}
                <div className="bg-white/5 rounded-lg p-4">
                  <div className="flex items-center gap-2 mb-1">
                    <MousePointer className="h-4 w-4 text-cyan-400" />
                    <span className="text-sm text-white/60">Клики</span>
                  </div>
                  <div className="text-xl font-bold text-white">
                    {formatNumber(campaignStats.reduce((sum, stat) => sum + stat.clicks, 0))}
                  </div>
                </div>

                {/* CTR */}
                <div className="bg-white/5 rounded-lg p-4">
                  <div className="flex items-center gap-2 mb-1">
                    <Percent className="h-4 w-4 text-green-400" />
                    <span className="text-sm text-white/60">CTR</span>
                  </div>
                  <div className="text-xl font-bold text-white">
                    {formatPercent(
                      campaignStats.reduce((sum, stat, _, arr) => {
                        const totalViews = arr.reduce((s, st) => s + st.views, 0)
                        const totalClicks = arr.reduce((s, st) => s + st.clicks, 0)
                        return totalViews > 0 ? (totalClicks / totalViews) * 100 : 0
                      }, 0)
                    )}
                  </div>
                </div>

                {/* CPC */}
                <div className="bg-white/5 rounded-lg p-4">
                  <div className="flex items-center gap-2 mb-1">
                    <DollarSign className="h-4 w-4 text-amber-400" />
                    <span className="text-sm text-white/60">CPC</span>
                  </div>
                  <div className="text-xl font-bold text-white">
                    {formatCurrency(
                      campaignStats.reduce((sum, stat, _, arr) => {
                        const totalClicks = arr.reduce((s, st) => s + st.clicks, 0)
                        const totalSum = arr.reduce((s, st) => s + st.sum, 0)
                        return totalClicks > 0 ? totalSum / totalClicks : 0
                      }, 0)
                    )}
                  </div>
                </div>

                {/* Затраты */}
                <div className="bg-white/5 rounded-lg p-4">
                  <div className="flex items-center gap-2 mb-1">
                    <DollarSign className="h-4 w-4 text-red-400" />
                    <span className="text-sm text-white/60">Затраты</span>
                  </div>
                  <div className="text-xl font-bold text-white">
                    {formatCurrency(campaignStats.reduce((sum, stat) => sum + stat.sum, 0))}
                  </div>
                </div>

                {/* Заказы */}
                <div className="bg-white/5 rounded-lg p-4">
                  <div className="flex items-center gap-2 mb-1">
                    <ShoppingCart className="h-4 w-4 text-green-400" />
                    <span className="text-sm text-white/60">Заказы</span>
                  </div>
                  <div className="text-xl font-bold text-white">
                    {formatNumber(campaignStats.reduce((sum, stat) => sum + stat.orders, 0))}
                  </div>
                </div>

                {/* CR */}
                <div className="bg-white/5 rounded-lg p-4">
                  <div className="flex items-center gap-2 mb-1">
                    <Percent className="h-4 w-4 text-blue-400" />
                    <span className="text-sm text-white/60">CR</span>
                  </div>
                  <div className="text-xl font-bold text-white">
                    {formatPercent(
                      campaignStats.reduce((sum, stat, _, arr) => {
                        const totalClicks = arr.reduce((s, st) => s + st.clicks, 0)
                        const totalOrders = arr.reduce((s, st) => s + st.orders, 0)
                        return totalClicks > 0 ? (totalOrders / totalClicks) * 100 : 0
                      }, 0)
                    )}
                  </div>
                </div>

                {/* Выручка */}
                <div className="bg-white/5 rounded-lg p-4">
                  <div className="flex items-center gap-2 mb-1">
                    <DollarSign className="h-4 w-4 text-emerald-400" />
                    <span className="text-sm text-white/60">Выручка</span>
                  </div>
                  <div className="text-xl font-bold text-white">
                    {formatCurrency(campaignStats.reduce((sum, stat) => sum + stat.sum_price, 0))}
                  </div>
                </div>
              </div>

                             {/* График */}
               {chartData.length > 0 && (
                 <div className="mt-6">
                   <h4 className="text-md font-medium text-white mb-4">Динамика по дням</h4>
                   <div className="h-80">
                     <ChartContainer config={chartConfig}>
                       <LineChart data={chartData}>
                         <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.1)" />
                         <XAxis 
                           dataKey="date" 
                           tick={{ fill: 'rgba(255,255,255,0.6)', fontSize: 12 }}
                           axisLine={false}
                         />
                         <YAxis 
                           tick={{ fill: 'rgba(255,255,255,0.6)', fontSize: 12 }}
                           axisLine={false}
                         />
                         <ChartTooltip content={<ChartTooltipContent />} />
                         <ChartLegend content={<ChartLegendContent />} />
                         <Line 
                           type="monotone" 
                           dataKey="views" 
                           stroke="#8b5cf6" 
                           strokeWidth={2}
                           dot={{ fill: '#8b5cf6', strokeWidth: 2, r: 4 }}
                         />
                         <Line 
                           type="monotone" 
                           dataKey="clicks" 
                           stroke="#06b6d4" 
                           strokeWidth={2}
                           dot={{ fill: '#06b6d4', strokeWidth: 2, r: 4 }}
                         />
                         <Line 
                           type="monotone" 
                           dataKey="sum" 
                           stroke="#f59e0b" 
                           strokeWidth={2}
                           dot={{ fill: '#f59e0b', strokeWidth: 2, r: 4 }}
                         />
                         <Line 
                           type="monotone" 
                           dataKey="orders" 
                           stroke="#10b981" 
                           strokeWidth={2}
                           dot={{ fill: '#10b981', strokeWidth: 2, r: 4 }}
                         />
                       </LineChart>
                     </ChartContainer>
                   </div>
                 </div>
               )}
            </Card>

            {/* Детальная статистика по каждой кампании */}
            {campaignStats.map((campaign) => (
              <Card key={campaign.advertId} className="glass-card p-6">
                <div className="flex items-center justify-between mb-4">
                  <h3 className="text-lg font-semibold text-white">
                    Кампания #{campaign.advertId}
                  </h3>
                  <Badge variant="outline" className="border-white/20 text-white">
                    {campaign.days.length} дней
                  </Badge>
                </div>
                
                <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-8 gap-4">
                  <div className="bg-white/5 rounded-lg p-3">
                    <div className="text-sm text-white/60 mb-1">Показы</div>
                    <div className="font-bold text-white">{formatNumber(campaign.views)}</div>
                  </div>
                  
                  <div className="bg-white/5 rounded-lg p-3">
                    <div className="text-sm text-white/60 mb-1">Клики</div>
                    <div className="font-bold text-white">{formatNumber(campaign.clicks)}</div>
                  </div>
                  
                  <div className="bg-white/5 rounded-lg p-3">
                    <div className="text-sm text-white/60 mb-1">CTR</div>
                    <div className="font-bold text-white">{formatPercent(campaign.ctr)}</div>
                  </div>
                  
                  <div className="bg-white/5 rounded-lg p-3">
                    <div className="text-sm text-white/60 mb-1">CPC</div>
                    <div className="font-bold text-white">{formatCurrency(campaign.cpc)}</div>
                  </div>
                  
                  <div className="bg-white/5 rounded-lg p-3">
                    <div className="text-sm text-white/60 mb-1">Затраты</div>
                    <div className="font-bold text-white">{formatCurrency(campaign.sum)}</div>
                  </div>
                  
                  <div className="bg-white/5 rounded-lg p-3">
                    <div className="text-sm text-white/60 mb-1">Заказы</div>
                    <div className="font-bold text-white">{formatNumber(campaign.orders)}</div>
                  </div>
                  
                  <div className="bg-white/5 rounded-lg p-3">
                    <div className="text-sm text-white/60 mb-1">CR</div>
                    <div className="font-bold text-white">{formatPercent(campaign.cr)}</div>
                  </div>
                  
                  <div className="bg-white/5 rounded-lg p-3">
                    <div className="text-sm text-white/60 mb-1">Выручка</div>
                    <div className="font-bold text-white">{formatCurrency(campaign.sum_price)}</div>
                  </div>
                </div>
              </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">Введите ID кампаний для получения детальной статистики</p>
                <p className="text-white/40 text-sm">
                  Поддерживается API Wildberries /adv/v2/fullstats
                </p>
              </div>
            </div>
          </Card>
        )}
      </div>
    </div>
  )
} 