import { useEffect, useState } from 'react'
import { useNavigate, Link } from 'react-router-dom'
import { api, Collection, setToken, getToken } from '../api/client'

export default function Dashboard() {
  const [collections, setCollections] = useState<Collection[]>([])
  const [name, setName] = useState('')
  const [user, setUser] = useState<any>(null)
  const navigate = useNavigate()

  useEffect(() => {
    if (!getToken()) {
      navigate('/login')
      return
    }
    api.me().then(u => {
      setUser(u)
      return api.listCollections()
    }).then(setCollections).catch(() => navigate('/login'))
  }, [navigate])

  async function createCollection(e: React.FormEvent) {
    e.preventDefault()
    const c = await api.createCollection(name)
    setCollections([c, ...collections])
    setName('')
  }

  async function removeCollection(id: string) {
    await api.deleteCollection(id)
    setCollections(collections.filter(c => c.id !== id))
  }

  function logout() {
    setToken(null)
    navigate('/login')
  }

  return (
    <div style={{ maxWidth: 800, margin: '0 auto', padding: 20 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <h1>Support Bot SaaS</h1>
        <div>
          <Link to="/settings" style={{ marginRight: 12 }}>Настройки</Link>
          <button onClick={logout}>Выйти</button>
        </div>
      </div>

      {user && <p>План: {user.plan} | Тип: {user.email}</p>}

      <form onSubmit={createCollection} style={{ margin: '20px 0', display: 'flex', gap: 8 }}>
        <input
          value={name}
          onChange={e => setName(e.target.value)}
          placeholder="Название базы знаний"
          required
          style={{ flex: 1, padding: 8 }}
        />
        <button type="submit" style={{ padding: '8px 16px' }}>Создать</button>
      </form>

      <h2>Базы знаний</h2>
      {collections.length === 0 && <p>Пока нет ни одной базы знаний</p>}
      {collections.map(c => (
        <div key={c.id} style={{ border: '1px solid #ddd', padding: 12, marginBottom: 8, borderRadius: 4 }}>
          <Link to={`/collections/${c.id}`} style={{ fontSize: 18, fontWeight: 'bold' }}>
            {c.name}
          </Link>
          <p style={{ margin: '4px 0', color: '#666' }}>
            Тикетов: {c.ticket_count} | Создана: {new Date(c.created_at).toLocaleDateString()}
          </p>
          <button onClick={() => removeCollection(c.id)} style={{ color: 'red' }}>
            Удалить
          </button>
        </div>
      ))}
    </div>
  )
}
