import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { wpApi } from "../api/wp-api";
import ReviewPrompt from "../components/ReviewPrompt";

interface ActivityItem {
  postId: number;
  title: string;
  date: string;
  editUrl: string;
  permalink: string;
  successCount: number;
  errorCount: number;
  channels: { type: string; status: string }[];
}

interface ActivityResponse {
  items: ActivityItem[];
  total: number;
  perPage: number;
  currentPage: number;
  totalPages: number;
}

const PLATFORM_ICONS: Record<string, string> = {
  Facebook: "📘", Instagram: "📷", TikTok: "🎵", Twitter: "𝕏",
  LinkedIn: "💼", Pinterest: "📌", YouTube: "▶️", Threads: "🧵",
  Bluesky: "🦋", Mastodon: "🐘",
};

export default function Activity() {
  const [page, setPage] = useState(1);

  const { data, isLoading } = useQuery({
    queryKey: ["activity", page],
    queryFn: () => wpApi.get<ActivityResponse>(`activity?page=${page}`),
  });

  return (
    <div>
      {/* Review prompt — shows after user has shared posts */}
      {data?.items && data.items.length > 0 && <ReviewPrompt />}

    <div className="vr-bg-white vr-rounded-xl vr-border vr-border-gray-200 vr-shadow-sm vr-p-7">
      <h2 className="vr-text-lg vr-font-bold vr-text-gray-900 vr-mb-1">Activity Log</h2>
      <p className="vr-text-sm vr-text-gray-500 vr-mb-5">History of blog posts shared to social media.</p>

      {isLoading ? (
        <div className="vr-flex vr-items-center vr-justify-center vr-gap-3 vr-py-10 vr-text-gray-400 vr-text-sm">
          <div className="vr-w-5 vr-h-5 vr-border-2 vr-border-gray-200 vr-border-t-primary-600 vr-rounded-full vr-animate-spin" />
          Loading activity...
        </div>
      ) : data?.items.length ? (
        <>
          <div className="vr-space-y-3">
            {data.items.map((item) => (
              <div
                key={item.postId}
                className="vr-p-4 vr-border vr-border-gray-200 vr-rounded-lg hover:vr-border-gray-300 vr-transition-all"
              >
                {/* Post info */}
                <div className="vr-flex vr-items-start vr-justify-between vr-gap-3 vr-mb-3">
                  <div className="vr-flex-1 vr-min-w-0">
                    <p className="vr-text-sm vr-font-semibold vr-text-gray-900 vr-truncate">{item.title}</p>
                    <p className="vr-text-xs vr-text-gray-500 vr-mt-0.5">{item.date}</p>
                  </div>
                  {/* Status badge */}
                  <span
                    className={`vr-inline-flex vr-items-center vr-gap-1 vr-px-2.5 vr-py-1 vr-rounded-full vr-text-xs vr-font-semibold vr-flex-shrink-0 ${
                      item.errorCount === 0
                        ? "vr-bg-emerald-50 vr-text-emerald-600"
                        : item.successCount === 0
                          ? "vr-bg-red-50 vr-text-red-500"
                          : "vr-bg-amber-50 vr-text-amber-600"
                    }`}
                  >
                    {item.errorCount === 0
                      ? `✓ ${item.successCount} sent`
                      : item.successCount === 0
                        ? `✕ ${item.errorCount} failed`
                        : `${item.successCount} sent, ${item.errorCount} failed`}
                  </span>
                </div>

                {/* Channel pills */}
                <div className="vr-flex vr-flex-wrap vr-gap-1.5">
                  {item.channels.map((ch, i) => (
                    <span
                      key={i}
                      className={`vr-inline-flex vr-items-center vr-gap-1 vr-px-2 vr-py-0.5 vr-rounded-md vr-text-xs vr-font-medium ${
                        ch.status === "success"
                          ? "vr-bg-emerald-50 vr-text-emerald-700"
                          : "vr-bg-red-50 vr-text-red-600"
                      }`}
                    >
                      {PLATFORM_ICONS[ch.type] || "🌐"} {ch.type}
                    </span>
                  ))}
                </div>
              </div>
            ))}
          </div>

          {/* Pagination */}
          {data.totalPages > 1 && (
            <div className="vr-flex vr-items-center vr-justify-between vr-mt-5 vr-pt-5 vr-border-t vr-border-gray-100">
              <button
                onClick={() => setPage((p) => Math.max(1, p - 1))}
                disabled={page <= 1}
                className="vr-inline-flex vr-items-center vr-gap-1.5 vr-px-4 vr-py-2 vr-bg-gray-100 vr-text-gray-600 vr-rounded-md vr-text-xs vr-font-medium disabled:vr-opacity-40 disabled:vr-cursor-not-allowed hover:vr-bg-gray-200 vr-transition-colors vr-border-0"
              >
                Previous
              </button>
              <span className="vr-text-xs vr-text-gray-400">
                Page {data.currentPage} of {data.totalPages}
              </span>
              <button
                onClick={() => setPage((p) => Math.min(data.totalPages, p + 1))}
                disabled={page >= data.totalPages}
                className="vr-inline-flex vr-items-center vr-gap-1.5 vr-px-4 vr-py-2 vr-bg-gray-100 vr-text-gray-600 vr-rounded-md vr-text-xs vr-font-medium disabled:vr-opacity-40 disabled:vr-cursor-not-allowed hover:vr-bg-gray-200 vr-transition-colors vr-border-0"
              >
                Next
              </button>
            </div>
          )}
        </>
      ) : (
        <div className="vr-text-center vr-py-10">
          <i className="fa-solid fa-clock-rotate-left vr-text-3xl vr-text-gray-200 vr-mb-3" />
          <h3 className="vr-text-sm vr-font-semibold vr-text-gray-900 vr-mb-1">No Activity Yet</h3>
          <p className="vr-text-xs vr-text-gray-500">
            Posts shared to social media will appear here. Enable Blog to Social or use the Share button to get started.
          </p>
        </div>
      )}
    </div>
    </div>
  );
}
