import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { CheckCircle2, UserCheck, MessageSquare, ArrowLeft } from "lucide-react"
import Link from "next/link"
import { fetchApi } from "@/lib/api-client"
import { VoteButtons } from "@/components/vote-buttons"
import { ReplyForm } from "@/components/reply-form"

interface Reply {
  id: number;
  content: string;
  upvotes: number;
  is_expert_reply: boolean;
  created_at: string;
  author: {
    first_name: string;
    last_name: string;
    role: string;
    avatar_url?: string;
  };
}

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

export default async function QuestionDetailPage({
  params,
}: {
  params: Promise<{ id: string }>
}) {
  const { id } = await params
  
  let question: Question | null = null
  let replies: Reply[] = []
  let relatedQuestions: any[] = []

  try {
    question = await fetchApi(`forum.php?id=${id}`)
    
    if (question) {
      // Fetch these in parallel but handle errors individually
      const [repliesData, relatedData] = await Promise.allSettled([
        fetchApi(`replies.php?question_id=${id}`),
        fetchApi(`forum.php?related_id=${id}`)
      ])
      
      if (repliesData.status === 'fulfilled') {
        replies = repliesData.value
      } else {
        console.error("Failed to fetch replies:", repliesData.reason)
      }
      
      if (relatedData.status === 'fulfilled') {
        relatedQuestions = relatedData.value
      } else {
        console.error("Failed to fetch related questions:", relatedData.reason)
      }
    }
  } catch (error) {
    console.error("Failed to fetch question details:", error)
  }

  if (!question) {
    return (
      <div className="container mx-auto px-4 py-20 text-center">
        <h1 className="text-2xl font-bold">Question not found</h1>
        <Button asChild className="mt-4">
          <Link href="/forum">Back to Forum</Link>
        </Button>
      </div>
    )
  }

  return (
    <main className="flex-1 bg-muted/30 pb-20">
      <div className="container mx-auto px-4 py-8">
        <Button variant="ghost" className="mb-6 gap-2" asChild>
          <Link href="/forum">
            <ArrowLeft className="h-4 w-4" />
            Back to Discussions
          </Link>
        </Button>

        <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
          <div className="lg:col-span-8 space-y-8">
            {/* Question Card */}
            <Card className="border-none shadow-lg ring-1 ring-primary/5">
              <CardContent className="p-0 flex items-stretch">
                <VoteButtons questionId={question.id} initialUpvotes={question.upvotes} />
                
                <div className="flex-1 p-6 space-y-4">
                  <div className="flex flex-wrap items-center gap-2">
                    {question.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">
                      Posted on {new Date(question.created_at).toLocaleDateString()}
                    </span>
                  </div>

                  <h1 className="text-3xl font-bold tracking-tight leading-tight">
                    {question.title}
                  </h1>

                  <div className="flex flex-wrap gap-2">
                    {question.tags?.map((tag: string) => (
                      <Badge key={tag} variant="outline" className="bg-background">
                        {tag}
                      </Badge>
                    ))}
                  </div>

                  <div className="prose prose-sm max-w-none text-muted-foreground leading-relaxed">
                    {question.content.split('\n').map((para, i) => (
                      <p key={i}>{para}</p>
                    ))}
                  </div>

                  <div className="pt-4 border-t flex items-center gap-3">
                    <div className="h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center text-primary font-bold">
                      {question.author?.first_name?.[0]}
                    </div>
                    <div>
                      <p className="text-sm font-bold">
                        {question.author?.first_name} {question.author?.last_name}
                      </p>
                      <p className="text-xs text-muted-foreground capitalize">
                        {question.author?.role}
                      </p>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* Replies Section */}
            <div className="space-y-6">
              <div className="flex items-center gap-2">
                <MessageSquare className="h-5 w-5 text-primary" />
                <h2 className="text-xl font-bold">{replies.length} Replies</h2>
              </div>

              {replies.map((reply) => (
                <Card key={reply.id} className={reply.is_expert_reply ? "border-primary/20 bg-primary/5" : "border-none shadow-sm"}>
                  <CardContent className="p-6 space-y-4">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-3">
                        <div className="h-8 w-8 rounded-full bg-muted flex items-center justify-center text-xs font-bold overflow-hidden">
                          {reply.author?.avatar_url ? (
                            <img src={reply.author.avatar_url} alt="" className="w-full h-full object-cover" />
                          ) : (
                            reply.author?.first_name?.[0]
                          )}
                        </div>
                        <div>
                          <p className="text-sm font-bold flex items-center gap-2">
                            {reply.author?.first_name} {reply.author?.last_name}
                            {reply.is_expert_reply && (
                              <Badge variant="secondary" className="bg-primary/10 text-primary border-primary/20 text-[10px] h-4 px-1">
                                <UserCheck className="h-2 w-2 mr-1" />
                                Expert
                              </Badge>
                            )}
                          </p>
                          <p className="text-[10px] text-muted-foreground">
                            {new Date(reply.created_at).toLocaleDateString()}
                          </p>
                        </div>
                      </div>
                    </div>

                    <div className="text-sm leading-relaxed text-muted-foreground">
                      {reply.content.split('\n').map((para, i) => (
                        <p key={i}>{para}</p>
                      ))}
                    </div>
                  </CardContent>
                </Card>
              ))}

              <ReplyForm questionId={question.id} />
            </div>
          </div>

          <aside className="lg:col-span-4 space-y-6">
            <Card className="border-none shadow-md">
              <CardHeader className="pb-3">
                <CardTitle className="text-lg flex items-center gap-2">
                  <MessageSquare className="h-5 w-5 text-primary" />
                  Similar Discussions
                </CardTitle>
              </CardHeader>
              <CardContent>
                {relatedQuestions.length > 0 ? (
                  <div className="space-y-4">
                    {relatedQuestions.map((related) => (
                      <Link 
                        key={related.id} 
                        href={`/forum/${related.id}`}
                        className="block group space-y-2 pb-4 border-b last:border-0 last:pb-0"
                      >
                        <h4 className="text-sm font-bold group-hover:text-primary transition-colors line-clamp-2 leading-snug">
                          {related.title}
                        </h4>
                        <div className="flex items-center gap-3">
                          <span className="text-[10px] text-muted-foreground flex items-center gap-1">
                            {related.upvotes} votes
                          </span>
                          <span className="text-[10px] text-muted-foreground">
                            {new Date(related.created_at).toLocaleDateString()}
                          </span>
                        </div>
                      </Link>
                    ))}
                  </div>
                ) : (
                  <p className="text-sm text-muted-foreground italic">No similar discussions found.</p>
                )}
              </CardContent>
            </Card>
          </aside>
        </div>
      </div>
    </main>
  )
}
