import React, { useState, useEffect } from 'react'
import { useAuth } from './auth/AuthContext'
import LoadingError from './LoadingError'
import './Integrations.css'

function TelegramIntegration({ onNavigate }) {
  const { authFetch } = useAuth()
  const [integration, setIntegration] = useState(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  useEffect(() => {
    fetchIntegration()
  }, [])

  const fetchIntegration = async () => {
    try {
      setLoading(true)
      const response = await authFetch('/api/integrations/telegram')
      if (!response.ok) {
        throw new Error('Ошибка при загрузке интеграции')
      }
      const data = await response.json()
      setIntegration(data)
    } catch (error) {
      console.error('Error fetching integration:', error)
      setError('Не удалось загрузить данные интеграции')
    } finally {
      setLoading(false)
    }
  }

  const handleOpenBot = () => {
    if (integration?.deep_link) {
      window.open(integration.deep_link, '_blank')
    }
  }

  const handleRefresh = () => {
    fetchIntegration()
  }

  if (loading) {
    return (
      <div className="fixed inset-0 flex justify-center items-center">
        <div className="flex flex-col items-center">
          <div className="w-12 h-12 border-4 border-indigo-200 border-t-indigo-600 rounded-full animate-spin mb-4"></div>
          <div className="text-gray-600 font-medium">Загрузка...</div>
        </div>
      </div>
    )
  }

  if (error && !integration) {
    return (
      <div className="p-4 md:p-6">
        <button className="close-x-button" onClick={() => onNavigate?.('profile')} title="Закрыть">
          ✕
        </button>
        <LoadingError onRetry={fetchIntegration} />
      </div>
    )
  }

  return (
    <div className="p-4 md:p-6">
      <button className="close-x-button" onClick={() => onNavigate?.('profile')} title="Закрыть">
        ✕
      </button>

      <h1 className="text-2xl font-bold mb-6">Telegram интеграция</h1>

      <div className="bg-white rounded-lg shadow-md p-6 mb-6">
        <h2 className="text-lg font-semibold mb-4">Статус подключения</h2>

        {integration?.is_connected ? (
          <div className="space-y-4">
            <div className="p-4 bg-green-50 border border-green-200 rounded-lg">
              <div className="flex items-center text-green-700">
                <span className="text-xl mr-2">✓</span>
                <span className="font-medium">Telegram подключен</span>
              </div>
            </div>
            
            {integration.telegram_user_id && (
              <div className="text-sm text-gray-600">
                Telegram ID: <span className="font-mono">{integration.telegram_user_id}</span>
              </div>
            )}

            <button
              onClick={handleOpenBot}
              className="w-full px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700"
            >
              Открыть бота
            </button>
          </div>
        ) : (
          <div className="space-y-4">
            <div className="p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
              <div className="flex items-center text-yellow-700">
                <span className="text-xl mr-2">⚠</span>
                <span className="font-medium">Telegram не подключен</span>
              </div>
              <p className="mt-2 text-sm text-gray-600">
                Нажмите кнопку ниже и отправьте команду /start в боте
              </p>
            </div>

            <button
              onClick={handleOpenBot}
              disabled={!integration?.deep_link}
              className="w-full px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:bg-gray-400 disabled:cursor-not-allowed"
            >
              Подключить Telegram
            </button>

            <button
              onClick={handleRefresh}
              className="w-full px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50"
            >
              Проверить подключение
            </button>
          </div>
        )}
      </div>

      <div className="bg-blue-50 border border-blue-200 rounded-lg p-6">
        <h3 className="text-lg font-semibold mb-3 text-blue-900">Инструкция</h3>
        <ol className="list-decimal list-inside space-y-2 text-gray-700">
          <li>Нажмите кнопку "Подключить Telegram"</li>
          <li>В открывшемся Telegram нажмите "Start" или отправьте /start</li>
          <li>Вернитесь сюда и нажмите "Проверить подключение"</li>
        </ol>
      </div>
    </div>
  )
}

export default TelegramIntegration
