'use client'

import { useQuery } from '@apollo/client'
import {
  Copy,
  Gift,
  Users,
  TrendingUp,
  Zap,
  UserPlus,
  ShoppingCart,
  Search,
  Filter,
  Calendar,
  Building,
  CheckCircle,
  X,
} from 'lucide-react'
import React, { useState, useMemo } from 'react'
import { toast } from 'sonner'

import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { GlassInput } from '@/components/ui/input'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { GET_REFERRAL_DASHBOARD_DATA } from '@/graphql/referral-queries'

export function ReferralsTab() {
  const [searchQuery, setSearchQuery] = useState('')
  const [typeFilter, setTypeFilter] = useState<string>('all')
  const [sourceFilter, setSourceFilter] = useState<string>('all')

  // Основной запрос для получения всех данных рефералов
  const { data, loading, error } = useQuery(GET_REFERRAL_DASHBOARD_DATA, {
    fetchPolicy: 'network-only', // Принудительно загружаем данные с сервера
    errorPolicy: 'all',
  })

  // Отладка для понимания что приходит в data (только в dev режиме)
  if (process.env.NODE_ENV === 'development') {
    console.warn('🔍 ReferralsTab - полные данные:', {
      loading,
      error: error?.message,
      data,
      myReferralLink: data?.myReferralLink,
      myReferralStats: data?.myReferralStats,
    })
  }

  // Извлекаем данные из GraphQL ответа или используем fallback для разработки
  const referralLink = data?.myReferralLink || 'http://localhost:3000/register?ref=LOADING'
  const stats = data?.myReferralStats || {
    totalPartners: 0,
    totalSpheres: 0,
    monthlyPartners: 0,
    monthlySpheres: 0,
  }
  const allReferrals = useMemo(() => data?.myReferrals?.referrals || [], [data])

  const copyReferralLink = async () => {
    try {
      await navigator.clipboard.writeText(referralLink)
      toast.success('Реферальная ссылка скопирована!', {
        description: 'Теперь вы можете поделиться ей с партнерами',
      })
    } catch {
      toast.error('Не удалось скопировать ссылку')
    }
  }

  // Фильтрация и поиск
  const filteredReferrals = useMemo(() => {
    return allReferrals.filter((referral) => {
      const matchesSearch =
        !searchQuery ||
        referral.organization.name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        referral.organization.fullName?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        referral.organization.inn.includes(searchQuery)

      const matchesType = typeFilter === 'all' || referral.organization.type === typeFilter
      const matchesSource = sourceFilter === 'all' || referral.source === sourceFilter

      return matchesSearch && matchesType && matchesSource
    })
  }, [allReferrals, searchQuery, typeFilter, sourceFilter])

  const getTypeLabel = (type: string) => {
    switch (type) {
      case 'SELLER':
        return 'Селлер'
      case 'WHOLESALE':
        return 'Поставщик'
      case 'FULFILLMENT':
        return 'Фулфилмент'
      case 'LOGIST':
        return 'Логистика'
      default:
        return type
    }
  }

  const getTypeBadgeStyles = (type: string) => {
    switch (type) {
      case 'SELLER':
        return 'bg-green-500/20 text-green-300 border-green-500/30'
      case 'WHOLESALE':
        return 'bg-purple-500/20 text-purple-300 border-purple-500/30'
      case 'FULFILLMENT':
        return 'bg-blue-500/20 text-blue-300 border-blue-500/30'
      case 'LOGIST':
        return 'bg-orange-500/20 text-orange-300 border-orange-500/30'
      default:
        return 'bg-gray-500/20 text-gray-300 border-gray-500/30'
    }
  }

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

  const clearFilters = () => {
    setSearchQuery('')
    setTypeFilter('all')
    setSourceFilter('all')
  }

  const hasActiveFilters = searchQuery || typeFilter !== 'all' || sourceFilter !== 'all'

  return (
    <div className="h-full flex flex-col space-y-4">
      {/* Компактный блок с реферальной ссылкой */}
      <Card className="glass-card p-4">
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-2">
            <div className="p-1.5 rounded-lg bg-yellow-500/20 border border-yellow-500/30">
              <Gift className="h-4 w-4 text-yellow-400" />
            </div>
            <h3 className="text-base font-semibold text-white">Реферальная ссылка</h3>
          </div>
          <div className="text-xs text-white/60">
            <span className="text-yellow-400 font-medium">100 сфер</span> за регистрацию +
            <span className="text-yellow-400 font-medium"> 100 сфер</span> за первую сделку
          </div>
        </div>

        <div className="flex items-center gap-3">
          <div className="flex-1 px-3 py-2 glass-input rounded-lg text-white/60 font-mono text-sm truncate">
            {referralLink}
          </div>
          <Button
            size="sm"
            onClick={copyReferralLink}
            className="glass-button hover:bg-white/20 transition-all duration-200 px-3"
          >
            <Copy className="h-4 w-4 mr-1" />
            Копировать
          </Button>
        </div>
      </Card>

      {/* Компактная статистика */}
      <div className="grid grid-cols-4 gap-3">
        <Card className="glass-card p-3 hover:bg-white/5 transition-all duration-200">
          <div className="flex items-center gap-2">
            <div className="p-1.5 rounded-lg bg-blue-500/20 border border-blue-500/30">
              <Users className="h-4 w-4 text-blue-400" />
            </div>
            <div>
              <p className="text-xs text-white/60 uppercase tracking-wide">Партнеров</p>
              <p className="text-xl font-bold text-white">
                {loading ? (
                  <span className="inline-block h-6 w-8 bg-white/10 rounded animate-pulse" />
                ) : (
                  stats.totalPartners
                )}
              </p>
            </div>
          </div>
        </Card>

        <Card className="glass-card p-3 hover:bg-white/5 transition-all duration-200">
          <div className="flex items-center gap-2">
            <div className="p-1.5 rounded-lg bg-yellow-500/20 border border-yellow-500/30">
              <Zap className="h-4 w-4 text-yellow-400" />
            </div>
            <div>
              <p className="text-xs text-white/60 uppercase tracking-wide">Заработано</p>
              <div className="flex items-center gap-1">
                <p className="text-xl font-bold text-white">
                  {loading ? (
                    <span className="inline-block h-6 w-8 bg-white/10 rounded animate-pulse" />
                  ) : (
                    stats.totalSpheres
                  )}
                </p>
                <Zap className="h-4 w-4 text-yellow-400" />
              </div>
            </div>
          </div>
        </Card>

        <Card className="glass-card p-3 hover:bg-white/5 transition-all duration-200">
          <div className="flex items-center gap-2">
            <div className="p-1.5 rounded-lg bg-green-500/20 border border-green-500/30">
              <TrendingUp className="h-4 w-4 text-green-400" />
            </div>
            <div>
              <p className="text-xs text-white/60 uppercase tracking-wide">За месяц</p>
              <p className="text-xl font-bold text-white">
                {loading ? (
                  <span className="inline-block h-6 w-8 bg-white/10 rounded animate-pulse" />
                ) : (
                  stats.monthlyPartners
                )}
              </p>
            </div>
          </div>
        </Card>

        <Card className="glass-card p-3 hover:bg-white/5 transition-all duration-200">
          <div className="flex items-center gap-2">
            <div className="p-1.5 rounded-lg bg-yellow-500/20 border border-yellow-500/30">
              <Zap className="h-4 w-4 text-yellow-400" />
            </div>
            <div>
              <p className="text-xs text-white/60 uppercase tracking-wide">Сфер/мес</p>
              <div className="flex items-center gap-1">
                <p className="text-xl font-bold text-white">
                  {loading ? (
                    <span className="inline-block h-6 w-8 bg-white/10 rounded animate-pulse" />
                  ) : (
                    stats.monthlySpheres
                  )}
                </p>
                <Zap className="h-4 w-4 text-yellow-400" />
              </div>
            </div>
          </div>
        </Card>
      </div>

      {/* Компактные фильтры */}
      <Card className="glass-card p-3">
        <div className="flex flex-col xl:flex-row gap-3">
          {/* Поиск */}
          <div className="flex-1">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-white/40" />
              <GlassInput
                placeholder="Поиск по названию или ИНН..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-10 h-9"
              />
            </div>
          </div>

          {/* Фильтры */}
          <div className="flex gap-2">
            <Select value={typeFilter} onValueChange={setTypeFilter}>
              <SelectTrigger className="glass-input text-white border-white/20 h-9 min-w-[130px]">
                <Filter className="h-3 w-3 mr-1" />
                <SelectValue placeholder="Тип" />
              </SelectTrigger>
              <SelectContent className="glass-card border-white/20">
                <SelectItem value="all">Все типы</SelectItem>
                <SelectItem value="SELLER">Селлер</SelectItem>
                <SelectItem value="WHOLESALE">Поставщик</SelectItem>
                <SelectItem value="FULFILLMENT">Фулфилмент</SelectItem>
                <SelectItem value="LOGIST">Логистика</SelectItem>
              </SelectContent>
            </Select>

            <Select value={sourceFilter} onValueChange={setSourceFilter}>
              <SelectTrigger className="glass-input text-white border-white/20 h-9 min-w-[140px]">
                <Filter className="h-3 w-3 mr-1" />
                <SelectValue placeholder="Источник" />
              </SelectTrigger>
              <SelectContent className="glass-card border-white/20">
                <SelectItem value="all">Все источники</SelectItem>
                <SelectItem value="REFERRAL_LINK">Реферальная ссылка</SelectItem>
                <SelectItem value="AUTO_BUSINESS">Бизнес-сделка</SelectItem>
              </SelectContent>
            </Select>

            {hasActiveFilters && (
              <Button
                variant="ghost"
                size="sm"
                onClick={clearFilters}
                className="text-white/60 hover:text-white hover:bg-white/10 h-9 w-9 p-0"
              >
                <X className="h-3 w-3" />
              </Button>
            )}
          </div>
        </div>

        {/* Краткая статистика */}
        <div className="flex items-center justify-between mt-3 text-xs">
          <div className="text-white/60">
            Показано {filteredReferrals.length} из {allReferrals.length} партнеров
          </div>

          <div className="flex gap-2">
            <div className="flex items-center gap-1 px-2 py-1 rounded-md bg-blue-500/10 text-blue-300">
              <UserPlus className="h-3 w-3" />
              <span>Рефералы: {allReferrals.filter((r) => r.source === 'REFERRAL_LINK').length}</span>
            </div>
            <div className="flex items-center gap-1 px-2 py-1 rounded-md bg-orange-500/10 text-orange-300">
              <ShoppingCart className="h-3 w-3" />
              <span>Бизнес: {allReferrals.filter((r) => r.source === 'AUTO_BUSINESS').length}</span>
            </div>
          </div>
        </div>
      </Card>

      {/* Таблица рефералов */}
      <Card className="glass-card flex-1 overflow-hidden">
        <div className="h-full overflow-auto">
          <div className="p-6 space-y-3">
            {/* Заголовок таблицы */}
            <div className="p-4 rounded-xl bg-gradient-to-r from-white/5 to-white/10 border border-white/10">
              <div className="grid grid-cols-12 gap-4 text-sm font-medium text-white/80">
                <div className="col-span-2 flex items-center gap-2">
                  <Calendar className="h-4 w-4 text-blue-400" />
                  <span>Дата регистрации</span>
                </div>
                <div className="col-span-3 flex items-center gap-2">
                  <Building className="h-4 w-4 text-green-400" />
                  <span>Организация</span>
                </div>
                <div className="col-span-1 text-center flex items-center justify-center">
                  <span>Тип</span>
                </div>
                <div className="col-span-2 text-center flex items-center justify-center gap-1">
                  <UserPlus className="h-4 w-4 text-purple-400" />
                  <span>Источник</span>
                </div>
                <div className="col-span-2 text-center flex items-center justify-center gap-1">
                  <Zap className="h-4 w-4 text-yellow-400" />
                  <span>Начислено</span>
                </div>
                <div className="col-span-2 text-center flex items-center justify-center">
                  <span>Статус</span>
                </div>
              </div>
            </div>

            {/* Строки партнеров */}
            {filteredReferrals.length === 0 ? (
              <div className="flex flex-col items-center justify-center h-64">
                <Gift className="h-12 w-12 text-white/20 mb-2" />
                <p className="text-white/60">
                  {loading
                    ? 'Загрузка...'
                    : allReferrals.length === 0
                      ? 'У вас пока нет партнеров'
                      : 'Ничего не найдено'}
                </p>
                <p className="text-white/40 text-sm mt-1">
                  {loading
                    ? 'Получаем данные о ваших партнерах...'
                    : allReferrals.length === 0
                      ? 'Поделитесь реферальной ссылкой или начните работать с клиентами'
                      : 'Попробуйте изменить параметры поиска'}
                </p>
              </div>
            ) : (
              filteredReferrals.map((referral) => (
                <div
                  key={referral.id}
                  className="p-4 rounded-xl bg-white/5 hover:bg-white/10 transition-all duration-200 border border-white/10"
                >
                  <div className="grid grid-cols-12 gap-4 items-center">
                    <div className="col-span-2 text-white/80">
                      <div className="flex items-center gap-2">
                        <Calendar className="h-3 w-3 text-white/40" />
                        <span className="text-sm">{formatDate(referral.registeredAt)}</span>
                      </div>
                    </div>
                    <div className="col-span-3">
                      <div>
                        <p className="text-white font-medium text-sm">
                          {referral.organization.name || referral.organization.fullName}
                        </p>
                        <p className="text-white/60 text-xs flex items-center gap-1">
                          <Building className="h-3 w-3" />
                          {referral.organization.inn}
                        </p>
                      </div>
                    </div>
                    <div className="col-span-1 text-center">
                      <Badge className={getTypeBadgeStyles(referral.organization.type) + ' text-xs'}>
                        {getTypeLabel(referral.organization.type)}
                      </Badge>
                    </div>
                    <div className="col-span-2 text-center">
                      <div className="flex items-center justify-center gap-2">
                        {referral.source === 'REFERRAL_LINK' ? (
                          <>
                            <UserPlus className="h-4 w-4 text-blue-400" />
                            <span className="text-blue-300 text-sm">Ссылка</span>
                          </>
                        ) : (
                          <>
                            <ShoppingCart className="h-4 w-4 text-orange-400" />
                            <span className="text-orange-300 text-sm">Бизнес</span>
                          </>
                        )}
                      </div>
                    </div>
                    <div className="col-span-2 text-center">
                      <div className="flex items-center justify-center gap-2">
                        <span className="text-green-400 font-semibold">+{referral.spheresEarned}</span>
                        <Zap className="h-4 w-4 text-yellow-400" />
                      </div>
                    </div>
                    <div className="col-span-2 text-center">
                      <div className="flex items-center justify-center gap-2">
                        <CheckCircle className="h-4 w-4 text-green-400" />
                        <span className="text-green-300 text-sm">Активен</span>
                      </div>
                    </div>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
      </Card>
    </div>
  )
}
