"use client";

import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { PageHeader } from "@/components/shared/page-header";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Avatar } from "@/components/ui/avatar";
import { Input } from "@/components/ui/input";
import { LoadingPage, LoadingSpinner } from "@/components/ui/loading";
import { ConfirmDialog } from "@/components/shared/confirm-dialog";
import { postsApi, commentsApi, Post, Comment } from "@/lib/api-client";
import { formatDate, truncate } from "@/lib/utils";
import {
  Search,
  Trash2,
  Heart,
  MessageCircle,
  ChevronRight,
} from "lucide-react";

export default function CommentsPage() {
  const queryClient = useQueryClient();
  const [selectedPost, setSelectedPost] = useState<Post | null>(null);
  const [searchQuery, setSearchQuery] = useState("");
  const [deleteDialog, setDeleteDialog] = useState<{ open: boolean; comment: Comment | null }>({
    open: false,
    comment: null,
  });

  // Fetch posts
  const { data: postsData, isLoading: postsLoading } = useQuery({
    queryKey: ["posts-for-comments", searchQuery],
    queryFn: async () => {
      const response = await postsApi.getFeed({ limit: 20 });
      let posts = response.data.data;
      if (searchQuery) {
        posts = posts.filter(
          (p: Post) =>
            p.content.toLowerCase().includes(searchQuery.toLowerCase()) ||
            `${p.author?.firstName} ${p.author?.lastName}`
              .toLowerCase()
              .includes(searchQuery.toLowerCase())
        );
      }
      return posts;
    },
  });

  // Fetch comments for selected post
  const { data: comments, isLoading: commentsLoading } = useQuery({
    queryKey: ["comments", selectedPost?.id],
    queryFn: async () => {
      if (!selectedPost) return [];
      const response = await commentsApi.getByPost(selectedPost.id, { limit: 50 });
      return response.data.data;
    },
    enabled: !!selectedPost,
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) => commentsApi.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["comments", selectedPost?.id] });
      queryClient.invalidateQueries({ queryKey: ["posts-for-comments"] });
      setDeleteDialog({ open: false, comment: null });
    },
  });

  if (postsLoading) {
    return <LoadingPage />;
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title="Comments"
        description="Moderate comments on posts"
      />

      <div className="grid gap-6 lg:grid-cols-3">
        {/* Posts List */}
        <Card className="lg:col-span-1">
          <CardHeader>
            <CardTitle className="text-lg">Select a Post</CardTitle>
            <div className="relative mt-2">
              <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
              <Input
                placeholder="Search posts..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-9"
              />
            </div>
          </CardHeader>
          <CardContent className="max-h-[600px] overflow-y-auto">
            <div className="space-y-2">
              {postsData?.map((post: Post) => (
                <button
                  key={post.id}
                  onClick={() => setSelectedPost(post)}
                  className={`w-full text-left rounded-lg border p-3 transition-colors hover:bg-muted ${
                    selectedPost?.id === post.id ? "bg-muted border-primary" : ""
                  }`}
                >
                  <div className="flex items-start justify-between gap-2">
                    <div className="flex items-center gap-2 min-w-0">
                      <Avatar
                        src={post.author?.avatarUrl}
                        fallback={
                          post.author
                            ? `${post.author.firstName} ${post.author.lastName}`
                            : "?"
                        }
                        size="sm"
                      />
                      <div className="min-w-0">
                        <p className="font-medium text-sm truncate">
                          {post.author?.firstName} {post.author?.lastName}
                        </p>
                        <p className="text-xs text-muted-foreground truncate">
                          {truncate(post.content, 50)}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center gap-1 text-xs text-muted-foreground shrink-0">
                      <MessageCircle className="h-3 w-3" />
                      {post.commentCount}
                      <ChevronRight className="h-4 w-4" />
                    </div>
                  </div>
                </button>
              ))}
              {postsData?.length === 0 && (
                <p className="text-center text-muted-foreground py-8">
                  No posts found
                </p>
              )}
            </div>
          </CardContent>
        </Card>

        {/* Comments Panel */}
        <Card className="lg:col-span-2">
          <CardHeader>
            <CardTitle className="text-lg">
              {selectedPost ? (
                <div className="flex items-center gap-2">
                  <MessageCircle className="h-5 w-5" />
                  Comments ({comments?.length || 0})
                </div>
              ) : (
                "Select a post to view comments"
              )}
            </CardTitle>
          </CardHeader>
          <CardContent>
            {!selectedPost ? (
              <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
                <MessageCircle className="h-12 w-12 mb-4 opacity-50" />
                <p>Select a post from the left panel to view its comments</p>
              </div>
            ) : commentsLoading ? (
              <div className="flex items-center justify-center py-12">
                <LoadingSpinner />
              </div>
            ) : comments?.length === 0 ? (
              <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
                <MessageCircle className="h-12 w-12 mb-4 opacity-50" />
                <p>No comments on this post</p>
              </div>
            ) : (
              <div className="space-y-4 max-h-[500px] overflow-y-auto">
                {comments?.map((comment: Comment) => (
                  <div
                    key={comment.id}
                    className={`rounded-lg border p-4 ${
                      comment.parentId ? "ml-8 border-dashed" : ""
                    }`}
                  >
                    <div className="flex items-start justify-between gap-4">
                      <div className="flex items-start gap-3 min-w-0">
                        <Avatar
                          src={comment.author?.avatarUrl}
                          fallback={
                            comment.author
                              ? `${comment.author.firstName} ${comment.author.lastName}`
                              : "?"
                          }
                          size="sm"
                        />
                        <div className="min-w-0">
                          <div className="flex items-center gap-2">
                            <span className="font-medium text-sm">
                              {comment.author?.firstName} {comment.author?.lastName}
                            </span>
                            <span className="text-xs text-muted-foreground">
                              {formatDate(comment.createdAt)}
                            </span>
                          </div>
                          <p className="text-sm mt-1">{comment.content}</p>
                          <div className="flex items-center gap-2 mt-2 text-xs text-muted-foreground">
                            <Heart className="h-3 w-3" />
                            {comment.likeCount} likes
                          </div>
                        </div>
                      </div>
                      <Button
                        variant="ghost"
                        size="icon"
                        className="text-destructive hover:text-destructive hover:bg-destructive/10"
                        onClick={() => setDeleteDialog({ open: true, comment })}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Delete Dialog */}
      <ConfirmDialog
        open={deleteDialog.open}
        onOpenChange={(open) => setDeleteDialog({ open, comment: null })}
        title="Delete Comment"
        description="Are you sure you want to delete this comment? This action cannot be undone."
        confirmText="Delete"
        variant="destructive"
        isLoading={deleteMutation.isPending}
        onConfirm={() => deleteDialog.comment && deleteMutation.mutate(deleteDialog.comment.id)}
      />
    </div>
  );
}
