import { useEffect, useRef, useState } from 'react'
import { useParams, Link } from 'react-router-dom'
import { api, getToken } from '../api/client'

export default function CollectionView() {
  const { id } = useParams<{ id: string }>()
  const [query, setQuery] = useState('')
  const [result, setResult] = useState<any>(null)
  const [loading, setLoading] = useState(false)
  const [uploading, setUploading] = useState(false)
  const [uploadResult, setUploadResult] = useState<string | null>(null)
  const [ticketCount, setTicketCount] = useState(0)
  const [expanded, setExpanded] = useState<Record<number, boolean>>({})
  const fileRef = useRef<HTMLInputElement>(null)

  useEffect(() => {
    if (!getToken()) {
      window.location.href = '/login'
      return
    }
    api.getCollection(id!).then(c => setTicketCount(c.ticket_count)).catch(() => {})
  }, [id])

  async function handleSearch(e: React.FormEvent) {
    e.preventDefault()
    if (!query.trim()) return

    setLoading(true)
    try {
      const res = await api.search(id!, query)
      setResult(res)
    } catch (err: any) {
      setResult({ error: err.message })
    } finally {
      setLoading(false)
    }
  }

  async function handleUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0]
    if (!file) return

    setUploading(true)
    setUploadResult(null)
    try {
      const res = await api.uploadFile(id!, file)
      setUploadResult(`Загружено: ${res.processed} тикетов, пропущено: ${res.skipped}`)
      setTicketCount(res.collection_ticket_count)
    } catch (err: any) {
      setUploadResult(`Ошибка: ${err.message}`)
    } finally {
      setUploading(false)
      if (fileRef.current) fileRef.current.value = ''
    }
  }

  async function handlePasteJson() {
    const text = prompt('Вставьте JSON с тикетами (массив объектов):')
    if (!text) return

    try {
      const tickets = JSON.parse(text)
      const data = Array.isArray(tickets) ? tickets : [tickets]
      const res = await api.uploadTickets(id!, data)
      setUploadResult(`Загружено: ${res.processed} тикетов, пропущено: ${res.skipped}`)
      setTicketCount(res.collection_ticket_count)
    } catch (err: any) {
      setUploadResult(`Ошибка: ${err.message}`)
    }
  }

  return (
    <div style={{ maxWidth: 800, margin: '0 auto', padding: 20 }}>
      <Link to="/dashboard" style={{ marginBottom: 16, display: 'block' }}>
        &larr; Назад к списку
      </Link>

      <h1>База знаний</h1>

      <div style={{ border: '1px solid #ddd', borderRadius: 8, padding: 16, marginBottom: 24 }}>
        <h3 style={{ margin: '0 0 12px' }}>Загрузка тикетов</h3>
        {ticketCount > 0 && (
          <p style={{ fontSize: 13, color: '#666', marginBottom: 8 }}>
            Тикетов в базе: {ticketCount}
          </p>
        )}
        <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
          <label style={{
            display: 'inline-block',
            padding: '8px 16px',
            background: '#1976d2',
            color: '#fff',
            borderRadius: 4,
            cursor: uploading ? 'not-allowed' : 'pointer',
            fontSize: 14,
          }}>
            {uploading ? 'Загрузка...' : 'Выбрать JSON/CSV файл'}
            <input
              ref={fileRef}
              type="file"
              accept=".json,.csv"
              onChange={handleUpload}
              disabled={uploading}
              style={{ display: 'none' }}
            />
          </label>
          <button
            onClick={handlePasteJson}
            disabled={uploading}
            style={{ padding: '8px 16px', fontSize: 14 }}
          >
            Вставить JSON
          </button>
        </div>
        {uploadResult && (
          <p style={{
            marginTop: 8,
            fontSize: 13,
            color: uploadResult.startsWith('Ошибка') ? 'red' : 'green',
          }}>
            {uploadResult}
          </p>
        )}
      </div>

      <h2>Поиск по базе знаний</h2>

      <form onSubmit={handleSearch} style={{ margin: '12px 0' }}>
        <textarea
          value={query}
          onChange={e => setQuery(e.target.value)}
          placeholder="Опишите проблему клиента..."
          rows={3}
          style={{ width: '100%', padding: 8, marginBottom: 8, boxSizing: 'border-box' }}
        />
        <button type="submit" disabled={loading} style={{ padding: '8px 16px' }}>
          {loading ? 'Поиск...' : 'Найти'}
        </button>
      </form>

      {result && (
        <div>
          {result.answer && (
            <div style={{ background: '#f5f5f5', padding: 16, borderRadius: 4, marginBottom: 16 }}>
              <h3>Ответ</h3>
              <p style={{ whiteSpace: 'pre-wrap' }}>{result.answer}</p>
            </div>
          )}

          {result.sources && result.sources.length > 0 && (
            <div>
              <h3>Найденные тикеты</h3>
              {result.sources.map((s: any, i: number) => (
                <div key={i} style={{ border: '1px solid #ddd', padding: 12, marginBottom: 8, borderRadius: 4 }}>
                  <div
                    onClick={() => setExpanded(prev => ({ ...prev, [i]: !prev[i] }))}
                    style={{ cursor: 'pointer', userSelect: 'none' }}
                  >
                    <strong>Тикет №{s.ticket_id}</strong>
                    <span style={{ marginLeft: 12, color: '#666' }}>
                      Релевантность: {s.score.toFixed(3)} | {s.category}
                    </span>
                    <span style={{ marginLeft: 8, color: '#999', fontSize: 12 }}>
                      {expanded[i] ? '▲' : '▼'}
                    </span>
                  </div>
                  {expanded[i] && s.full_text && (
                    <pre style={{
                      marginTop: 8, padding: 12, background: '#f9f9f9',
                      borderRadius: 4, fontSize: 13, whiteSpace: 'pre-wrap',
                      wordBreak: 'break-word',
                    }}>
                      {s.full_text}
                    </pre>
                  )}
                </div>
              ))}
            </div>
          )}

          {result.error && <p style={{ color: 'red' }}>{result.error}</p>}
        </div>
      )}
    </div>
  )
}
