'use client'; import React, { useState, useEffect } from 'react'; import { generateTelegramCode, unlinkTelegram, getTelegramStatus, getTelegramBotInfo, } from '@/api/telegram'; import { useToast } from '@/contexts/ToastContext'; interface TelegramSectionProps { onLinkedChange?: () => void; } export function TelegramSection({ onLinkedChange }: TelegramSectionProps) { const { showToast } = useToast(); const [loading, setLoading] = useState(true); const [linked, setLinked] = useState(false); const [telegramUsername, setTelegramUsername] = useState(''); const [showLinkModal, setShowLinkModal] = useState(false); const [linkCode, setLinkCode] = useState(''); const [generating, setGenerating] = useState(false); const [unlinking, setUnlinking] = useState(false); const [error, setError] = useState(null); const [success, setSuccess] = useState(null); const [copied, setCopied] = useState(false); const [botLink, setBotLink] = useState(''); const [botUsername, setBotUsername] = useState(''); const [showUnlinkConfirm, setShowUnlinkConfirm] = useState(false); const loadStatus = async () => { try { setLoading(true); setError(null); const status = await getTelegramStatus(); setLinked(status.linked); setTelegramUsername(status.telegram_username || ''); } catch (err) { console.error('Error loading Telegram status:', err); setError('Не удалось загрузить статус Telegram'); } finally { setLoading(false); } }; const loadBotInfo = async () => { try { const botInfo = await getTelegramBotInfo(); if (botInfo?.success && botInfo?.username) { setBotLink(botInfo.link || `https://t.me/${botInfo.username}`); setBotUsername(`@${botInfo.username}`); } } catch (err) { console.error('Failed to fetch bot info:', err); } }; useEffect(() => { loadStatus(); loadBotInfo(); }, []); useEffect(() => { if (showLinkModal && !botUsername) loadBotInfo(); }, [showLinkModal, botUsername]); const handleGenerateCode = async () => { try { setGenerating(true); setError(null); setSuccess(null); const response = await generateTelegramCode(); if (response?.success && response?.code) { setLinkCode(response.code); setShowLinkModal(true); } else { setError(response?.error || 'Не удалось сгенерировать код'); } } catch (err) { console.error('Error generating code:', err); setError('Ошибка генерации кода'); } finally { setGenerating(false); } }; const handleUnlinkClick = () => { setShowUnlinkConfirm(true); setError(null); }; const handleUnlinkConfirm = async () => { try { setUnlinking(true); setShowUnlinkConfirm(false); setError(null); setSuccess(null); const response = await unlinkTelegram(); if (response?.success) { setSuccess('Telegram отвязан'); setLinked(false); setTelegramUsername(''); onLinkedChange?.(); setTimeout(() => setSuccess(null), 3000); } else { setError(response?.error || 'Не удалось отвязать'); } } catch (err) { console.error('Error unlinking:', err); setError('Ошибка отвязки'); } finally { setUnlinking(false); } }; const closeLinkModal = () => { setShowLinkModal(false); setLinkCode(''); setCopied(false); setTimeout(() => { loadStatus(); onLinkedChange?.(); }, 2000); }; const copyLinkCommand = async () => { if (!linkCode) return; const command = `/link ${linkCode}`; try { await navigator.clipboard.writeText(command); setCopied(true); showToast('Команда скопирована', 'success'); setTimeout(() => setCopied(false), 2000); } catch { const el = document.createElement('textarea'); el.value = command; el.style.position = 'fixed'; el.style.opacity = '0'; document.body.appendChild(el); el.select(); try { document.execCommand('copy'); setCopied(true); showToast('Команда скопирована', 'success'); setTimeout(() => setCopied(false), 2000); } finally { document.body.removeChild(el); } } }; if (loading) { return (
Telegram: загрузка...
); } return ( <>
Telegram
{linked ? (
Подключён {telegramUsername ? `@${telegramUsername.replace(/^@/, '')}` : ''}
) : (
Подключите для уведомлений о занятиях и сообщениях
)}
{error && ( {error} )} {success && ( {success} )} {linked ? ( ) : ( )}
{showUnlinkConfirm && (

Вы уверены, что хотите отвязать Telegram?

)} {showLinkModal && (

Привязка к Telegram

Ваш код связывания:

{linkCode}

Действителен 15 минут

Инструкция:

  1. Откройте Telegram
  2. {botLink && botUsername ? ( <> Найдите бота{' '} {botUsername} ) : ( <>Найдите бота {botUsername || '(ссылка ниже)'} )}
  3. Отправьте команду:{' '} /link {linkCode} {copied && ✓ Скопировано}
)} ); }