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

interface ThreadsResponse {
  threads: Thread[]
  page: number
  per_page: number
  served_by: string
}

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

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

function fmt(dateStr: string) {
  return new Date(dateStr).toLocaleString()
}

export function CategoryView() {
  const { categoryId } = useParams<{ categoryId: string }>()
  const { user } = useAuthStore()
  const [category, setCategory] = useState<Category | null>(null)
  const [threads, setThreads] = useState<Thread[]>([])
  const [error, setError] = useState<string | null>(null)
  const [page, setPage] = useState(1)

  useEffect(() => {
    apiFetch<Category & { served_by: string }>(`/categories/${categoryId}`)
      .then(setCategory)
      .catch((e) => setError(e.message))
  }, [categoryId])

  useEffect(() => {
    apiFetch<ThreadsResponse>(`/categories/${categoryId}/threads?page=${page}&per_page=20`)
      .then((r) => setThreads(r.threads))
      .catch((e) => setError(e.message))
  }, [categoryId, page])

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

  return (
    <>
      <p style={{ fontSize: 11, marginBottom: 6 }}>
        <Link to="/" style={{ color: '#003399' }}>Home</Link>
        {' » '}
        {category?.name}
      </p>

      <table
        width="100%"
        cellPadding={0}
        cellSpacing={0}
        style={{ border: '1px solid #7080b0', borderCollapse: 'collapse', marginBottom: 8 }}
      >
        <thead>
          <tr>
            <th style={thStyle} colSpan={5}>
              {category?.name ?? '…'}
            </th>
          </tr>
          <tr style={{ background: '#d0d8f0' }}>
            <th style={{ ...tdStyle, fontWeight: 'bold' }}>Thread Title</th>
            <th style={{ ...tdStyle, width: 100, fontWeight: 'bold' }}>Author</th>
            <th style={{ ...tdStyle, width: 60, textAlign: 'center', fontWeight: 'bold' }}>Replies</th>
            <th style={{ ...tdStyle, width: 60, textAlign: 'center', fontWeight: 'bold' }}>Views</th>
            <th style={{ ...tdStyle, width: 130, fontWeight: 'bold' }}>Last Post</th>
          </tr>
        </thead>
        <tbody>
          {threads.length === 0 && (
            <tr>
              <td colSpan={5} style={{ ...tdStyle, textAlign: 'center', color: '#666' }}>
                No threads yet.
              </td>
            </tr>
          )}
          {threads.map((t, i) => (
            <tr key={t.id} style={{ background: i % 2 === 0 ? '#EEF2FF' : '#ffffff' }}>
              <td style={tdStyle}>
                {t.is_pinned && (
                  <span style={{ color: '#cc0000', fontWeight: 'bold', marginRight: 4 }}>[PIN]</span>
                )}
                {t.is_locked && (
                  <span style={{ color: '#888', marginRight: 4 }}>[LOCK]</span>
                )}
                <Link
                  to={`/thread/${t.id}`}
                  style={{ color: '#FF6600', fontWeight: 'bold', textDecoration: 'none' }}
                >
                  {t.title}
                </Link>
              </td>
              <td style={{ ...tdStyle, color: '#003399' }}>{t.author_username}</td>
              <td style={{ ...tdStyle, textAlign: 'center' }}>{t.reply_count}</td>
              <td style={{ ...tdStyle, textAlign: 'center' }}>{t.view_count}</td>
              <td style={{ ...tdStyle, fontSize: 10, color: '#555' }}>{fmt(t.last_post_at)}</td>
            </tr>
          ))}
        </tbody>
      </table>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          {page > 1 && (
            <button
              onClick={() => setPage((p) => p - 1)}
              style={btnStyle}
            >
              &laquo; Prev
            </button>
          )}
          {threads.length === 20 && (
            <button
              onClick={() => setPage((p) => p + 1)}
              style={{ ...btnStyle, marginLeft: 4 }}
            >
              Next &raquo;
            </button>
          )}
        </div>
        {user && (
          <Link
            to={`/category/${categoryId}/new-thread`}
            style={{
              background: '#003399',
              color: '#fff',
              padding: '3px 12px',
              textDecoration: 'none',
              border: '1px solid #001166',
              fontSize: 11,
            }}
          >
            + New Thread
          </Link>
        )}
      </div>
    </>
  )
}

const btnStyle: React.CSSProperties = {
  background: '#003399',
  color: '#fff',
  border: '1px solid #001166',
  padding: '2px 10px',
  cursor: 'pointer',
  fontFamily: 'Verdana, sans-serif',
  fontSize: 11,
}
