"use client";
// 688cfe417f293134a0de5f99
import { useState, useMemo, useCallback, useRef, useEffect } from "react";
import AudioPlayer from "react-h5-audio-player";
import "react-h5-audio-player/lib/styles.css";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  MoreHorizontal,
  Shield,
  ShieldOff,
  Trash2,
  Eye,
  Heart,
  MessageCircle,
  Users,
  Search,
  Filter,
  ChevronLeft,
  ChevronRight,
} from "lucide-react";
import {
  usePosts,
  useBlockPost,
  useUnblockPost,
  useDeletePost,
  useGetPostCommentsInfinite,
} from "@/hooks/use-posts";
import { Post, PaginationParams, Comment } from "@/types/api";
import { toast } from "sonner";
// Simple date formatting function to replace date-fns
const formatDistanceToNow = (date: Date) => {
  const now = new Date();
  const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);

  if (diffInSeconds < 60) return "just now";
  if (diffInSeconds < 3600)
    return `${Math.floor(diffInSeconds / 60)} minutes ago`;
  if (diffInSeconds < 86400)
    return `${Math.floor(diffInSeconds / 3600)} hours ago`;
  if (diffInSeconds < 2592000)
    return `${Math.floor(diffInSeconds / 86400)} days ago`;
  return `${Math.floor(diffInSeconds / 2592000)} months ago`;
};

