import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { apiFetch } from '../api/client'
import type { Category } from '../types'

interface CategoriesResponse {
  categories: Category[]
  served_by: string
}

const tdStyle: React.CSSProperties = {
  padding: '4px 8px',
  borderBottom: '1px solid #c0c8e0',
  verticalAlign: 'top',
}

const thStyle: React.CSSProperties = {
  background: '#003399',
  color: '#fff',
  padding: '4px 8px',
  textAlign: 'left',
  fontWeight: 'bold',
  fontSize: 11,
}

export function Home() {
  const [categories, setCategories] = useState<Category[]>([])
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    apiFetch<CategoriesResponse>('/categories')
      .then((r) => setCategories(r.categories))
      .catch((e) => setError(e.message))
  }, [])

  if (error) return <p style={{ color: 'red' }}>Error: {error}</p>

  return (
    <>
      <table
        width="100%"
        cellPadding={0}
        cellSpacing={0}
        style={{ border: '1px solid #7080b0', borderCollapse: 'collapse', marginBottom: 10 }}
      >
        <thead>
          <tr>
            <th style={thStyle} colSpan={4}>
              Forum Categories
            </th>
          </tr>
          <tr style={{ background: '#d0d8f0' }}>
            <th style={{ ...tdStyle, width: 200, fontWeight: 'bold' }}>Category</th>
            <th style={{ ...tdStyle, fontWeight: 'bold' }}>Description</th>
            <th style={{ ...tdStyle, width: 70, textAlign: 'center', fontWeight: 'bold' }}>Threads</th>
            <th style={{ ...tdStyle, width: 60, textAlign: 'center', fontWeight: 'bold' }}>Posts</th>
          </tr>
        </thead>
        <tbody>
          {categories.map((cat, i) => (
            <tr key={cat.id} style={{ background: i % 2 === 0 ? '#EEF2FF' : '#ffffff' }}>
              <td style={tdStyle}>
                <Link
                  to={`/category/${cat.id}`}
                  style={{ color: '#003399', fontWeight: 'bold', textDecoration: 'none' }}
                >
                  {cat.name}
                </Link>
              </td>
              <td style={{ ...tdStyle, color: '#444' }}>{cat.description}</td>
              <td style={{ ...tdStyle, textAlign: 'center' }}>{cat.thread_count}</td>
              <td style={{ ...tdStyle, textAlign: 'center' }}>{cat.post_count}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </>
  )
}
