"use client";
import { useState, useRef, useEffect } from "react";
import { useAuth } from "@/hooks/use-auth";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/hooks/use-toast";
import { useMutation } from "@tanstack/react-query";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { Card, CardContent } from "@/components/ui/card";
import { MessageSquare, Heart, Loader2 } from "lucide-react";
import { timeAgo } from "@/lib/utils";
import { Post } from "@/models/Post";
import { Comment } from "@/models/Comment";

interface ForumPostProps {
  post: Post;
}

const ForumPost = ({ post }: ForumPostProps) => {
  const [isReplyFormVisible, setIsReplyFormVisible] = useState(false);
  const [replyContent, setReplyContent] = useState("");
  const { user } = useAuth();
  const { toast } = useToast();
  const replyInputRef = useRef<HTMLTextAreaElement>(null);
  const [liked, setLiked] = useState(false);

  // Focus the reply input when the form becomes visible
  useEffect(() => {
    if (isReplyFormVisible && replyInputRef.current) {
      replyInputRef.current.focus();
    }
  }, [isReplyFormVisible]);

  // Create comment mutation
  const createCommentMutation = useMutation({
    mutationFn: async (content: string) => {
      const res = await apiRequest("POST", `/posts/${post.id}/comments`, {
        content: content,
      });
      return res;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/posts"] });
      setReplyContent("");
      setIsReplyFormVisible(false);
      toast({
        title: "Comment added",
        description: "Your reply has been posted successfully.",
      });
    },
    onError: (error: Error) => {
      toast({
        title: "Failed to post comment",
        description: error.message,
        variant: "destructive",
      });
    },
  });

  const handleReply = () => {
    if (!user) {
      toast({
        title: "Authentication required",
        description: "You must be logged in to reply to posts.",
        variant: "destructive",
      });
      return;
    }

    if (!replyContent.trim()) {
      toast({
        title: "Reply cannot be empty",
        variant: "destructive",
      });
      return;
    }

    createCommentMutation.mutate(replyContent);
  };

  // Like mutation
  const likeMutation = useMutation({
    mutationFn: async () => {
      const res = await apiRequest("POST", `/post_likes`, {
        userId: String(user?.id),
        postId: String(post?.id),
      });
      return res;
    },
    onSuccess: () => {
      setLiked(true);
      queryClient.invalidateQueries({ queryKey: ["/posts"] });
    },
    onError: (error: Error) => {
      toast({
        title: "Failed to like post",
        description: error.message,
        variant: "destructive",
      });
    },
  });

  // Unlike mutation
  const unlikeMutation = useMutation({
    mutationFn: async () => {
      const res = await apiRequest("DELETE", `/post_likes`, {
        userId: String(user?.id),
        postId: String(post?.id),
      });
      return res;
    },
    onSuccess: () => {
      setLiked(false);
      queryClient.invalidateQueries({ queryKey: ["/posts"] });
    },
    onError: (error: Error) => {
      toast({
        title: "Failed to unlike post",
        description: error.message,
        variant: "destructive",
      });
    },
  });

  const handleLikeToggle = () => {
    if (!user) {
      toast({
        title: "Authentication required",
        description: "You must be logged in to like posts.",
        variant: "destructive",
      });
      return;
    }

    liked ? unlikeMutation.mutate() : likeMutation.mutate();
  };

  return (
    <Card className="mb-4">
      <CardContent className="p-6">
        <div className="flex items-start">
          <div className="flex-shrink-0 mr-4">
            <Avatar className="h-10 w-10">
              <AvatarImage
                src={`${post.author?.profileImage}`}
                alt={post.author?.fullName || "User"}
              />
              <AvatarFallback className="bg-primary text-white">
                {post.author?.fullName?.charAt(0).toUpperCase() ||
                  post.author?.username?.charAt(0).toUpperCase() ||
                  "U"}
              </AvatarFallback>
            </Avatar>
          </div>
          <div className="w-full">
            <h4 className="font-medium text-neutral-dark">
              {post.author?.fullName || "Anonymous"}
            </h4>
            <p className="text-sm text-gray-500">{timeAgo(post.createdAt)}</p>
            <div className="mt-2">
              <h5 className="font-medium text-lg mb-2">{post.title}</h5>
              <p className="text-gray-600 whitespace-pre-line">
                {post.content}
              </p>
            </div>
            <div className="mt-3 flex items-center space-x-4">
              <Button
                variant="ghost"
                size="sm"
                className="text-primary hover:text-primary-dark hover:bg-secondary flex items-center"
                onClick={() => setIsReplyFormVisible(!isReplyFormVisible)}
              >
                <MessageSquare className="mr-1 h-4 w-4" />
                {isReplyFormVisible ? "Cancel" : "Reply"}
              </Button>
              <Button
                variant="ghost"
                size="sm"
                className={`flex items-center ${
                  liked ? "text-red-500" : "text-gray-500"
                } hover:text-red-600 hover:bg-secondary`}
                onClick={handleLikeToggle}
                disabled={likeMutation.isPending || unlikeMutation.isPending}
              >
                <Heart
                  className={`mr-1 h-4 w-4 ${
                    liked ? "fill-red-500" : "fill-transparent"
                  } transition-all`}
                />
                {liked ? "Unlike" : "Like"}
              </Button>
            </div>

            {isReplyFormVisible && (
              <div className="mt-4">
                <Textarea
                  placeholder="Write your reply..."
                  value={replyContent}
                  onChange={(e) => setReplyContent(e.target.value)}
                  rows={3}
                  ref={replyInputRef}
                  className="mb-2"
                />
                <div className="flex justify-end space-x-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setIsReplyFormVisible(false)}
                  >
                    Cancel
                  </Button>
                  <Button
                    variant="default"
                    size="sm"
                    className="bg-primary hover:bg-primary-dark"
                    onClick={handleReply}
                    disabled={createCommentMutation.isPending}
                  >
                    {createCommentMutation.isPending ? (
                      <>
                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                        Posting...
                      </>
                    ) : (
                      "Post Reply"
                    )}
                  </Button>
                </div>
              </div>
            )}

            {/* Comments/Replies */}
            {post.comments && post.comments.length > 0 && (
              <div className="mt-6 space-y-4">
                {post.comments.map((comment: Comment) => (
                  <div
                    key={comment.id}
                    className="bg-white p-3 rounded-lg border border-gray-200 ml-6"
                  >
                    <div className="flex items-start">
                      <div className="flex-shrink-0 mr-3">
                        <Avatar className="h-8 w-8">
                          <AvatarImage
                            src={`${comment.author?.profileImage}`}
                            alt={comment.author?.fullName || "User"}
                          />
                          <AvatarFallback className="bg-primary-light text-white text-xs">
                            {comment.author?.fullName
                              ?.charAt(0)
                              .toUpperCase() || "U"}
                          </AvatarFallback>
                        </Avatar>
                      </div>
                      <div>
                        <h5 className="font-medium text-neutral-dark text-sm">
                          {comment.author?.fullName || "Anonymous"}
                        </h5>
                        <p className="text-xs text-gray-500">
                          {timeAgo(comment.createdAt)}
                        </p>
                        <div className="mt-1">
                          <p className="text-sm text-gray-600 whitespace-pre-line">
                            {comment.content}
                          </p>
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </CardContent>
    </Card>
  );
};

export default ForumPost;
