"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, } 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) { 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); if (pollingIntervalRef.current) { clearInterval(pollingIntervalRef.current); pollingIntervalRef.current = null; } 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 handleDialogOpenChange = (open: boolean) => { if (!open) { // Разрешаем закрытие всегда (в том числе через кнопку крестик) 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()} onEscapeKeyDown={(e) => !isSuccess && e.preventDefault()} > Добавить целевой канал Следуйте инструкциям ниже, чтобы подключить новый канал {isSuccess ? (

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

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

) : (

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

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

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

)}
); };