import { useState } from 'react';
import { SiteNavbar } from '../../components/SiteNavbar';
import { usePosts } from '../../hooks/useApi';
import { Link as RouterLink } from 'react-router-dom';
import { Card, Button, Input, TextArea, Form, Link, toast } 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) => {
    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="min-h-screen bg-background text-foreground">
      <SiteNavbar />
      <main className="container mx-auto px-4 py-8">
        <div className="flex flex-col md:flex-row gap-8">
          <div className="flex-1">
            <h2 className="text-2xl font-bold mb-6">最新帖子</h2>
            {isLoading ? (
              <div>加载中...</div>
            ) : (
              <div className="flex flex-col gap-4">
                {posts?.map((post: any) => (
                  <Card key={post.id} className="p-4">
                    <Card.Header>
                        <div className="flex flex-col">
                            <Link as={RouterLink} to={`/posts/${post.id}`} className="text-md font-bold text-foreground hover:text-primary">
                              {post.title}
                            </Link>
                            <p className="text-small text-default-500">
                                {post.user?.name || '匿名用户'} - {new Date(post.createdAt).toLocaleDateString()}
                            </p>
                        </div>
                    </Card.Header>
                    <Card.Content>
                      <p className="whitespace-pre-wrap line-clamp-3">{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="p-4 sticky top-4">
                <h3 className="text-xl font-bold mb-4">发布新帖</h3>
                <Form validationBehavior="native" onSubmit={handleSubmit} className="flex flex-col gap-4">
                  <Input
                    isRequired
                    label="标题"
                    placeholder="请输入标题"
                    value={title}
                    onValueChange={setTitle}
                  />
                  <TextArea
                    isRequired
                    label="内容"
                    placeholder="请输入内容"
                    value={content}
                    onValueChange={setContent}
                  />
                  <Button color="primary" type="submit" isLoading={isSubmitting}>
                    发布
                  </Button>
                </Form>
              </Card>
            </div>
          )}
        </div>
      </main>
    </div>
  );
}
