"use client";

import { useCallback, useEffect, useMemo, useRef, useState } from "react";

import { NoPermissionState } from "@/components/auth/no-permission-state";
import { useSuperAdminSession } from "@/components/auth/session-context";
import { PageHeader } from "@/components/dashboard/page-header";
import { MediaInspector, getMediaHealth } from "@/components/dashboard/media-inspector";
import { PaginationControls } from "@/components/dashboard/pagination-controls";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Drawer } from "@/components/ui/drawer";
import { EmptyState } from "@/components/ui/empty-state";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useToast } from "@/components/ui/toast";
import { listModerationComments } from "@/lib/api/comments";
import { getItems, getPagination } from "@/lib/api/core";
import { listModerationPosts } from "@/lib/api/posts";
import {
  deleteSuperAdminComment,
  deleteSuperAdminPost,
  getSuperAdminReports,
  performSuperAdminBulkAction,
  updateSuperAdminCommentStatus,
  updateSuperAdminPostStatus,
} from "@/lib/api/superadmin";
import { formatDateTime } from "@/lib/format";
import { getCommentAuthor, getPostAuthor, getUserLabel } from "@/lib/post-utils";
import { SUPERADMIN_PERMISSIONS, hasPermission } from "@/lib/permissions";
import type {
  ApiComment,
  ApiPost,
  CommentsResponse,
  ModerationStatus,
  PostsResponse,
  SuperAdminReportsResponse,
} from "@/types/api";

type BulkTarget = "post" | "comment";
type BulkAction = "activate" | "flag" | "hide" | "delete";

const EMPTY_REPORTS: SuperAdminReportsResponse = {
  summary: {
    flaggedPostsCount: 0,
    flaggedCommentsCount: 0,
    disabledUsersCount: 0,
    inactiveListingsCount: 0,
    inactiveRepairShopsCount: 0,
    openCasesCount: 0,
    failedOutboxEventsCount: 0,
    pendingOutboxEventsCount: 0,
  },
  flaggedPosts: [],
  flaggedComments: [],
  disabledUsers: [],
  inactiveListings: [],
  inactiveRepairShops: [],
};

function promptReason(actionLabel: string) {
  if (typeof window === "undefined") {
    return "";
  }

  const result = window.prompt(`Optional reason for ${actionLabel}`, "");
  if (result === null) {
    return null;
  }

  return result.trim();
}

