import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { MessageSquare, Pin, CheckCircle2, Loader2, ArrowLeft, Send } from "lucide-react";
import { useDiscussionBoards, usePosts, useCreatePost, usePinPost, useResolvePost } from "@/hooks/queries";
import { useToast } from "@/hooks/use-toast";
import type { DiscussionPost } from "@/types/communication";

function PostThread({ post, boardId, onPin, onResolve }: { post: DiscussionPost; boardId: number; onPin: (id: number, pinned: boolean) => void; onResolve: (id: number) => void }) {
  const [showReply, setShowReply] = useState(false);
  const [replyContent, setReplyContent] = useState("");
  const createPost = useCreatePost();
  const { toast } = useToast();

  const handleReply = () => {
    createPost.mutate(
      { boardId, data: { board_id: boardId, parent_id: post.id, content: replyContent } },
      {
        onSuccess: () => { setShowReply(false); setReplyContent(""); },
        onError: () => toast({ title: "Error", description: "Failed to post reply", variant: "destructive" }),
      },
    );
  };

  return (
    <div className="space-y-2">
      <div className={`p-4 rounded-lg border ${post.is_pinned ? "border-primary/30 bg-primary/5" : ""}`}>
        <div className="flex items-start justify-between gap-2">
          <div className="flex-1 min-w-0">
            {post.title && <p className="font-medium">{post.title}</p>}
            <p className="text-sm mt-1">{post.content}</p>
            <div className="flex items-center gap-2 mt-2 text-xs text-muted-foreground">
              <span>{post.author_name}</span>
              <span>·</span>
              <Badge variant="outline" className="text-xs">{post.author_role}</Badge>
              <span>·</span>
              <span>{new Date(post.created_at).toLocaleDateString()}</span>
              {post.is_pinned && <Badge variant="secondary" className="text-xs"><Pin className="h-3 w-3 mr-1" />Pinned</Badge>}
              {post.is_resolved && <Badge variant="default" className="text-xs"><CheckCircle2 className="h-3 w-3 mr-1" />Resolved</Badge>}
            </div>
          </div>
          <div className="flex gap-1 shrink-0">
            <Button variant="ghost" size="sm" onClick={() => onPin(post.id, !post.is_pinned)}>
              <Pin className="h-3 w-3" />
            </Button>
            {!post.is_resolved && (
              <Button variant="ghost" size="sm" onClick={() => onResolve(post.id)}>
                <CheckCircle2 className="h-3 w-3" />
              </Button>
            )}
            <Button variant="ghost" size="sm" onClick={() => setShowReply(!showReply)}>Reply</Button>
          </div>
        </div>
        {showReply && (
          <div className="flex gap-2 mt-3 pt-3 border-t">
            <Input placeholder="Write a reply..." value={replyContent} onChange={e => setReplyContent(e.target.value)} className="flex-1" />
            <Button size="sm" onClick={handleReply} disabled={createPost.isPending || !replyContent}>
              {createPost.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Send className="h-4 w-4" />}
            </Button>
          </div>
        )}
      </div>
      {post.replies && post.replies.length > 0 && (
        <div className="ml-6 space-y-2">
          {post.replies.map(reply => (
            <PostThread key={reply.id} post={reply} boardId={boardId} onPin={onPin} onResolve={onResolve} />
          ))}
        </div>
      )}
    </div>
  );
}