export default function PostsPage() {
  const [searchTerm, setSearchTerm] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const [selectedPost, setSelectedPost] = useState<Post | null>(null);
  const [blockReason, setBlockReason] = useState("");
  const [deleteReason, setDeleteReason] = useState("");
  const [isBlockDialogOpen, setIsBlockDialogOpen] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [isCommentsDialogOpen, setIsCommentsDialogOpen] = useState(false);
  const commentsScrollRef = useRef<HTMLDivElement>(null);

  const params: PaginationParams = {
    page: currentPage,
    limit: 10,
    search: searchTerm,
  };
  const {
    data: commentsData,
    isLoading: commentsLoading,
    error: commentsError,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
  } = useGetPostCommentsInfinite(selectedPost?._id || "", 10);

  const { data: postsData, isLoading, error } = usePosts(params);
  const blockPostMutation = useBlockPost();
  const unblockPostMutation = useUnblockPost();
  const deletePostMutation = useDeletePost();

  const posts = useMemo(
    () => postsData?.data?.posts?.posts || [],
    [postsData?.data?.posts?.posts]
  );

  const handleBlockPost = async () => {
    if (!selectedPost || !blockReason.trim()) {
      toast.error("Please provide a reason for blocking");
      return;
    }

    try {
      await blockPostMutation.mutateAsync({
        id: selectedPost._id,
        data: { reason: blockReason },
      });
      setIsBlockDialogOpen(false);
      setBlockReason("");
      setSelectedPost(null);
    } catch (error) {
      console.error("Failed to block post:", error);
    }
  };

  const handleUnblockPost = async (post: Post) => {
    try {
      await unblockPostMutation.mutateAsync(post._id);
    } catch (error) {
      console.error("Failed to unblock post:", error);
    }
  };

  const handleDeletePost = async () => {
    if (!selectedPost || !deleteReason.trim()) {
      toast.error("Please provide a reason for deletion");
      return;
    }

    try {
      await deletePostMutation.mutateAsync({
        id: selectedPost._id,
        reason: deleteReason,
      });
      setIsDeleteDialogOpen(false);
      setDeleteReason("");
      setSelectedPost(null);
    } catch (error) {
      console.error("Failed to delete post:", error);
    }
  };

  const handlePlay = () => {
    console.log("Audio started playing");
  };

  const handlePause = () => {
    console.log("Audio paused");
  };

  const handleEnded = () => {
    console.log("Audio ended");
  };

  const handleError = (e: Event) => {
    console.error("Audio playback error:", e);
    toast.error("Failed to play audio");
  };

  const handleOpenComments = (post: Post) => {
    setSelectedPost(post);
    setIsCommentsDialogOpen(true);
  };

  // Flatten comments from all pages
  const allComments = useMemo(() => {
    if (!commentsData?.pages) return [];
    return commentsData.pages.flatMap((page) => page) as Comment[];
  }, [commentsData]);

  // Infinite scroll handler
  const handleScroll = useCallback(() => {
    if (!commentsScrollRef.current) return;

    const { scrollTop, scrollHeight, clientHeight } = commentsScrollRef.current;
    const isNearBottom = scrollTop + clientHeight >= scrollHeight - 100;

    if (isNearBottom && hasNextPage && !isFetchingNextPage) {
      fetchNextPage();
    }
  }, [hasNextPage, isFetchingNextPage, fetchNextPage]);

  // Add scroll listener
  useEffect(() => {
    const scrollElement = commentsScrollRef.current;
    if (scrollElement) {
      scrollElement.addEventListener("scroll", handleScroll);
      return () => scrollElement.removeEventListener("scroll", handleScroll);
    }
  }, [handleScroll]);

  const formatDuration = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs.toString().padStart(2, "0")}`;
  };

  const getPostStatusBadge = (post: Post) => {
    if (post.isDeleted) {
      return <Badge variant="destructive">Deleted</Badge>;
    }
    if (post.isBlocked) {
      return <Badge variant="secondary">Blocked</Badge>;
    }
    return (
      <Badge variant="default" className="gradient-badge">
        Active
      </Badge>
    );
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"></div>
          <p>Loading posts...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center text-destructive">
          <p>Failed to load posts</p>
          <p className="text-sm text-muted-foreground mt-2">
            {error instanceof Error ? error.message : "An error occurred"}
          </p>
        </div>
      </div>
    );
  }

  const totalPages = postsData?.data?.posts?.totalPages || 1;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">
            Posts Management
          </h1>
          <p className="text-muted-foreground">
            Manage and moderate voice posts across the platform
          </p>
        </div>
      </div>

      {/* Search and Filters */}
      <Card>
        <CardHeader>
          <CardTitle>Search & Filter</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center space-x-4">
            <div className="flex-1">
              <Label htmlFor="search">Search posts</Label>
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4" />
                <Input
                  id="search"
                  placeholder="Search by content, user, or tags..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10"
                />
              </div>
            </div>
            <Button variant="outline" size="sm" className="gradient-button">
              <Filter className="h-4 w-4 mr-2" />
              Filter
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* Posts List */}
      <div className="space-y-4">
        {posts.length === 0 ? (
          <Card>
            <CardContent className="flex items-center justify-center h-32">
              <div className="text-center">
                <MessageCircle className="h-8 w-8 text-muted-foreground mx-auto mb-2" />
                <p className="text-muted-foreground">No posts found</p>
              </div>
            </CardContent>
          </Card>
        ) : (
          posts.map((post) => (
            <Card key={post._id} className="hover:shadow-md transition-shadow">
              <CardContent className="p-6">
                <div className="flex items-start justify-between">
                  <div className="flex-1 space-y-4">
                    {/* Post Header */}
                    <div className="flex items-center justify-between">
                      <div className="flex items-center space-x-3">
                        <div className="w-10 h-10 bg-primary/10 rounded-full flex items-center justify-center">
                          {post.anonymous || !post.user ? (
                            <Users className="h-5 w-5 text-primary" />
                          ) : (
                            <div className="w-8 h-8 bg-primary rounded-full flex items-center justify-center text-primary-foreground text-sm font-medium">
                              {post.user.fullName.charAt(0).toUpperCase()}
                            </div>
                          )}
                        </div>
                        <div>
                          <p className="font-medium">
                            {post.anonymous || !post.user
                              ? "Anonymous User"
                              : post.user.fullName}
                          </p>
                          <p className="text-sm text-muted-foreground">
                            {formatDistanceToNow(new Date(post.createdAt))}
                          </p>
                        </div>
                      </div>
                      <div className="flex items-center space-x-2">
                        {getPostStatusBadge(post)}
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button variant="ghost" size="sm">
                              <MoreHorizontal className="h-4 w-4" />
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end">
                            <DropdownMenuItem
                              onClick={() => {
                                setSelectedPost(post);
                                setIsBlockDialogOpen(true);
                              }}
                              disabled={post.isBlocked}
                            >
                              <Shield className="h-4 w-4 mr-2" />
                              Block Post
                            </DropdownMenuItem>
                            <DropdownMenuItem
                              onClick={() => handleUnblockPost(post)}
                              disabled={!post.isBlocked}
                            >
                              <ShieldOff className="h-4 w-4 mr-2" />
                              Unblock Post
                            </DropdownMenuItem>
                            <DropdownMenuItem
                              onClick={() => {
                                setSelectedPost(post);
                                setIsDeleteDialogOpen(true);
                              }}
                              className="text-destructive"
                            >
                              <Trash2 className="h-4 w-4 mr-2" />
                              Delete Post
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </div>
                    </div>

                    {/* Audio Player */}
                    <div className="p-4 bg-muted/50 rounded-lg">
                      <div className="flex items-center justify-between mb-2">
                        <span className="text-sm font-medium">
                          {formatDuration(post.duration)}
                        </span>
                        <div className="flex items-center space-x-4 text-sm text-muted-foreground">
                          <div className="flex items-center space-x-1">
                            <Heart className="h-4 w-4" />
                            <span>{post.likes.length}</span>
                          </div>
                          <div
                            className={`flex items-center space-x-1 transition-colors ${
                              post.replies.length === 0
                                ? "cursor-not-allowed opacity-50"
                                : "cursor-pointer hover:text-primary"
                            }`}
                            onClick={
                              post.replies.length === 0
                                ? undefined
                                : () => handleOpenComments(post)
                            }
                          >
                            <MessageCircle className="h-4 w-4" />
                            <span>{post.replies.length}</span>
                          </div>
                          <div className="flex items-center space-x-1">
                            <Eye className="h-4 w-4" />
                            <span>{post.micTaps}</span>
                          </div>
                        </div>
                      </div>
                      <AudioPlayer
                        src={post.audioUrl}
                        onPlay={() => handlePlay()}
                        onPause={handlePause}
                        onEnded={handleEnded}
                        onError={handleError}
                        style={{
                          width: "100%",
                          borderRadius: "8px",
                        }}
                        className="custom-audio-player"
                      />
                    </div>

                    {/* Tags */}
                    {post.tags && post.tags.length > 0 && (
                      <div className="flex flex-wrap gap-2">
                        {post.tags.map((tag, index) => (
                          <Badge
                            key={index}
                            variant="outline"
                            className="text-xs"
                          >
                            #{tag.tag}
                          </Badge>
                        ))}
                      </div>
                    )}

                    {/* Community Info */}
                    {post.community && (
                      <div className="flex items-center space-x-2 text-sm text-muted-foreground">
                        <Users className="h-4 w-4" />
                        <span>Posted in community: {post.community}</span>
                      </div>
                    )}
                  </div>
                </div>
              </CardContent>
            </Card>
          ))
        )}
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <Card>
          <CardContent className="flex items-center justify-between p-4">
            <div className="text-sm text-muted-foreground">
              Page {currentPage} of {totalPages}
            </div>
            <div className="flex items-center space-x-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                disabled={currentPage === 1}
              >
                <ChevronLeft className="h-4 w-4 mr-1" />
                Previous
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() =>
                  setCurrentPage(Math.min(totalPages, currentPage + 1))
                }
                disabled={currentPage === totalPages}
              >
                Next
                <ChevronRight className="h-4 w-4 ml-1" />
              </Button>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Block Post Dialog */}
      <Dialog open={isBlockDialogOpen} onOpenChange={setIsBlockDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Block Post</DialogTitle>
            <DialogDescription>
              Please provide a reason for blocking this post. This action will
              hide the post from all users.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label htmlFor="block-reason">Reason for blocking</Label>
              <Input
                id="block-reason"
                placeholder="Enter reason for blocking..."
                value={blockReason}
                onChange={(e) => setBlockReason(e.target.value)}
              />
            </div>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setIsBlockDialogOpen(false)}
            >
              Cancel
            </Button>
            <Button
              onClick={handleBlockPost}
              disabled={!blockReason.trim()}
              className="gradient-button"
            >
              Block Post
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Post Dialog */}
      <Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Delete Post</DialogTitle>
            <DialogDescription>
              Please provide a reason for deleting this post. This action cannot
              be undone.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div>
              <Label htmlFor="delete-reason">Reason for deletion</Label>
              <Input
                id="delete-reason"
                placeholder="Enter reason for deletion..."
                value={deleteReason}
                onChange={(e) => setDeleteReason(e.target.value)}
              />
            </div>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setIsDeleteDialogOpen(false)}
            >
              Cancel
            </Button>
            <Button
              variant="destructive"
              onClick={handleDeletePost}
              disabled={!deleteReason.trim()}
            >
              Delete Post
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Comments Dialog */}
      <Dialog
        open={isCommentsDialogOpen}
        onOpenChange={setIsCommentsDialogOpen}
      >
        <DialogContent className="max-w-4xl max-h-[80vh] gradient-bg">
          <DialogHeader>
            <DialogTitle>Post Comments</DialogTitle>
            <DialogDescription>
              View and manage comments for this post
            </DialogDescription>
          </DialogHeader>

          <div
            ref={commentsScrollRef}
            className="space-y-4 max-h-[60vh] overflow-y-auto"
          >
            {commentsLoading ? (
              <div className="flex items-center justify-center h-32">
                <div className="text-center">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"></div>
                  <p>Loading comments...</p>
                </div>
              </div>
            ) : commentsError ? (
              <div className="flex items-center justify-center h-32">
                <div className="text-center text-destructive">
                  <p>Failed to load comments</p>
                  <p className="text-sm text-muted-foreground mt-2">
                    {commentsError instanceof Error
                      ? commentsError.message
                      : "An error occurred"}
                  </p>
                </div>
              </div>
            ) : allComments && allComments.length > 0 ? (
              <div className="space-y-4 p-4">
                {allComments.map((comment: Comment) => (
                  <Card key={comment._id} className="p-4">
                    <div className="space-y-3">
                      {/* Comment Header */}
                      <div className="flex items-center space-x-3">
                        <div className="w-8 h-8 bg-primary/10 rounded-full flex items-center justify-center">
                          <div className="w-6 h-6 bg-primary rounded-full flex items-center justify-center text-primary-foreground text-xs font-medium">
                            {comment.user.fullName.charAt(0).toUpperCase()}
                          </div>
                        </div>
                        <div>
                          <p className="font-medium text-sm">
                            {comment.user.fullName}
                          </p>
                          <p className="text-xs text-muted-foreground">
                            {formatDistanceToNow(new Date(comment.createdAt))}
                          </p>
                        </div>
                      </div>

                      {/* Comment Audio Player */}
                      <div className="p-3 bg-muted/50 rounded-lg">
                        <div className="flex items-center justify-between mb-2">
                          <span className="text-sm font-medium">
                            {formatDuration(comment.duration)}
                          </span>
                        </div>
                        <AudioPlayer
                          src={comment.audioUrl}
                          onPlay={() => handlePlay()}
                          onPause={handlePause}
                          onEnded={handleEnded}
                          onError={handleError}
                          style={{
                            width: "100%",
                            borderRadius: "8px",
                          }}
                          className="custom-audio-player"
                        />
                      </div>

                      {/* Nested Replies */}
                      {comment.replies && comment.replies.length > 0 && (
                        <div className="ml-6 space-y-3 border-l-2 border-muted pl-4">
                          {comment.replies.map((reply: Comment) => (
                            <Card key={reply._id} className="p-3 bg-muted/30">
                              <div className="space-y-2">
                                <div className="flex items-center space-x-2">
                                  <div className="w-6 h-6 bg-primary/10 rounded-full flex items-center justify-center">
                                    <div className="w-4 h-4 bg-primary rounded-full flex items-center justify-center text-primary-foreground text-xs font-medium">
                                      {reply.user.fullName
                                        .charAt(0)
                                        .toUpperCase()}
                                    </div>
                                  </div>
                                  <div>
                                    <p className="font-medium text-xs">
                                      {reply.user.fullName}
                                    </p>
                                    <p className="text-xs text-muted-foreground">
                                      {formatDistanceToNow(
                                        new Date(reply.createdAt)
                                      )}
                                    </p>
                                  </div>
                                </div>

                                <div className="p-2 bg-muted/50 rounded">
                                  <div className="flex items-center justify-between mb-1">
                                    <span className="text-xs font-medium">
                                      {formatDuration(reply.duration)}
                                    </span>
                                  </div>
                                  <AudioPlayer
                                    src={reply.audioUrl}
                                    onPlay={() => handlePlay()}
                                    onPause={handlePause}
                                    onEnded={handleEnded}
                                    onError={handleError}
                                    style={{
                                      width: "100%",
                                      borderRadius: "6px",
                                    }}
                                    className="custom-audio-player"
                                  />
                                </div>
                              </div>
                            </Card>
                          ))}
                        </div>
                      )}
                    </div>
                  </Card>
                ))}

                {/* Loading indicator for next page */}
                {isFetchingNextPage && (
                  <div className="flex items-center justify-center py-4">
                    <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary mr-2"></div>
                    <span className="text-sm text-muted-foreground">
                      Loading more comments...
                    </span>
                  </div>
                )}

                {/* Load more button as fallback */}
                {hasNextPage && !isFetchingNextPage && (
                  <div className="flex justify-center py-4">
                    <Button
                      variant="outline"
                      onClick={() => fetchNextPage()}
                      className="w-full gradient-button"
                    >
                      Load More Comments
                    </Button>
                  </div>
                )}
              </div>
            ) : (
              <div className="flex items-center justify-center h-32">
                <div className="text-center">
                  <MessageCircle className="h-8 w-8 text-muted-foreground mx-auto mb-2" />
                  <p className="text-muted-foreground">No comments found</p>
                </div>
              </div>
            )}
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setIsCommentsDialogOpen(false)}
            >
              Close
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
