import { useState } from 'react'
import { usePosts, Post } from '../../hooks/useApi'
import { Link as RouterLink } from 'react-router-dom'
import {
  Card,
  Button,
  Input,
  TextArea,
  Form,
  toast,
  TextField,
  Label,
  FieldError,
} from '@heroui/react'
import { useSession } from '../../lib/auth-client'
import { api } from '../../api/client'

export default function PostsPage() {
  const { posts, isLoading, mutate } = usePosts()
  const { data: session } = useSession()
  const [title, setTitle] = useState('')
  const [content, setContent] = useState('')
  const [isSubmitting, setIsSubmitting] = useState(false)

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    if (!session) return
    setIsSubmitting(true)
    try {
      await api.posts.post({
        title,
        content,
        userId: session.user.id,
        published: true,
      })
      setTitle('')
      setContent('')
      mutate() // Refresh list
    } catch (err) {
      console.error(err)
      toast.danger('发布失败')
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <div className="pb-20">
      <main className="container mx-auto px-4 py-8">
        <div className="flex flex-col gap-8 md:flex-row">
          <div className="flex-1">
            <h2 className="mb-6 text-2xl font-bold">最新帖子</h2>
            {isLoading ? (
              <div>加载中...</div>
            ) : (
              <div className="flex flex-col gap-4">
                {posts?.map((post: Post) => (
                  <Card key={post.id} className="p-4">
                    <Card.Header>
                      <div className="flex flex-col">
                        <RouterLink
                          to={`/posts/${post.id}`}
                          className="text-md text-foreground hover:text-primary font-bold"
                        >
                          {post.title}
                        </RouterLink>
                        <p className="text-small text-default-500">
                          {post.user?.name || '匿名用户'} -{' '}
                          {new Date(post.createdAt).toLocaleDateString()}
                        </p>
                      </div>
                    </Card.Header>
                    <Card.Content>
                      <p className="line-clamp-3 whitespace-pre-wrap">
                        {post.content}
                      </p>
                    </Card.Content>
                  </Card>
                ))}
                {!posts?.length && (
                  <div className="text-center text-gray-500">暂无帖子</div>
                )}
              </div>
            )}
          </div>

          {session && (
            <div className="w-full md:w-80">
              <Card className="sticky top-4 p-4">
                <h3 className="mb-4 text-xl font-bold">发布新帖</h3>
                <Form
                  validationBehavior="native"
                  onSubmit={handleSubmit}
                  className="flex flex-col gap-4"
                >
                  <TextField
                    isRequired
                    name="title"
                    value={title}
                    onChange={setTitle}
                  >
                    <Label>标题</Label>
                    <Input placeholder="请输入标题" />
                    <FieldError />
                  </TextField>

                  <TextField
                    isRequired
                    name="content"
                    value={content}
                    onChange={setContent}
                  >
                    <Label>内容</Label>
                    <TextArea placeholder="请输入内容" />
                    <FieldError />
                  </TextField>

                  <Button type="submit" isPending={isSubmitting}>
                    发布
                  </Button>
                </Form>
              </Card>
            </div>
          )}
        </div>
      </main>
    </div>
  )
}
