"use client";

import { useState } from "react";
import AudioPlayer from "react-h5-audio-player";
import "react-h5-audio-player/lib/styles.css";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Shield, Filter, ChevronLeft, ChevronRight } from "lucide-react";
import { useFlaggedContent, useModerateContent } from "@/hooks";
import { ReportStatus, ReportAction } from "@/types/api";
import { toast } from "sonner";

export default function ModerationPage() {
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [statusFilter, setStatusFilter] = useState("");
  const [typeFilter, setTypeFilter] = useState("");
  const [sortBy, setSortBy] = useState("createdAt");
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");

  // Audio player event handlers
  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 formatDuration = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs.toString().padStart(2, "0")}`;
  };

  // Fetch flagged content with filters
  const { data: flaggedContent, isLoading: flaggedLoading } = useFlaggedContent(
    {
      page: currentPage,
      limit: pageSize,
      status: statusFilter && statusFilter !== "all" ? statusFilter : undefined,
      type: typeFilter && typeFilter !== "all" ? typeFilter : undefined,
      sortBy,
      sortOrder,
    }
  );

  // Moderation mutations
  const moderateContentMutation = useModerateContent();

  // Moderation action handlers
  const handleModerateContent = async (
    contentId: string,
    reportAction: string,
    contentAction?: "delete" | "block" | "keep"
  ) => {
    try {
      await moderateContentMutation.mutateAsync({
        reportId: contentId,
        moderationData: {
          action: reportAction as ReportAction,
          reason: `Content ${reportAction}ed by admin`,
          contentAction: contentAction, // New field for content actions
        },
      });
    } catch (error) {
      console.error(`Failed to ${reportAction} content:`, error);
    }
  };

  const handleFilterChange = (filterType: string, value: string) => {
    switch (filterType) {
      case "status":
        setStatusFilter(value);
        break;
      case "type":
        setTypeFilter(value);
        break;
      case "sortBy":
        setSortBy(value);
        break;
      case "sortOrder":
        setSortOrder(value as "asc" | "desc");
        break;
    }
    setCurrentPage(1);
  };

  const totalPages = Math.ceil((flaggedContent?.data?.total || 0) / pageSize);

  return (
    <div className="flex-1 space-y-6 p-4 sm:p-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold tracking-tight">
            Content Moderation
          </h1>
          <p className="text-muted-foreground text-sm sm:text-base">
            Review and moderate flagged content
          </p>
        </div>
      </div>

      {/* Filters */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Filter className="h-5 w-5 mr-2" />
            Filters
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            {/* Status Filter */}
            <div className="space-y-2">
              <Label htmlFor="status">Status</Label>
              <Select
                value={statusFilter}
                onValueChange={(value) => handleFilterChange("status", value)}
              >
                <SelectTrigger>
                  <SelectValue placeholder="All statuses" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All statuses</SelectItem>
                  <SelectItem value={ReportStatus.unresolved}>
                    Unresolved
                  </SelectItem>
                  <SelectItem value={ReportStatus.resolved}>
                    Resolved
                  </SelectItem>
                  <SelectItem value={ReportStatus.dismissed}>
                    Dismissed
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* Type Filter */}
            <div className="space-y-2">
              <Label htmlFor="type">Content Type</Label>
              <Select
                value={typeFilter}
                onValueChange={(value) => handleFilterChange("type", value)}
              >
                <SelectTrigger>
                  <SelectValue placeholder="All types" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All types</SelectItem>
                  <SelectItem value="post">Post</SelectItem>
                  <SelectItem value="comment">Comment</SelectItem>
                  <SelectItem value="community">Community</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* Sort By */}
            {/* <div className="space-y-2">
              <Label htmlFor="sortBy">Sort By</Label>
              <Select
                value={sortBy}
                onValueChange={(value) => handleFilterChange("sortBy", value)}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="createdAt">Reported Date</SelectItem>
                  <SelectItem value="status">Status</SelectItem>
                  <SelectItem value="type">Type</SelectItem>
                </SelectContent>
              </Select>
            </div> */}

            {/* Sort Order */}
            <div className="space-y-2">
              <Label htmlFor="sortOrder">Order</Label>
              <Select
                value={sortOrder}
                onValueChange={(value) =>
                  handleFilterChange("sortOrder", value)
                }
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="desc">Descending</SelectItem>
                  <SelectItem value="asc">Ascending</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Flagged Content List */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Shield className="h-5 w-5 mr-2" />
            Flagged Content ({flaggedContent?.data?.total || 0})
          </CardTitle>
          <CardDescription>
            Showing {flaggedContent?.data?.flaggedContent?.length || 0} of{" "}
            {flaggedContent?.data?.total || 0} flagged content items
          </CardDescription>
        </CardHeader>
        <CardContent>
          {flaggedLoading ? (
            <div className="space-y-3">
              {[...Array(5)].map((_, i) => (
                <div key={i} className="p-4 border rounded-lg animate-pulse">
                  <div className="space-y-2">
                    <div className="h-4 bg-gray-200 rounded w-1/2"></div>
                    <div className="h-3 bg-gray-200 rounded w-3/4"></div>
                    <div className="flex space-x-2">
                      <div className="h-6 w-20 bg-gray-200 rounded"></div>
                      <div className="h-6 w-16 bg-gray-200 rounded"></div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="space-y-3">
              {(flaggedContent?.data?.flaggedContent || []).length > 0 ? (
                flaggedContent?.data?.flaggedContent?.map((flaggedItem) => (
                  <div
                    key={flaggedItem._id.contentId}
                    className="p-4 border rounded-lg"
                  >
                    <div className="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-4">
                      <div className="space-y-2 flex-1">
                        <div className="flex flex-wrap items-center gap-2">
                          <Badge variant="outline" className="capitalize">
                            {flaggedItem.contentType}
                          </Badge>
                          <Badge
                            className={`capitalize ${
                              flaggedItem.status === "resolved"
                                ? "gradient-badge"
                                : ""
                            }`}
                            variant={
                              flaggedItem.status === "unresolved"
                                ? "destructive"
                                : flaggedItem.status === "resolved"
                                ? "default"
                                : "secondary"
                            }
                          >
                            {flaggedItem.status}
                          </Badge>
                          <Badge variant="secondary" className="capitalize">
                            {flaggedItem.reportCount} report
                            {flaggedItem.reportCount !== 1 ? "s" : ""}
                          </Badge>
                        </div>
                        <p className="text-sm font-medium">
                          Content ID: {flaggedItem.contentId}
                        </p>
                        <p className="text-sm text-muted-foreground">
                          Latest Report:{" "}
                          {new Date(
                            flaggedItem.latestReportDate
                          ).toLocaleDateString()}
                        </p>

                        {/* Display the actual reported content */}
                        {flaggedItem.content && (
                          <div className="space-y-2 p-3 gradient-bg rounded-lg border">
                            <p className="text-sm font-medium text-primary">
                              Reported Content:
                            </p>

                            {/* User Content */}
                            {flaggedItem.contentType === "user" && (
                              <div className="space-y-3">
                                <div className="flex items-center space-x-3">
                                  {flaggedItem.content.profilePictureData && (
                                    <img
                                      src={
                                        flaggedItem.content.profilePictureData
                                          .url
                                      }
                                      alt={flaggedItem.content.fullName}
                                      className="w-12 h-12 rounded-full object-cover"
                                    />
                                  )}
                                  <div className="flex-1">
                                    <div className="flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-2">
                                      <span className="text-sm font-medium">
                                        Name: {flaggedItem.content.fullName}
                                      </span>
                                    </div>
                                    <div className="text-xs text-muted-foreground space-y-1">
                                      <p>User ID: {flaggedItem.content._id}</p>
                                      {flaggedItem.content.authData?.email && (
                                        <p>
                                          Email:{" "}
                                          {flaggedItem.content.authData.email}
                                        </p>
                                      )}
                                      {flaggedItem.content.authData?.role && (
                                        <p>
                                          Role:{" "}
                                          {flaggedItem.content.authData.role}
                                        </p>
                                      )}
                                      {flaggedItem.content.dateOfBirth && (
                                        <p>
                                          Date of Birth:{" "}
                                          {flaggedItem.content.dateOfBirth}
                                        </p>
                                      )}
                                      {flaggedItem.content.gender && (
                                        <p>
                                          Gender: {flaggedItem.content.gender}
                                        </p>
                                      )}
                                      {flaggedItem.content
                                        .profileVisibility && (
                                        <p>
                                          Profile Visibility:{" "}
                                          {
                                            flaggedItem.content
                                              .profileVisibility
                                          }
                                        </p>
                                      )}
                                    </div>
                                  </div>
                                </div>
                              </div>
                            )}

                            {/* Post Content */}
                            {flaggedItem.contentType === "post" &&
                              "audioUrl" in flaggedItem.content && (
                                <div className="space-y-2">
                                  <div className="flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-2">
                                    <span className="text-sm font-medium">
                                      Author:{" "}
                                      {flaggedItem.content?.fullName ||
                                        "Unknown"}
                                    </span>
                                  </div>

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

                                  {/* Tags */}
                                  {/* {flaggedItem.content.tags &&
                                  flaggedItem.content.tags.length > 0 && (
                                    <div className="flex flex-wrap gap-1">
                                      <span className="text-xs text-muted-foreground">
                                        Tags:
                                      </span>
                                      {flaggedItem.content.tags.map(
                                        (tag:Tag, index) => (
                                          <Badge
                                            key={index}
                                            variant="outline"
                                            className="text-xs"
                                          >
                                            {tag.tag}
                                          </Badge>
                                        )
                                      )}
                                    </div>
                                  )} */}
                                </div>
                              )}

                            {/* Comment Content */}
                            {flaggedItem.contentType === "comment" &&
                              "text" in flaggedItem.content && (
                                <div className="space-y-2">
                                  <div className="flex flex-col sm:flex-row sm:items-center gap-1 sm:gap-2">
                                    <span className="text-sm font-medium">
                                      Author:{" "}
                                      {(
                                        flaggedItem.content as {
                                          user?: { fullName: string };
                                        }
                                      )?.user?.fullName || "Unknown"}
                                    </span>
                                  </div>
                                  <div className="p-2 bg-white rounded border">
                                    <p className="text-sm">
                                      {(
                                        flaggedItem.content as { text?: string }
                                      )?.text || "No text content"}
                                    </p>
                                  </div>
                                  <p className="text-xs text-muted-foreground">
                                    Comment ID: {flaggedItem.content._id}
                                  </p>
                                </div>
                              )}
                          </div>
                        )}

                        {/* Display individual reports */}
                        {flaggedItem.reports &&
                          flaggedItem.reports.length > 0 && (
                            <div className="space-y-2">
                              <p className="text-sm font-medium">Reports:</p>
                              {flaggedItem.reports.map((report) => (
                                <div
                                  key={report._id}
                                  className="p-3 rounded-lg bg-primary"
                                >
                                  <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
                                    <div className="flex items-center space-x-2">
                                      {report.reporter.profilePictureData && (
                                        <img
                                          src={
                                            report.reporter.profilePictureData
                                              .url
                                          }
                                          alt={report.reporter.fullName}
                                          className="w-6 h-6 rounded-full object-cover"
                                        />
                                      )}
                                      <div>
                                        <p className="text-sm font-medium">
                                          Reporter: {report.reporter.fullName}
                                        </p>
                                        <p className="text-xs">
                                          Reason: {report.reason}
                                        </p>
                                        <p className="text-xs">
                                          Reported:{" "}
                                          {new Date(
                                            report.createdAt
                                          ).toLocaleDateString()}
                                        </p>
                                      </div>
                                    </div>
                                    <Badge
                                      variant={
                                        report.status === "unresolved"
                                          ? "destructive"
                                          : report.status === "resolved"
                                          ? "default"
                                          : "secondary"
                                      }
                                      className={`self-start sm:self-auto capitalize ${
                                        report.status === "resolved"
                                          ? "gradient-badge"
                                          : ""
                                      }`}
                                    >
                                      {report.status}
                                    </Badge>
                                  </div>
                                </div>
                              ))}
                            </div>
                          )}
                      </div>
                      <div className="space-y-2">
                        {/* Report Actions */}
                        <div className="flex flex-col sm:flex-row gap-2">
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() =>
                              handleModerateContent(
                                flaggedItem.contentId,
                                "resolved",
                                "keep"
                              )
                            }
                            disabled={moderateContentMutation.isPending}
                            title="Mark as Resolved - Keep Content"
                            className="w-full sm:w-auto gradient-button"
                          >
                            Resolve & Keep
                          </Button>
                          <Button
                            variant="outline"
                            size="sm"
                            onClick={() =>
                              handleModerateContent(
                                flaggedItem.contentId,
                                "dismissed",
                                "keep"
                              )
                            }
                            disabled={moderateContentMutation.isPending}
                            title="Dismiss Reports - Keep Content"
                            className="w-full sm:w-auto gradient-button"
                          >
                            Dismiss & Keep
                          </Button>
                        </div>

                        {/* Content Actions */}
                        <div className="flex flex-col sm:flex-row gap-2">
                          <Button
                            variant="destructive"
                            size="sm"
                            onClick={() =>
                              handleModerateContent(
                                flaggedItem.contentId,
                                "resolved",
                                "delete"
                              )
                            }
                            disabled={moderateContentMutation.isPending}
                            title="Resolve Reports - Delete Content"
                            className="w-full sm:w-auto"
                          >
                            Resolve & Delete
                          </Button>
                          <Button
                            variant="destructive"
                            size="sm"
                            onClick={() =>
                              handleModerateContent(
                                flaggedItem.contentId,
                                "resolved",
                                "block"
                              )
                            }
                            disabled={moderateContentMutation.isPending}
                            title="Resolve Reports - Block Content"
                            className="w-full sm:w-auto"
                          >
                            Resolve & Block
                          </Button>
                        </div>
                      </div>
                    </div>
                  </div>
                ))
              ) : (
                <div className="text-center py-12">
                  <div className="text-muted-foreground">
                    <Shield className="h-16 w-16 mx-auto mb-6 opacity-50" />
                    <p className="text-xl font-medium mb-2">
                      No flagged content yet
                    </p>
                    <p className="text-sm">
                      All content is clean and properly moderated
                    </p>
                  </div>
                </div>
              )}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Pagination */}
      {totalPages > 1 && (
        <Card>
          <CardContent className="pt-6">
            <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
              <div className="flex items-center space-x-2">
                <Label htmlFor="pageSize" className="text-sm">
                  Items per page:
                </Label>
                <Select
                  value={pageSize.toString()}
                  onValueChange={(value) => {
                    setPageSize(parseInt(value));
                    setCurrentPage(1);
                  }}
                >
                  <SelectTrigger className="w-20">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="5">5</SelectItem>
                    <SelectItem value="10">10</SelectItem>
                    <SelectItem value="20">20</SelectItem>
                    <SelectItem value="50">50</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="flex items-center justify-center sm:justify-end space-x-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setCurrentPage(currentPage - 1)}
                  disabled={currentPage === 1}
                  className="gradient-button"
                >
                  <ChevronLeft className="h-4 w-4" />
                  <span className="hidden sm:inline">Previous</span>
                </Button>
                <span className="text-sm text-muted-foreground px-2">
                  Page {currentPage} of {totalPages}
                </span>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setCurrentPage(currentPage + 1)}
                  disabled={currentPage === totalPages}
                  className="gradient-button"
                >
                  <span className="hidden sm:inline">Next</span>
                  <ChevronRight className="h-4 w-4" />
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}
