"use client"; import React, { useState, useEffect, useRef } from "react"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { useTargetChannel } from "@/components/providers/target-channel-provider"; import { Loader2, AlertCircle, Plus, ExternalLink, CheckCircle2, ArrowUpRightIcon, } from "lucide-react"; import { Alert, AlertDescription } from "@/components/ui/alert"; import { BOT_USERNAME } from "@/lib/utils/constants"; import { channelsApi } from "@/lib/api"; export const TargetChannelSelector: React.FC = () => { const { channels, selectedChannel, setSelectedChannel, isLoading, error } = useTargetChannel(); const [isAddDialogOpen, setIsAddDialogOpen] = useState(false); const [isSuccess, setIsSuccess] = useState(false); const [initialChannelCount, setInitialChannelCount] = useState(0); const pollingIntervalRef = useRef(null); // Очистка интервала при размонтировании useEffect(() => { return () => { if (pollingIntervalRef.current) { clearInterval(pollingIntervalRef.current); } }; }, []); // Автоматический запуск polling при открытии диалога useEffect(() => { if (isAddDialogOpen && !isSuccess && initialChannelCount > 0) { // Polling каждую секунду pollingIntervalRef.current = setInterval(() => { checkForNewChannels(); }, 1000); return () => { if (pollingIntervalRef.current) { clearInterval(pollingIntervalRef.current); pollingIntervalRef.current = null; } }; } }, [isAddDialogOpen, isSuccess, initialChannelCount]); const checkForNewChannels = async () => { try { const response = await channelsApi.list(); const activeChannels = response.target_channels.filter( (c) => c.is_active ); if (activeChannels.length > initialChannelCount) { // Новый канал добавлен! setIsSuccess(true); // Останавливаем polling if (pollingIntervalRef.current) { clearInterval(pollingIntervalRef.current); pollingIntervalRef.current = null; } // Закрываем диалог через 2 секунды setTimeout(() => { setIsAddDialogOpen(false); setIsSuccess(false); // Обновляем список каналов через провайдер window.location.reload(); }, 2000); } } catch (err) { console.error("Error polling channels:", err); } }; const handleAddChannel = () => { setInitialChannelCount(channels.length); setIsSuccess(false); setIsAddDialogOpen(true); }; const handleDialogClose = () => { if (!isSuccess) { // Не даем закрыть диалог во время ожидания return; } setIsAddDialogOpen(false); setIsSuccess(false); if (pollingIntervalRef.current) { clearInterval(pollingIntervalRef.current); pollingIntervalRef.current = null; } }; if (isLoading) { return (
Загрузка каналов...
); } if (error) { return ( Ошибка: {error} ); } if (channels.length === 0) { return ( ); } return ( <> !isSuccess && e.preventDefault()} > Добавить целевой канал Следуйте инструкциям ниже, чтобы подключить новый канал {isSuccess ? (

Канал успешно добавлен!

Страница обновится автоматически...

) : (

Шаги для добавления канала:

  1. Откройте свой Telegram канал
  2. Перейдите в настройки канала → Администраторы
  3. Добавьте бота{" "} @{BOT_USERNAME} {" "} как администратора
  4. Предоставьте боту права:{" "} Публикация сообщений, Удаление сообщений

Ждем добавления бота...
Как только вы добавите бота, канал автоматически появится

)}
); };