"use client";

import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { PageHeader } from "@/components/shared/page-header";
import { DataTable, Column } from "@/components/shared/data-table";
import { ConfirmDialog } from "@/components/shared/confirm-dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Avatar } from "@/components/ui/avatar";
import { NativeSelect } from "@/components/ui/native-select";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
  DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { postsApi, Post, locationsApi, Location } from "@/lib/api-client";
import { formatDate, truncate } from "@/lib/utils";
import {
  MoreHorizontal,
  Pin,
  PinOff,
  Trash2,
  Eye,
  Filter,
  Heart,
  MessageCircle,
  Image,
  Video,
  BarChart3,
  Megaphone,
} from "lucide-react";

const typeIcons: Record<string, React.ReactNode> = {
  text: null,
  image: <Image className="h-4 w-4" />,
  video: <Video className="h-4 w-4" />,
  poll: <BarChart3 className="h-4 w-4" />,
  announcement: <Megaphone className="h-4 w-4" />,
};

export default function PostsPage() {
  const queryClient = useQueryClient();
  const [page, setPage] = useState(1);
  const [typeFilter, setTypeFilter] = useState<string>("all");
  const [viewDialog, setViewDialog] = useState<{ open: boolean; post: Post | null }>({
    open: false,
    post: null,
  });
  const [deleteDialog, setDeleteDialog] = useState<{ open: boolean; post: Post | null }>({
    open: false,
    post: null,
  });

  const { data, isLoading } = useQuery({
    queryKey: ["posts", page, typeFilter],
    queryFn: async () => {
      const params: Record<string, unknown> = { page, limit: 10 };
      if (typeFilter !== "all") {
        params.type = typeFilter;
      }
      const response = await postsApi.getFeed(params);
      return response.data;
    },
  });

  const pinMutation = useMutation({
    mutationFn: (id: string) => postsApi.togglePin(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["posts"] });
    },
  });

  const deleteMutation = useMutation({
    mutationFn: (id: string) => postsApi.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["posts"] });
      setDeleteDialog({ open: false, post: null });
    },
  });

  const columns: Column<Post>[] = [
    {
      key: "author",
      header: "Author",
      cell: (post) => (
        <div className="flex items-center gap-3">
          <Avatar
            src={post.author?.avatarUrl}
            fallback={post.author ? `${post.author.firstName} ${post.author.lastName}` : "?"}
            size="sm"
          />
          <span className="font-medium">
            {post.author?.firstName} {post.author?.lastName}
          </span>
        </div>
      ),
    },
    {
      key: "content",
      header: "Content",
      cell: (post) => (
        <div className="max-w-md">
          <div className="flex items-center gap-2 mb-1">
            {typeIcons[post.type] && (
              <Badge variant="outline" className="gap-1">
                {typeIcons[post.type]}
                {post.type}
              </Badge>
            )}
            {post.isPinned && (
              <Badge variant="default" className="gap-1">
                <Pin className="h-3 w-3" />
                Pinned
              </Badge>
            )}
          </div>
          <p className="text-sm text-muted-foreground line-clamp-2">
            {truncate(post.content, 100)}
          </p>
        </div>
      ),
    },
    {
      key: "engagement",
      header: "Engagement",
      cell: (post) => (
        <div className="flex items-center gap-4 text-sm text-muted-foreground">
          <span className="flex items-center gap-1">
            <Heart className="h-4 w-4" />
            {post.likeCount}
          </span>
          <span className="flex items-center gap-1">
            <MessageCircle className="h-4 w-4" />
            {post.commentCount}
          </span>
        </div>
      ),
    },
    {
      key: "createdAt",
      header: "Posted",
      cell: (post) => (
        <span className="text-muted-foreground">{formatDate(post.createdAt)}</span>
      ),
    },
    {
      key: "actions",
      header: "",
      className: "w-12",
      cell: (post) => (
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button variant="ghost" size="icon">
              <MoreHorizontal className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem onClick={() => setViewDialog({ open: true, post })}>
              <Eye className="mr-2 h-4 w-4" />
              View Details
            </DropdownMenuItem>
            <DropdownMenuItem onClick={() => pinMutation.mutate(post.id)}>
              {post.isPinned ? (
                <>
                  <PinOff className="mr-2 h-4 w-4" />
                  Unpin Post
                </>
              ) : (
                <>
                  <Pin className="mr-2 h-4 w-4" />
                  Pin Post
                </>
              )}
            </DropdownMenuItem>
            <DropdownMenuSeparator />
            <DropdownMenuItem
              destructive
              onClick={() => setDeleteDialog({ open: true, post })}
            >
              <Trash2 className="mr-2 h-4 w-4" />
              Delete Post
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      ),
    },
  ];

  return (
    <div className="space-y-6">
      <PageHeader
        title="Posts"
        description="Moderate and manage content on your platform"
      />

      {/* Filters */}
      <div className="flex items-center gap-4">
        <div className="flex items-center gap-2">
          <Filter className="h-4 w-4 text-muted-foreground" />
          <NativeSelect
            value={typeFilter}
            onChange={(e) => setTypeFilter(e.target.value)}
            options={[
              { value: "all", label: "All Types" },
              { value: "text", label: "Text" },
              { value: "image", label: "Image" },
              { value: "video", label: "Video" },
              { value: "poll", label: "Poll" },
              { value: "announcement", label: "Announcement" },
            ]}
            className="w-40"
          />
        </div>
      </div>

      <DataTable
        data={data?.data || []}
        columns={columns}
        isLoading={isLoading}
        pagination={
          data
            ? {
                page,
                totalPages: data.totalPages,
                onPageChange: setPage,
              }
            : undefined
        }
        emptyMessage="No posts found"
      />

      {/* View Dialog */}
      <Dialog open={viewDialog.open} onOpenChange={(open) => setViewDialog({ open, post: null })}>
        <DialogContent onClose={() => setViewDialog({ open: false, post: null })}>
          <DialogHeader>
            <DialogTitle>Post Details</DialogTitle>
          </DialogHeader>
          {viewDialog.post && (
            <div className="space-y-4">
              <div className="flex items-center gap-3">
                <Avatar
                  src={viewDialog.post.author?.avatarUrl}
                  fallback={
                    viewDialog.post.author
                      ? `${viewDialog.post.author.firstName} ${viewDialog.post.author.lastName}`
                      : "?"
                  }
                />
                <div>
                  <p className="font-medium">
                    {viewDialog.post.author?.firstName} {viewDialog.post.author?.lastName}
                  </p>
                  <p className="text-sm text-muted-foreground">
                    {formatDate(viewDialog.post.createdAt)}
                  </p>
                </div>
              </div>

              <div className="flex gap-2">
                <Badge variant="outline">{viewDialog.post.type}</Badge>
                {viewDialog.post.isPinned && (
                  <Badge>
                    <Pin className="mr-1 h-3 w-3" />
                    Pinned
                  </Badge>
                )}
              </div>

              <p className="text-sm whitespace-pre-wrap">{viewDialog.post.content}</p>

              {viewDialog.post.media && viewDialog.post.media.length > 0 && (
                <div className="grid grid-cols-2 gap-2">
                  {viewDialog.post.media.map((item, index) => (
                    <div key={index} className="rounded-lg overflow-hidden bg-muted">
                      {item.type.startsWith("image") ? (
                        <img
                          src={item.url}
                          alt=""
                          className="w-full h-32 object-cover"
                        />
                      ) : (
                        <video src={item.url} className="w-full h-32 object-cover" controls />
                      )}
                    </div>
                  ))}
                </div>
              )}

              <div className="flex items-center gap-6 pt-4 border-t">
                <span className="flex items-center gap-2 text-muted-foreground">
                  <Heart className="h-5 w-5" />
                  {viewDialog.post.likeCount} likes
                </span>
                <span className="flex items-center gap-2 text-muted-foreground">
                  <MessageCircle className="h-5 w-5" />
                  {viewDialog.post.commentCount} comments
                </span>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>

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