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

const API_URL = '/api'

function AddWords({ onNavigate, dictionaryId, dictionaryName }) {
  const { authFetch } = useAuth()
  const [activeTab, setActiveTab] = useState('words')
  const [markdownText, setMarkdownText] = useState('')
  const [wordPairs, setWordPairs] = useState([{ word: '', translation: '' }])
  const [message, setMessage] = useState('')
  const [loading, setLoading] = useState(false)
  const [currentDictionaryName, setCurrentDictionaryName] = useState(dictionaryName || '')
  const [dictionaryLoading, setDictionaryLoading] = useState(false)

  // Fetch dictionary name if not provided and dictionaryId exists
  useEffect(() => {
    if (dictionaryName) {
      setCurrentDictionaryName(dictionaryName)
    } else if (dictionaryId) {
      fetchDictionaryName(dictionaryId)
    }
  }, [dictionaryId, dictionaryName])

  const fetchDictionaryName = async (dictId) => {
    if (!dictId) return

    setDictionaryLoading(true)
    try {
      const response = await authFetch(`${API_URL}/dictionaries`)
      if (!response.ok) {
        throw new Error('Ошибка при загрузке словарей')
      }
      const dictionaries = await response.json()
      const dict = dictionaries.find(d => d.id === dictId)
      if (dict) {
        setCurrentDictionaryName(dict.name)
      }
    } catch (err) {
      console.error('Error fetching dictionary name:', err)
    } finally {
      setDictionaryLoading(false)
    }
  }

  // Hide add button if dictionary name is not set
  const canAddWords = currentDictionaryName && currentDictionaryName.trim() !== ''

  const handleAddPair = () => {
    setWordPairs([...wordPairs, { word: '', translation: '' }])
  }

  const handleRemovePair = (index) => {
    const newPairs = wordPairs.filter((_, i) => i !== index)
    setWordPairs(newPairs)
  }

  const handlePairChange = (index, field, value) => {
    const newPairs = [...wordPairs]
    newPairs[index][field] = value
    setWordPairs(newPairs)
  }

  const parseMarkdownTable = (text) => {
    const lines = text.split('\n')
    const words = []
    let foundTable = false
    let headerFound = false

    for (let i = 0; i < lines.length; i++) {
      const line = lines[i].trim()

      // Skip empty lines
      if (!line) continue

      // Look for table start (markdown table with |)
      if (line.includes('|') && line.includes('Слово')) {
        foundTable = true
        headerFound = true
        continue
      }

      // Skip separator line (|---|---|)
      if (foundTable && line.match(/^\|[\s\-|:]+\|$/)) {
        continue
      }

      // Parse table rows
      if (foundTable && headerFound && line.includes('|')) {
        const cells = line
          .split('|')
          .map(cell => (cell || '').trim())
          .filter(cell => cell && cell.length > 0)

        if (cells.length >= 2) {
          // Remove markdown formatting (**bold**, etc.)
          const word = cells[0].replace(/\*\*/g, '').trim()
          const translation = cells[1].replace(/\*\*/g, '').trim()

          if (word && translation) {
            words.push({
              name: word,
              translation: translation,
              description: ''
            })
          }
        }
      }
    }

    return words
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    setMessage('')
    setLoading(true)

    try {
      let words = []

      if (activeTab === 'table') {
        words = parseMarkdownTable(markdownText)
        if (words.length === 0) {
          setMessage('Не удалось найти слова в таблице. Убедитесь, что таблица содержит колонки "Слово" и "Перевод".')
          setLoading(false)
          return
        }
      } else if (activeTab === 'words') {
        // Filter out empty pairs and convert to words format
        words = wordPairs
          .filter(pair => pair.word.trim() && pair.translation.trim())
          .map(pair => ({
            name: pair.word.trim(),
            translation: pair.translation.trim(),
            description: ''
          }))
        
        if (words.length === 0) {
          setMessage('Добавьте хотя бы одно слово с переводом.')
          setLoading(false)
          return
        }
      }

      // Add dictionary_id to each word if dictionaryId is provided
      const wordsWithDictionary = words.map(word => ({
        ...word,
        dictionary_id: dictionaryId !== undefined && dictionaryId !== null ? dictionaryId : undefined
      }))

      const response = await authFetch(`${API_URL}/words`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ words: wordsWithDictionary }),
      })

      if (!response.ok) {
        throw new Error('Ошибка при добавлении слов')
      }

      const data = await response.json()
      const addedCount = data?.added || 0
      setMessage(`Успешно добавлено ${addedCount} слов(а)!`)
      
      // Reset form based on active tab
      if (activeTab === 'table') {
        setMarkdownText('')
      } else if (activeTab === 'words') {
        setWordPairs([{ word: '', translation: '' }])
      }
    } catch (error) {
      setMessage(`Ошибка: ${error.message}`)
    } finally {
      setLoading(false)
    }
  }

  // Check if form can be submitted
  const canSubmit = () => {
    if (!canAddWords) return false
    if (activeTab === 'table') {
      return markdownText.trim().length > 0
    } else if (activeTab === 'words') {
      return wordPairs.some(pair => pair.word.trim() && pair.translation.trim())
    }
    return false
  }

  const handleClose = () => {
    window.history.back()
  }

  // Show loading state while fetching dictionary name
  if (dictionaryLoading) {
    return (
      <div className="add-words">
        <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>
      </div>
    )
  }

  return (
    <div className="add-words">
      <button className="close-x-button" onClick={handleClose}>
        ✕
      </button>
      <h2>Добавить слова</h2>
      
      <div className="tabs-container">
        <button
          className={`tab-button ${activeTab === 'words' ? 'active' : ''}`}
          onClick={() => setActiveTab('words')}
        >
          Слова
        </button>
        <button
          className={`tab-button ${activeTab === 'table' ? 'active' : ''}`}
          onClick={() => setActiveTab('table')}
        >
          Таблица
        </button>
      </div>

      <form onSubmit={handleSubmit}>
        <div className="tab-content">
          {activeTab === 'table' && (
            <>
              <p className="description">
                Вставьте текст в формате Markdown с таблицей, содержащей колонки "Слово" и "Перевод"
              </p>
              <textarea
                className="markdown-input"
                value={markdownText}
                onChange={(e) => setMarkdownText(e.target.value)}
                placeholder={`Вот таблица, содержащая только слова и их перевод:

| Слово (Word) | Перевод |
| --- | --- |
| **Adventure** | Приключение |
| **Challenge** | Вызов, сложная задача |
| **Decision** | Решение |`}
                rows={15}
              />
            </>
          )}

          {activeTab === 'words' && (
            <div className="word-pairs-list">
              {wordPairs.map((pair, index) => (
                <div key={index} className="word-pair-item">
                  <input
                    type="text"
                    className="word-input"
                    placeholder="Слово"
                    value={pair.word}
                    onChange={(e) => handlePairChange(index, 'word', e.target.value)}
                  />
                  <input
                    type="text"
                    className="translation-input"
                    placeholder="Перевод"
                    value={pair.translation}
                    onChange={(e) => handlePairChange(index, 'translation', e.target.value)}
                  />
                  <button
                    type="button"
                    className="remove-pair-button"
                    onClick={() => handleRemovePair(index)}
                    title="Удалить"
                  >
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                      <line x1="18" y1="6" x2="6" y2="18"></line>
                      <line x1="6" y1="6" x2="18" y2="18"></line>
                    </svg>
                  </button>
                </div>
              ))}
              <button
                type="button"
                className="add-pair-button"
                onClick={handleAddPair}
              >
                +
              </button>
            </div>
          )}
        </div>
        
        {canAddWords && (
          <button 
            type="submit" 
            className="submit-button"
            disabled={loading || !canSubmit()}
          >
            {loading ? 'Добавление...' : 'Добавить слова'}
          </button>
        )}
        
        {!canAddWords && (
          <div className="message error">
            Сначала установите название словаря на экране списка слов
          </div>
        )}
      </form>

      {message && (
        <div className={`message ${message.includes('Ошибка') ? 'error' : 'success'}`}>
          {message}
        </div>
      )}
    </div>
  )
}

export default AddWords