export default function TeacherDiscussionBoard() {
  const { toast } = useToast();
  const { data: boards = [], isLoading } = useDiscussionBoards();
  const [selectedBoardId, setSelectedBoardId] = useState<number | null>(null);
  const { data: postsData, isLoading: loadingPosts } = usePosts(selectedBoardId ?? 0);
  const createPost = useCreatePost();
  const pinPost = usePinPost();
  const resolvePost = useResolvePost();

  const [showNewPost, setShowNewPost] = useState(false);
  const [newTitle, setNewTitle] = useState("");
  const [newContent, setNewContent] = useState("");

  const posts = postsData?.results ?? [];

  const handleCreatePost = () => {
    if (!selectedBoardId) return;
    createPost.mutate(
      { boardId: selectedBoardId, data: { board_id: selectedBoardId, title: newTitle, content: newContent } },
      {
        onSuccess: () => { toast({ title: "Post Created" }); setShowNewPost(false); setNewTitle(""); setNewContent(""); },
        onError: () => toast({ title: "Error", description: "Failed to create post", variant: "destructive" }),
      },
    );
  };

  const handlePin = (id: number, pinned: boolean) => {
    pinPost.mutate(
      { id, body: { pinned } },
      { onError: () => toast({ title: "Error", description: "Failed to pin post", variant: "destructive" }) },
    );
  };

  const handleResolve = (id: number) => {
    resolvePost.mutate(id, {
      onError: () => toast({ title: "Error", description: "Failed to resolve post", variant: "destructive" }),
    });
  };

  if (isLoading) return <div className="flex items-center justify-center min-h-[400px]"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" /></div>;

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Discussion Boards</h1>
        <p className="text-muted-foreground">Manage and participate in course discussions.</p>
      </div>

      {!selectedBoardId ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {boards.map(board => (
            <Card key={board.id} className="cursor-pointer hover:shadow-md transition-shadow" onClick={() => setSelectedBoardId(board.id)}>
              <CardHeader>
                <div className="flex items-center gap-3">
                  <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center">
                    <MessageSquare className="h-5 w-5 text-primary" />
                  </div>
                  <div>
                    <CardTitle className="text-base">{board.name}</CardTitle>
                    <p className="text-xs text-muted-foreground">{board.course_name}</p>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <span className="text-sm text-muted-foreground">{board.post_count} posts</span>
              </CardContent>
            </Card>
          ))}
          {boards.length === 0 && (
            <div className="col-span-full text-center py-12 text-muted-foreground">
              <MessageSquare className="h-12 w-12 mx-auto mb-3 opacity-40" />
              <p>No discussion boards available.</p>
            </div>
          )}
        </div>
      ) : (
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <Button variant="ghost" onClick={() => setSelectedBoardId(null)}>
              <ArrowLeft className="mr-2 h-4 w-4" /> Back to Boards
            </Button>
            <Dialog open={showNewPost} onOpenChange={setShowNewPost}>
              <Button onClick={() => setShowNewPost(true)}><MessageSquare className="mr-2 h-4 w-4" /> New Post</Button>
              <DialogContent>
                <DialogHeader><DialogTitle>Create Post</DialogTitle></DialogHeader>
                <div className="space-y-4 pt-4">
                  <div className="space-y-2">
                    <Label>Title</Label>
                    <Input placeholder="Post title" value={newTitle} onChange={e => setNewTitle(e.target.value)} />
                  </div>
                  <div className="space-y-2">
                    <Label>Content</Label>
                    <Textarea placeholder="Write your post..." rows={4} value={newContent} onChange={e => setNewContent(e.target.value)} />
                  </div>
                  <Button className="w-full" onClick={handleCreatePost} disabled={createPost.isPending || !newContent}>
                    {createPost.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                    Post
                  </Button>
                </div>
              </DialogContent>
            </Dialog>
          </div>

          {loadingPosts ? (
            <div className="flex items-center justify-center min-h-[200px]"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" /></div>
          ) : (
            <div className="space-y-3">
              {posts.map(post => (
                <PostThread key={post.id} post={post} boardId={selectedBoardId} onPin={handlePin} onResolve={handleResolve} />
              ))}
              {posts.length === 0 && (
                <Card><CardContent className="py-8 text-center text-muted-foreground">No posts yet. Start the conversation!</CardContent></Card>
              )}
            </div>
          )}
        </div>
      )}
    </div>
  );
}
