import { useState } from 'react'
import { Link, useNavigate, useParams } from 'react-router-dom'
import { apiFetch } from '../api/client'
import type { Thread } from '../types'

interface ThreadResponse extends Thread {
  served_by: string
}

export function NewThread() {
  const { categoryId } = useParams<{ categoryId: string }>()
  const navigate = useNavigate()
  const [title, setTitle] = useState('')
  const [content, setContent] = useState('')
  const [error, setError] = useState<string | null>(null)
  const [submitting, setSubmitting] = useState(false)

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setError(null)
    setSubmitting(true)
    try {
      const res = await apiFetch<ThreadResponse>(
        `/categories/${categoryId}/threads`,
        {
          method: 'POST',
          body: JSON.stringify({ title, content }),
        },
      )
      navigate(`/thread/${res.id}`)
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Failed to create thread')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <>
      <p style={{ fontSize: 11, marginBottom: 6 }}>
        <Link to="/" style={{ color: '#003399' }}>Home</Link>
        {' » '}
        <Link to={`/category/${categoryId}`} style={{ color: '#003399' }}>Category</Link>
        {' » '}
        New Thread
      </p>

      <table
        width="100%"
        cellPadding={0}
        cellSpacing={0}
        style={{ border: '1px solid #7080b0', borderCollapse: 'collapse' }}
      >
        <thead>
          <tr>
            <th
              style={{
                background: '#003399',
                color: '#fff',
                padding: '4px 8px',
                textAlign: 'left',
                fontSize: 11,
              }}
            >
              Create New Thread
            </th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td style={{ padding: 12 }}>
              {error && <p style={{ color: 'red', marginBottom: 8 }}>{error}</p>}
              <form onSubmit={handleSubmit}>
                <table cellPadding={4} width="100%">
                  <tbody>
                    <tr>
                      <td style={{ width: 80 }}>Title:</td>
                      <td>
                        <input
                          value={title}
                          onChange={(e) => setTitle(e.target.value)}
                          style={{
                            width: '100%',
                            boxSizing: 'border-box',
                            border: '1px solid #999',
                            padding: 3,
                            fontFamily: 'Verdana, sans-serif',
                            fontSize: 11,
                          }}
                          autoFocus
                        />
                      </td>
                    </tr>
                    <tr>
                      <td style={{ verticalAlign: 'top', paddingTop: 6 }}>Content:</td>
                      <td>
                        <textarea
                          value={content}
                          onChange={(e) => setContent(e.target.value)}
                          rows={8}
                          style={{
                            width: '100%',
                            boxSizing: 'border-box',
                            border: '1px solid #999',
                            fontFamily: 'Verdana, sans-serif',
                            fontSize: 11,
                            padding: 3,
                          }}
                        />
                      </td>
                    </tr>
                    <tr>
                      <td />
                      <td style={{ paddingTop: 6 }}>
                        <input
                          type="submit"
                          value={submitting ? 'Posting…' : 'Create Thread'}
                          disabled={submitting}
                          style={{
                            background: '#003399',
                            color: '#fff',
                            border: '1px solid #001166',
                            padding: '2px 14px',
                            cursor: 'pointer',
                            fontFamily: 'Verdana, sans-serif',
                            fontSize: 11,
                            opacity: submitting ? 0.6 : 1,
                          }}
                        />
                      </td>
                    </tr>
                  </tbody>
                </table>
              </form>
            </td>
          </tr>
        </tbody>
      </table>
    </>
  )
}