export default function ContentPage() {
  const { permissions } = useSuperAdminSession();
  const [query, setQuery] = useState("");
  const [postType, setPostType] = useState("all");
  const [visibility, setVisibility] = useState("all");
  const [moderationStatus, setModerationStatus] = useState("all");
  const [postsResponse, setPostsResponse] = useState<PostsResponse | null>(null);
  const [commentsResponse, setCommentsResponse] = useState<CommentsResponse | null>(null);
  const [reports, setReports] = useState<SuperAdminReportsResponse>(EMPTY_REPORTS);
  const [loading, setLoading] = useState(true);
  const [postsPage, setPostsPage] = useState(1);
  const [commentsPage, setCommentsPage] = useState(1);
  const [selectedPostIds, setSelectedPostIds] = useState<string[]>([]);
  const [selectedCommentIds, setSelectedCommentIds] = useState<string[]>([]);
  const [bulkTarget, setBulkTarget] = useState<BulkTarget>("post");
  const [bulkAction, setBulkAction] = useState<BulkAction>("flag");
  const [bulkReason, setBulkReason] = useState("");
  const [bulkLoading, setBulkLoading] = useState(false);
  const [selectedPost, setSelectedPost] = useState<ApiPost | null>(null);
  const { toast } = useToast();
  const filtersRef = useRef({ query, postType, visibility, moderationStatus });

  const canModerateContent = hasPermission(
    permissions,
    SUPERADMIN_PERMISSIONS.CONTENT_MODERATE,
  );
  const canReadAnalytics = hasPermission(permissions, SUPERADMIN_PERMISSIONS.ANALYTICS_READ);
  const canUseBulkActions =
    canModerateContent && hasPermission(permissions, SUPERADMIN_PERMISSIONS.CASES_MANAGE);

  filtersRef.current = { query, postType, visibility, moderationStatus };

  const loadContent = useCallback(async () => {
    if (!canModerateContent) {
      setLoading(false);
      return;
    }

    const {
      query: currentQuery,
      postType: currentPostType,
      visibility: currentVisibility,
      moderationStatus: currentModerationStatus,
    } = filtersRef.current;

    setLoading(true);
    try {
      const [posts, comments, nextReports] = await Promise.all([
        listModerationPosts({
          page: postsPage,
          limit: 10,
          q: currentQuery || undefined,
          postType: currentPostType === "all" ? undefined : currentPostType,
          visibility: currentVisibility === "all" ? undefined : currentVisibility,
          moderationStatus:
            currentModerationStatus === "all" ? undefined : currentModerationStatus,
          sortBy: "createdAt",
          sortOrder: "desc",
        }),
        listModerationComments({
          page: commentsPage,
          limit: 10,
          q: currentQuery || undefined,
          moderationStatus:
            currentModerationStatus === "all" ? undefined : currentModerationStatus,
          sortOrder: "desc",
        }),
        canReadAnalytics ? getSuperAdminReports({ limit: 6 }) : Promise.resolve(EMPTY_REPORTS),
      ]);
      setPostsResponse(posts);
      setCommentsResponse(comments);
      setReports(nextReports);
    } catch (error) {
      toast({ title: "Failed to load content", description: String(error), variant: "danger" });
    } finally {
      setLoading(false);
    }
  }, [canModerateContent, canReadAnalytics, commentsPage, postsPage, toast]);

  useEffect(() => {
    void loadContent();
  }, [loadContent]);

  const applyFilters = () => {
    const shouldReloadDirectly = postsPage === 1 && commentsPage === 1;
    setPostsPage(1);
    setCommentsPage(1);
    if (shouldReloadDirectly) {
      void loadContent();
    }
  };

  const posts = getItems(postsResponse) as ApiPost[];
  const comments = getItems(commentsResponse) as ApiComment[];
  const bulkIds = bulkTarget === "post" ? selectedPostIds : selectedCommentIds;
  const mediaSummary = useMemo(() => {
    const mediaPosts = posts.filter((post) => ["image", "video", "audio"].includes(post.postType ?? ""));
    const unhealthy = mediaPosts.filter((post) => getMediaHealth(post).problems.length > 0);
    const hlsReady = posts.filter((post) => post.postType === "video" && post.hlsUrl).length;
    const thumbnailsReady = posts.filter((post) => post.thumbnailUrl || post.thumbnailVariants?.thumbnail).length;
    return { mediaPosts: mediaPosts.length, unhealthy: unhealthy.length, hlsReady, thumbnailsReady };
  }, [posts]);

  const updatePostStatus = async (postId: string, status: ModerationStatus) => {
    const reason = promptReason(`post ${status}`);
    if (reason === null) return;

    try {
      await updateSuperAdminPostStatus(postId, status, reason || undefined);
      await loadContent();
      toast({ title: "Post updated", description: `${postId} -> ${status}`, variant: "success" });
    } catch (error) {
      toast({ title: "Post update failed", description: String(error), variant: "danger" });
    }
  };

  const updateCommentStatus = async (commentId: string, status: ModerationStatus) => {
    const reason = promptReason(`comment ${status}`);
    if (reason === null) return;

    try {
      await updateSuperAdminCommentStatus(commentId, status, reason || undefined);
      await loadContent();
      toast({ title: "Comment updated", description: `${commentId} -> ${status}`, variant: "success" });
    } catch (error) {
      toast({ title: "Comment update failed", description: String(error), variant: "danger" });
    }
  };

  const toggleSelection = (kind: BulkTarget, id: string) => {
    const setter = kind === "post" ? setSelectedPostIds : setSelectedCommentIds;
    setter((prev) => (prev.includes(id) ? prev.filter((item) => item !== id) : [...prev, id]));
  };

  if (!canModerateContent) {
    return (
      <div className="space-y-5 pb-8">
        <PageHeader
          title="Content moderation"
          subtitle="Review posts and comments, update moderation states, and run bulk actions."
        />
        <NoPermissionState description="This page needs the content.moderate permission." />
      </div>
    );
  }

  return (
    <div className="space-y-5 pb-8">
      <PageHeader
        title="Content moderation"
        subtitle="Review posts and comments, update moderation states, and run bulk actions."
        actions={
          <Button variant="outline" onClick={applyFilters}>
            Apply filters
          </Button>
        }
      />

      {canReadAnalytics ? (
        <section className="grid gap-4 md:grid-cols-4 xl:grid-cols-7">
          <Card>
            <CardHeader>
              <CardTitle>Flagged posts</CardTitle>
            </CardHeader>
            <CardContent className="text-3xl font-bold text-foreground">
              {reports.summary.flaggedPostsCount}
            </CardContent>
          </Card>
          <Card>
            <CardHeader>
              <CardTitle>Flagged comments</CardTitle>
            </CardHeader>
            <CardContent className="text-3xl font-bold text-foreground">
              {reports.summary.flaggedCommentsCount}
            </CardContent>
          </Card>
          <Card>
            <CardHeader>
              <CardTitle>Disabled users</CardTitle>
            </CardHeader>
            <CardContent className="text-3xl font-bold text-foreground">
              {reports.summary.disabledUsersCount}
            </CardContent>
          </Card>
          <Card>
            <CardHeader>
              <CardTitle>Inactive listings</CardTitle>
            </CardHeader>
            <CardContent className="text-3xl font-bold text-foreground">
              {reports.summary.inactiveListingsCount}
            </CardContent>
          </Card>
          <Card>
            <CardHeader>
              <CardTitle>Inactive shops</CardTitle>
            </CardHeader>
            <CardContent className="text-3xl font-bold text-foreground">
              {reports.summary.inactiveRepairShopsCount}
            </CardContent>
          </Card>
          <Card>
            <CardHeader>
              <CardTitle>Open cases</CardTitle>
            </CardHeader>
            <CardContent className="text-3xl font-bold text-foreground">
              {reports.summary.openCasesCount}
            </CardContent>
          </Card>
          <Card>
            <CardHeader>
              <CardTitle>Failed outbox</CardTitle>
            </CardHeader>
            <CardContent className="text-3xl font-bold text-foreground">
              {reports.summary.failedOutboxEventsCount}
            </CardContent>
          </Card>
        </section>
      ) : null}

      <Card>
        <CardHeader>
          <CardTitle>Filters</CardTitle>
        </CardHeader>
        <CardContent className="grid gap-3 md:grid-cols-5">
          <Input value={query} onChange={(event) => setQuery(event.target.value)} placeholder="Search text or identity" />
          <Select value={postType} onValueChange={setPostType}>
            <SelectTrigger>
              <SelectValue placeholder="Post type" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All post types</SelectItem>
              <SelectItem value="text">text</SelectItem>
              <SelectItem value="image">image</SelectItem>
              <SelectItem value="video">video</SelectItem>
              <SelectItem value="audio">audio</SelectItem>
            </SelectContent>
          </Select>
          <Select value={visibility} onValueChange={setVisibility}>
            <SelectTrigger>
              <SelectValue placeholder="Visibility" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All visibility</SelectItem>
              <SelectItem value="public">public</SelectItem>
              <SelectItem value="followers">followers</SelectItem>
              <SelectItem value="private">private</SelectItem>
            </SelectContent>
          </Select>
          <Select value={moderationStatus} onValueChange={setModerationStatus}>
            <SelectTrigger>
              <SelectValue placeholder="Moderation state" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">All states</SelectItem>
              <SelectItem value="active">active</SelectItem>
              <SelectItem value="hidden">hidden</SelectItem>
              <SelectItem value="flagged">flagged</SelectItem>
            </SelectContent>
          </Select>
          <Button variant="outline" onClick={applyFilters}>
            Apply
          </Button>
        </CardContent>
      </Card>

      <section className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader>
            <CardTitle>Media posts</CardTitle>
          </CardHeader>
          <CardContent className="text-3xl font-bold text-foreground">{mediaSummary.mediaPosts}</CardContent>
        </Card>
        <Card>
          <CardHeader>
            <CardTitle>Needs media review</CardTitle>
          </CardHeader>
          <CardContent className="text-3xl font-bold text-foreground">{mediaSummary.unhealthy}</CardContent>
        </Card>
        <Card>
          <CardHeader>
            <CardTitle>HLS ready videos</CardTitle>
          </CardHeader>
          <CardContent className="text-3xl font-bold text-foreground">{mediaSummary.hlsReady}</CardContent>
        </Card>
        <Card>
          <CardHeader>
            <CardTitle>Thumbnails ready</CardTitle>
          </CardHeader>
          <CardContent className="text-3xl font-bold text-foreground">{mediaSummary.thumbnailsReady}</CardContent>
        </Card>
      </section>

      {canUseBulkActions ? (
        <Card>
          <CardHeader>
            <CardTitle>Bulk actions</CardTitle>
          </CardHeader>
          <CardContent className="grid gap-3 md:grid-cols-4">
            <Select value={bulkTarget} onValueChange={(value) => setBulkTarget(value as BulkTarget)}>
              <SelectTrigger>
                <SelectValue placeholder="Target type" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="post">posts</SelectItem>
                <SelectItem value="comment">comments</SelectItem>
              </SelectContent>
            </Select>
            <Select value={bulkAction} onValueChange={(value) => setBulkAction(value as BulkAction)}>
              <SelectTrigger>
                <SelectValue placeholder="Action" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="activate">activate</SelectItem>
                <SelectItem value="flag">flag</SelectItem>
                <SelectItem value="hide">hide</SelectItem>
                <SelectItem value="delete">delete</SelectItem>
              </SelectContent>
            </Select>
            <Input value={bulkReason} onChange={(event) => setBulkReason(event.target.value)} placeholder="Reason for audit/case log" />
            <Button
              disabled={bulkLoading || !bulkIds.length}
              onClick={async () => {
                setBulkLoading(true);
                try {
                  await performSuperAdminBulkAction({
                    resourceType: bulkTarget,
                    targetIds: bulkIds,
                    action: bulkAction,
                    reason: bulkReason || undefined,
                    assignToMe: true,
                  });
                  setSelectedPostIds([]);
                  setSelectedCommentIds([]);
                  setBulkReason("");
                  await loadContent();
                  toast({ title: "Bulk action applied", description: `${bulkIds.length} items processed`, variant: "success" });
                } catch (error) {
                  toast({ title: "Bulk action failed", description: String(error), variant: "danger" });
                } finally {
                  setBulkLoading(false);
                }
              }}
            >
              Apply to {bulkIds.length} selected
            </Button>
          </CardContent>
        </Card>
      ) : null}

      <section className="grid gap-4 xl:grid-cols-12">
        <Card className="xl:col-span-7">
          <CardHeader>
            <CardTitle>Posts</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {!posts.length && !loading ? (
              <EmptyState title="No posts" description="No posts matched the current filters." />
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    {canUseBulkActions ? <TableHead /> : null}
                    <TableHead>Content</TableHead>
                    <TableHead>Author</TableHead>
                    <TableHead>Type</TableHead>
                    <TableHead>State</TableHead>
                    <TableHead>Engagement</TableHead>
                    <TableHead>Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {posts.map((post) => (
                    <TableRow key={post._id}>
                      {canUseBulkActions ? (
                        <TableCell>
                          <input
                            type="checkbox"
                            checked={selectedPostIds.includes(post._id)}
                            onChange={() => toggleSelection("post", post._id)}
                          />
                        </TableCell>
                      ) : null}
                      <TableCell className="max-w-[240px] truncate">{post.content || "-"}</TableCell>
                      <TableCell>{getUserLabel(getPostAuthor(post))}</TableCell>
                      <TableCell>
                        <div className="space-y-1">
                          <div>{post.postType ?? "-"}</div>
                          <Badge variant={getMediaHealth(post).problems.length ? "warning" : "muted"}>
                            {getMediaHealth(post).problems.length ? "media check" : "ok"}
                          </Badge>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge
                          variant={
                            post.moderationStatus === "flagged"
                              ? "warning"
                              : post.moderationStatus === "hidden"
                                ? "danger"
                                : "success"
                          }
                        >
                          {post.moderationStatus ?? "active"}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        {post.likesCount ?? 0}/{post.commentsCount ?? 0}/{post.shareCount ?? 0}
                      </TableCell>
                      <TableCell className="flex flex-wrap gap-2">
                        <Button size="sm" variant="outline" onClick={() => setSelectedPost(post)}>
                          Details
                        </Button>
                        <Button size="sm" variant="outline" onClick={() => void updatePostStatus(post._id, "active")}>
                          Activate
                        </Button>
                        <Button size="sm" variant="outline" onClick={() => void updatePostStatus(post._id, "flagged")}>
                          Flag
                        </Button>
                        <Button size="sm" variant="outline" onClick={() => void updatePostStatus(post._id, "hidden")}>
                          Hide
                        </Button>
                        <Button
                          size="sm"
                          variant="danger"
                          onClick={async () => {
                            try {
                              await deleteSuperAdminPost(post._id);
                              await loadContent();
                              toast({ title: "Post deleted", description: post._id, variant: "warning" });
                            } catch (error) {
                              toast({ title: "Delete failed", description: String(error), variant: "danger" });
                            }
                          }}
                        >
                          Delete
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            )}
            <PaginationControls pagination={getPagination(postsResponse)} loading={loading} onPageChange={setPostsPage} />
          </CardContent>
        </Card>

        <Card className="xl:col-span-5">
          <CardHeader>
            <CardTitle>Comments</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {!comments.length && !loading ? (
              <EmptyState title="No comments" description="No comments matched the current filters." />
            ) : (
              <div className="space-y-3">
                {comments.map((comment) => (
                  <div key={comment._id} className="rounded-xl border border-border/70 bg-secondary/20 p-4">
                    <div className="flex items-start justify-between gap-3">
                      <div>
                        <p className="text-sm font-medium text-foreground">
                            {getUserLabel(getCommentAuthor(comment))}
                        </p>
                        <p className="mt-1 text-xs text-muted-foreground">{formatDateTime(comment.createdAt)}</p>
                      </div>
                      <div className="flex items-center gap-2">
                        <Badge
                          variant={
                            comment.moderationStatus === "flagged"
                              ? "warning"
                              : comment.moderationStatus === "hidden"
                                ? "danger"
                                : "muted"
                          }
                        >
                          {comment.moderationStatus ?? "comment"}
                        </Badge>
                        {canUseBulkActions ? (
                          <input
                            type="checkbox"
                            checked={selectedCommentIds.includes(comment._id)}
                            onChange={() => toggleSelection("comment", comment._id)}
                          />
                        ) : null}
                      </div>
                    </div>
                    <p className="mt-3 text-sm text-foreground">{comment.content}</p>
                    <div className="mt-3 flex flex-wrap justify-end gap-2">
                      <Button size="sm" variant="outline" onClick={() => void updateCommentStatus(comment._id, "active")}>
                        Activate
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => void updateCommentStatus(comment._id, "flagged")}>
                        Flag
                      </Button>
                      <Button size="sm" variant="outline" onClick={() => void updateCommentStatus(comment._id, "hidden")}>
                        Hide
                      </Button>
                      <Button
                        size="sm"
                        variant="danger"
                        onClick={async () => {
                          try {
                            await deleteSuperAdminComment(comment._id);
                            await loadContent();
                            toast({ title: "Comment deleted", description: comment._id, variant: "warning" });
                          } catch (error) {
                            toast({ title: "Delete failed", description: String(error), variant: "danger" });
                          }
                        }}
                      >
                        Delete
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            )}
            <PaginationControls pagination={getPagination(commentsResponse)} loading={loading} onPageChange={setCommentsPage} />
          </CardContent>
        </Card>
      </section>

      <Drawer
        open={Boolean(selectedPost)}
        onClose={() => setSelectedPost(null)}
        title="Post media details"
        description="Preview the actual media, inspect generated URLs, and review moderation state."
        side="right"
        widthClassName="w-full sm:w-[92vw] sm:max-w-3xl"
      >
        {selectedPost ? (
          <div className="space-y-4">
            <MediaInspector post={selectedPost} />
            <Card className="border-border/70 bg-secondary/20">
              <CardHeader>
                <CardTitle>Post metadata</CardTitle>
              </CardHeader>
              <CardContent className="grid gap-3 text-sm md:grid-cols-2">
                <div>Author: {getUserLabel(getPostAuthor(selectedPost))}</div>
                <div>Type: {selectedPost.postType ?? "-"}</div>
                <div>Status: {selectedPost.moderationStatus ?? "active"}</div>
                <div>Processing: {selectedPost.processingStatus ?? "-"}</div>
                <div>Visibility: {selectedPost.visibility ?? "-"}</div>
                <div>Created: {formatDateTime(selectedPost.createdAt)}</div>
                <div>Likes: {selectedPost.likesCount ?? 0}</div>
                <div>Comments: {selectedPost.commentsCount ?? 0}</div>
              </CardContent>
            </Card>
          </div>
        ) : null}
      </Drawer>
    </div>
  );
}
