"use client";

import { useEffect, useState } from "react";
import Link from "next/link";

import { BACKEND } from "../config";

type ToxicComment = {
  platform: string;
  platform_post_id: string;
  comment_id: string;
  username: string | null;
  text: string | null;
  timestamp: string | null;
  like_count: number | null;
  toxicity_level: number | null;
  created_at: string | null;
};

type ToxicCommentsResponse = {
  ok: boolean;
  count: number;
  items: ToxicComment[];
};

export default function ToxicityPage() {
  const [comments, setComments] = useState<ToxicComment[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [processing, setProcessing] = useState<Set<string>>(new Set());

  useEffect(() => {
    loadToxicComments();
  }, []);

  async function loadToxicComments() {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch(`${BACKEND}/toxicity/review`, { credentials: "include" });
      const data: ToxicCommentsResponse = await res.json();
      if (data.ok) {
        setComments(data.items);
      } else {
        setError("Failed to load toxic comments");
      }
    } catch (err) {
      setError("Failed to load data. Check backend connection.");
    } finally {
      setLoading(false);
    }
  }

  async function updateToxicity(
    platform: string,
    platform_post_id: string,
    comment_id: string,
    is_toxic: boolean
  ) {
    const key = `${platform}_${platform_post_id}_${comment_id}`;
    setProcessing((prev) => new Set(prev).add(key));

    try {
      const res = await fetch(`${BACKEND}/toxicity/review`, {
        method: "POST",
        credentials: "include",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          platform,
          platform_post_id,
          comment_id,
          is_toxic,
        }),
      });

      const data = await res.json();
      if (data.ok) {
        // Remove the comment from the list
        setComments((prev) =>
          prev.filter(
            (c) =>
              !(
                c.platform === platform &&
                c.platform_post_id === platform_post_id &&
                c.comment_id === comment_id
              )
          )
        );
      } else {
        setError(data.error || "Failed to update toxicity status");
      }
    } catch (err) {
      setError("Failed to update toxicity status");
    } finally {
      setProcessing((prev) => {
        const next = new Set(prev);
        next.delete(key);
        return next;
      });
    }
  }

  function formatDate(dateStr: string | null): string {
    if (!dateStr) return "Unknown";
    try {
      return new Date(dateStr).toLocaleString();
    } catch {
      return dateStr;
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-black via-gray-900 to-black p-4 sm:p-8">
      <div className="mx-auto max-w-7xl">
        {/* Header */}
        <div className="mb-8 flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-white">Toxicity Review</h1>
            <p className="mt-2 text-sm text-white/60">
              Review and correct comments flagged as toxic by AI analysis
            </p>
          </div>
          <div className="flex gap-3">
            <Link
              href="/settings"
              className="rounded-xl border border-white/15 bg-white/5 px-4 py-2 text-sm hover:bg-white/10"
            >
              Settings
            </Link>
            <Link
              href="/help"
              className="rounded-xl border border-white/15 bg-white/5 px-4 py-2 text-sm hover:bg-white/10"
            >
              Help
            </Link>
            <Link
              href="/"
              className="rounded-xl border border-white/15 bg-white/5 px-4 py-2 text-sm hover:bg-white/10"
            >
              ← Back to Dashboard
            </Link>
          </div>
        </div>

        {/* Stats */}
        <div className="mb-6 rounded-2xl border border-white/10 bg-white/5 p-4">
          <div className="text-sm text-white/60">
            Comments pending review: <span className="font-semibold text-white">{comments.length}</span>
          </div>
        </div>

        {error && (
          <div className="mb-6 rounded-xl border border-red-500/30 bg-red-500/10 p-4 text-sm text-red-200">
            {error}
          </div>
        )}

        {loading ? (
          <div className="text-center text-white/60">Loading toxic comments...</div>
        ) : comments.length === 0 ? (
          <div className="rounded-2xl border border-white/10 bg-white/5 p-8 text-center">
            <div className="text-xl font-semibold text-white">No toxic comments to review</div>
            <div className="mt-2 text-sm text-white/60">
              All comments flagged as toxic have been reviewed, or no toxic comments were found.
            </div>
          </div>
        ) : (
          <div className="space-y-4">
            {comments.map((comment) => {
              const key = `${comment.platform}_${comment.platform_post_id}_${comment.comment_id}`;
              const isProcessing = processing.has(key);

              return (
                <div
                  key={key}
                  className="futuristic-panel rounded-2xl border border-white/10 bg-white/5 p-6"
                >
                  <div className="mb-4 flex items-start justify-between gap-4">
                    <div className="flex-1">
                      <div className="mb-2 flex items-center gap-3">
                        <span className="font-semibold text-white">
                          @{comment.username || "Unknown"}
                        </span>
                        <span className="text-xs text-white/40 capitalize">{comment.platform}</span>
                        {comment.toxicity_level !== null && (
                          <span className="rounded-full bg-red-500/20 px-2 py-0.5 text-xs text-red-400">
                            {comment.toxicity_level}% toxic
                          </span>
                        )}
                      </div>
                      <div className="mb-3 text-white/90">{comment.text || "(No text)"}</div>
                      <div className="flex flex-wrap gap-4 text-xs text-white/50">
                        {comment.timestamp && (
                          <span>Posted: {formatDate(comment.timestamp)}</span>
                        )}
                        {comment.like_count !== null && (
                          <span>Likes: {comment.like_count}</span>
                        )}
                        {comment.created_at && (
                          <span>Analyzed: {formatDate(comment.created_at)}</span>
                        )}
                      </div>
                    </div>
                  </div>

                  <div className="flex gap-3">
                    <button
                      onClick={() =>
                        updateToxicity(
                          comment.platform,
                          comment.platform_post_id,
                          comment.comment_id,
                          true
                        )
                      }
                      disabled={isProcessing}
                      className="rounded-lg bg-red-600 px-6 py-2 font-semibold text-white transition-all hover:bg-red-700 disabled:cursor-not-allowed disabled:opacity-50"
                    >
                      {isProcessing ? "Processing..." : "Toxic"}
                    </button>
                    <button
                      onClick={() =>
                        updateToxicity(
                          comment.platform,
                          comment.platform_post_id,
                          comment.comment_id,
                          false
                        )
                      }
                      disabled={isProcessing}
                      className="rounded-lg bg-green-600 px-6 py-2 font-semibold text-white transition-all hover:bg-green-700 disabled:cursor-not-allowed disabled:opacity-50"
                    >
                      {isProcessing ? "Processing..." : "Not Toxic"}
                    </button>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}
