"use client";

import { useEffect, useState } from "react";
import { api } from "@/lib/api";
import { shortenPubkey } from "@/lib/nostr";
import { formatDate } from "@/lib/utils";
import {
  Clock,
  CheckCircle,
  XCircle,
  Inbox,
} from "lucide-react";

interface Submission {
  id: string;
  eventId?: string;
  naddr?: string;
  title: string;
  authorPubkey: string;
  status: string;
  reviewedBy?: string;
  reviewNote?: string;
  createdAt: string;
}

type FilterStatus = "ALL" | "PENDING" | "APPROVED" | "REJECTED";

const TABS: { value: FilterStatus; label: string }[] = [
  { value: "ALL", label: "All" },
  { value: "PENDING", label: "Pending" },
  { value: "APPROVED", label: "Approved" },
  { value: "REJECTED", label: "Rejected" },
];

export default function AdminSubmissionsPage() {
  const [submissions, setSubmissions] = useState<Submission[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");
  const [filter, setFilter] = useState<FilterStatus>("PENDING");
  const [reviewingId, setReviewingId] = useState<string | null>(null);
  const [reviewNote, setReviewNote] = useState("");
  const [processing, setProcessing] = useState(false);

  const loadSubmissions = async () => {
    try {
      const status = filter === "ALL" ? undefined : filter;
      const data = await api.getSubmissions(status);
      setSubmissions(data);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    setLoading(true);
    loadSubmissions();
  }, [filter]);

  const handleReview = async (id: string, status: "APPROVED" | "REJECTED") => {
    setProcessing(true);
    setError("");
    try {
      await api.reviewSubmission(id, { status, reviewNote: reviewNote.trim() || undefined });
      setReviewingId(null);
      setReviewNote("");
      await loadSubmissions();
    } catch (err: any) {
      setError(err.message);
    } finally {
      setProcessing(false);
    }
  };

  const pendingCount = submissions.filter((s) => s.status === "PENDING").length;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-on-surface">User Submissions</h1>
        {pendingCount > 0 && filter !== "PENDING" && (
          <span className="text-xs font-bold bg-primary/10 text-primary px-3 py-1 rounded-full">
            {pendingCount} pending
          </span>
        )}
      </div>

      {error && <p className="text-error text-sm">{error}</p>}

      <div className="flex gap-2">
        {TABS.map((tab) => (
          <button
            key={tab.value}
            onClick={() => setFilter(tab.value)}
            className={`px-4 py-2 rounded-lg text-sm font-semibold transition-colors ${
              filter === tab.value
                ? "bg-primary/20 text-primary"
                : "bg-surface-container-highest text-on-surface/60 hover:text-on-surface"
            }`}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {loading ? (
        <div className="space-y-3">
          {[1, 2, 3].map((i) => (
            <div key={i} className="animate-pulse bg-surface-container-low rounded-xl p-6">
              <div className="h-5 w-2/3 bg-surface-container-high rounded mb-3" />
              <div className="h-4 w-1/3 bg-surface-container-high rounded" />
            </div>
          ))}
        </div>
      ) : submissions.length === 0 ? (
        <div className="bg-surface-container-low rounded-xl p-8 text-center">
          <Inbox size={32} className="text-on-surface-variant/30 mx-auto mb-3" />
          <p className="text-on-surface-variant/60 text-sm">
            No {filter !== "ALL" ? filter.toLowerCase() : ""} submissions.
          </p>
        </div>
      ) : (
        <div className="space-y-3">
          {submissions.map((sub) => (
            <div
              key={sub.id}
              className="bg-surface-container-low rounded-xl p-6"
            >
              <div className="flex items-start justify-between gap-4">
                <div className="flex-1 min-w-0">
                  <h3 className="font-semibold text-on-surface">{sub.title}</h3>
                  <div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-on-surface-variant/60 mt-1">
                    <span>by {shortenPubkey(sub.authorPubkey)}</span>
                    <span>{formatDate(sub.createdAt)}</span>
                    {sub.eventId && (
                      <span className="font-mono">{sub.eventId.slice(0, 16)}...</span>
                    )}
                    {sub.naddr && (
                      <span className="font-mono">{sub.naddr.slice(0, 20)}...</span>
                    )}
                  </div>
                </div>
                <StatusBadge status={sub.status} />
              </div>

              {sub.reviewNote && (
                <p className="mt-3 text-sm text-on-surface-variant bg-surface-container-high rounded-lg px-4 py-2">
                  {sub.reviewNote}
                </p>
              )}

              {sub.status === "PENDING" && (
                <div className="mt-4">
                  {reviewingId === sub.id ? (
                    <div className="space-y-3">
                      <textarea
                        value={reviewNote}
                        onChange={(e) => setReviewNote(e.target.value)}
                        placeholder="Optional review note..."
                        rows={2}
                        className="w-full bg-surface-container-highest text-on-surface rounded-lg px-4 py-3 text-sm placeholder:text-on-surface-variant/40 focus:outline-none focus:ring-1 focus:ring-primary/40 resize-none"
                      />
                      <div className="flex gap-2">
                        <button
                          onClick={() => handleReview(sub.id, "APPROVED")}
                          disabled={processing}
                          className="flex items-center gap-2 px-4 py-2 rounded-lg bg-green-500/20 text-green-400 text-sm font-semibold hover:bg-green-500/30 transition-colors disabled:opacity-50"
                        >
                          <CheckCircle size={14} />
                          Approve
                        </button>
                        <button
                          onClick={() => handleReview(sub.id, "REJECTED")}
                          disabled={processing}
                          className="flex items-center gap-2 px-4 py-2 rounded-lg bg-error/20 text-error text-sm font-semibold hover:bg-error/30 transition-colors disabled:opacity-50"
                        >
                          <XCircle size={14} />
                          Reject
                        </button>
                        <button
                          onClick={() => {
                            setReviewingId(null);
                            setReviewNote("");
                          }}
                          className="px-4 py-2 rounded-lg bg-surface-container-highest text-on-surface/60 text-sm font-semibold hover:text-on-surface transition-colors"
                        >
                          Cancel
                        </button>
                      </div>
                    </div>
                  ) : (
                    <button
                      onClick={() => setReviewingId(sub.id)}
                      className="text-sm font-semibold text-primary hover:underline"
                    >
                      Review
                    </button>
                  )}
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function StatusBadge({ status }: { status: string }) {
  const config: Record<string, { icon: typeof Clock; className: string; label: string }> = {
    PENDING: { icon: Clock, className: "text-primary bg-primary/10", label: "Pending" },
    APPROVED: { icon: CheckCircle, className: "text-green-400 bg-green-400/10", label: "Approved" },
    REJECTED: { icon: XCircle, className: "text-error bg-error/10", label: "Rejected" },
  };

  const cfg = config[status] || config.PENDING;
  const Icon = cfg.icon;

  return (
    <span className={`flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-bold whitespace-nowrap ${cfg.className}`}>
      <Icon size={14} />
      {cfg.label}
    </span>
  );
}
