import { Badge } from "@/components/ui/badge"
import { Card, CardContent } from "@/components/ui/card"
import { CheckCircle2, UserCheck } from "lucide-react"
import Link from "next/link"
import { fetchApi } from "@/lib/api-client"
import { VoteButtons } from "./vote-buttons"

interface Post {
  id: number;
  title: string;
  content: string;
  upvotes: number;
  is_solved: boolean;
  created_at: string;
  tags: string[];
  author: {
    first_name: string;
    last_name: string;
    role: string;
  };
}

export async function ForumList({ searchQuery = "" }: { searchQuery?: string }) {
  let posts: Post[] = []
  try {
    posts = await fetchApi(`forum.php?q=${encodeURIComponent(searchQuery)}`)
  } catch (error) {
    console.error("Failed to fetch forum posts:", error)
  }

  if (!posts || posts.length === 0) {
    return (
      <Card className="p-12 text-center border-dashed">
        <p className="text-muted-foreground italic">No discussions found matching your search.</p>
      </Card>
    )
  }

  return (
    <div className="space-y-4">
      {posts.map((post: Post) => (
        <Card key={post.id} className="hover:ring-1 hover:ring-primary/20 transition-all cursor-pointer">
          <CardContent className="p-0 flex items-stretch">
            {/* Voting Column */}
            <VoteButtons questionId={post.id} initialUpvotes={post.upvotes} />

            {/* Content Column */}
            <div className="flex-1 p-5 space-y-3">
              <div className="flex flex-wrap items-center gap-2 mb-1">
                {post.author?.role === "expert" && (
                  <Badge variant="secondary" className="bg-primary/10 text-primary border-primary/20 gap-1">
                    <UserCheck className="h-3 w-3" />
                    Expert Participation
                  </Badge>
                )}
                {post.is_solved && (
                  <Badge variant="secondary" className="bg-green-500/10 text-green-600 border-green-500/20 gap-1">
                    <CheckCircle2 className="h-3 w-3" />
                    Solved
                  </Badge>
                )}
                <span className="text-xs text-muted-foreground ml-auto">
                  {new Date(post.created_at).toLocaleDateString()}
                </span>
              </div>

              <Link href={`/forum/${post.id}`} className="block group">
                <h3 className="text-xl font-bold group-hover:text-primary transition-colors leading-snug">
                  {post.title}
                </h3>
              </Link>

              <p className="text-sm text-muted-foreground line-clamp-2">{post.content}</p>

              <div className="flex flex-wrap items-center justify-between gap-4 pt-2">
                <div className="flex flex-wrap gap-2">
                  {post.tags?.map((tag: string) => (
                    <Link key={tag} href={`/forum?q=${encodeURIComponent(tag.startsWith('#') ? tag.slice(1) : tag)}`}>
                      <Badge variant="outline" className="text-[10px] font-semibold bg-background hover:bg-primary hover:text-primary-foreground transition-colors cursor-pointer">
                        {tag}
                      </Badge>
                    </Link>
                  ))}
                </div>

                <div className="flex items-center gap-4 text-xs font-medium text-muted-foreground">
                  <span className="flex items-center gap-1">
                    <span className="h-5 w-5 rounded-full bg-primary/10 flex items-center justify-center text-[10px] text-primary uppercase">
                      {post.author?.first_name?.[0]}
                    </span>
                    {post.author?.first_name} {post.author?.last_name}
                  </span>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      ))}
    </div>
  )
}
