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

interface PostsResponse {
  posts: Post[]
  page: number
  per_page: number
  served_by: string
}

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

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

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

const smallBtnStyle: React.CSSProperties = {
  ...btnStyle,
  padding: '1px 7px',
  fontSize: 10,
}

// ── Inline edit component for a single post ───────────────────────────────────
function EditablePost({
  post,
  isOwn,
  onSaved,
}: {
  post: Post
  isOwn: boolean
  onSaved: (updated: Post) => void
}) {
  const [editing, setEditing] = useState(false)
  const [draft, setDraft] = useState(post.content)
  const [saving, setSaving] = useState(false)
  const [err, setErr] = useState<string | null>(null)

  async function save() {
    if (!draft.trim()) return
    setSaving(true)
    setErr(null)
    try {
      const updated = await apiFetch<Post & { served_by: string }>(`/posts/${post.id}`, {
        method: 'PUT',
        body: JSON.stringify({ content: draft }),
      })
      onSaved({ ...post, content: updated.content, updated_at: updated.updated_at })
      setEditing(false)
    } catch (e: unknown) {
      setErr(e instanceof Error ? e.message : 'Save failed')
    } finally {
      setSaving(false)
    }
  }

  function cancel() {
    setDraft(post.content)
    setErr(null)
    setEditing(false)
  }

  return (
    <td style={tdStyle}>
      {/* Meta row */}
      <div style={{ fontSize: 10, color: '#888', marginBottom: 6, display: 'flex', justifyContent: 'space-between' }}>
        <span>
          Posted: {fmt(post.created_at)}
          {post.updated_at !== post.created_at && (
            <span style={{ marginLeft: 8, fontStyle: 'italic' }}>
              (edited {fmt(post.updated_at)})
            </span>
          )}
        </span>
        {isOwn && !editing && (
          <button onClick={() => setEditing(true)} style={smallBtnStyle}>
            Edit
          </button>
        )}
      </div>

      {/* Content or editor */}
      {editing ? (
        <>
          {err && <p style={{ color: 'red', marginBottom: 4, fontSize: 10 }}>{err}</p>}
          <textarea
            value={draft}
            onChange={(e) => setDraft(e.target.value)}
            rows={5}
            style={{
              width: '100%',
              boxSizing: 'border-box',
              border: '1px solid #003399',
              fontFamily: 'Verdana, sans-serif',
              fontSize: 11,
              padding: 4,
              marginBottom: 4,
            }}
            autoFocus
          />
          <button onClick={save} disabled={saving} style={{ ...smallBtnStyle, marginRight: 4, opacity: saving ? 0.6 : 1 }}>
            {saving ? 'Saving…' : 'Save'}
          </button>
          <button onClick={cancel} style={{ ...smallBtnStyle, background: '#666', borderColor: '#444' }}>
            Cancel
          </button>
        </>
      ) : (
        <div style={{ whiteSpace: 'pre-wrap', lineHeight: 1.5 }}>{post.content}</div>
      )}
    </td>
  )
}

// ── Main ThreadView ───────────────────────────────────────────────────────────
export function ThreadView() {
  const { threadId } = useParams<{ threadId: string }>()
  const { user } = useAuthStore()
  const [posts, setPosts] = useState<Post[]>([])
  const [page, setPage] = useState(1)
  const [reply, setReply] = useState('')
  const [error, setError] = useState<string | null>(null)
  const [submitting, setSubmitting] = useState(false)

  function loadPosts(p: number) {
    apiFetch<PostsResponse>(`/threads/${threadId}/posts?page=${p}&per_page=20`)
      .then((r) => setPosts(r.posts))
      .catch((e) => setError(e.message))
  }

  useEffect(() => {
    loadPosts(page)
  }, [threadId, page])

  function handlePostSaved(updated: Post) {
    setPosts((prev) => prev.map((p) => (p.id === updated.id ? updated : p)))
  }

  async function submitReply(e: React.FormEvent) {
    e.preventDefault()
    if (!reply.trim()) return
    setSubmitting(true)
    try {
      await apiFetch(`/threads/${threadId}/posts`, {
        method: 'POST',
        body: JSON.stringify({ content: reply }),
      })
      setReply('')
      loadPosts(page)
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Failed to post')
    } finally {
      setSubmitting(false)
    }
  }

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

  return (
    <>
      <p style={{ fontSize: 11, marginBottom: 6 }}>
        <Link to="/" style={{ color: '#003399' }}>Home</Link>
        {' » '}
        <span style={{ color: '#555' }}>Thread</span>
      </p>

      {/* Posts table */}
      <table
        width="100%"
        cellPadding={0}
        cellSpacing={0}
        style={{ border: '1px solid #7080b0', borderCollapse: 'collapse', marginBottom: 8 }}
      >
        <thead>
          <tr>
            <th
              colSpan={2}
              style={{
                background: '#003399',
                color: '#fff',
                padding: '4px 8px',
                textAlign: 'left',
                fontSize: 11,
                fontWeight: 'bold',
              }}
            >
              Thread
            </th>
          </tr>
        </thead>
        <tbody>
          {posts.map((post, i) => (
            <tr key={post.id} style={{ background: i % 2 === 0 ? '#EEF2FF' : '#ffffff' }}>
              {/* Mini-profile sidebar */}
              <td
                style={{
                  ...tdStyle,
                  width: 130,
                  background: '#dde4f0',
                  borderRight: '1px solid #b0b8d0',
                  textAlign: 'center',
                }}
              >
                <div style={{ fontWeight: 'bold', color: '#003399', fontSize: 12 }}>
                  {post.author_username}
                </div>
                <div style={{ color: '#555', fontSize: 10, marginTop: 2 }}>
                  Posts: {post.author_post_count}
                </div>
                <div style={{ color: '#888', fontSize: 10 }}>
                  Joined: {new Date(post.author_created_at).toLocaleDateString()}
                </div>
              </td>

              {/* Post content (with inline edit for own posts) */}
              <EditablePost
                post={post}
                isOwn={user?.id === post.author_id}
                onSaved={handlePostSaved}
              />
            </tr>
          ))}
        </tbody>
      </table>

      {/* Pagination */}
      <div style={{ marginBottom: 12 }}>
        {page > 1 && (
          <button onClick={() => setPage((p) => p - 1)} style={btnStyle}>
            &laquo; Prev
          </button>
        )}
        {posts.length === 20 && (
          <button onClick={() => setPage((p) => p + 1)} style={{ ...btnStyle, marginLeft: 4 }}>
            Next &raquo;
          </button>
        )}
      </div>

      {/* Reply box */}
      {user && (
        <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,
                }}
              >
                Post Reply
              </th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td style={{ padding: 10 }}>
                <form onSubmit={submitReply}>
                  <textarea
                    value={reply}
                    onChange={(e) => setReply(e.target.value)}
                    rows={5}
                    style={{
                      width: '100%',
                      boxSizing: 'border-box',
                      border: '1px solid #999',
                      fontFamily: 'Verdana, sans-serif',
                      fontSize: 11,
                      padding: 4,
                    }}
                    placeholder="Write your reply here..."
                  />
                  <br />
                  <input
                    type="submit"
                    value={submitting ? 'Posting…' : 'Post Reply'}
                    disabled={submitting}
                    style={{ ...btnStyle, marginTop: 6, opacity: submitting ? 0.6 : 1 }}
                  />
                </form>
              </td>
            </tr>
          </tbody>
        </table>
      )}
    </>
  )
}
