"use client";
import { useState, useEffect, useCallback } from "react";

type VideoRow = { id: string; title: string; views: number; createdAt: string | null };
type BlogRow = { id: string; title: string; slug: string; viewCount: number; publishedAt: string | null };

export default function ViewCountsPage() {
  const [tab, setTab] = useState<"videos" | "blog">("videos");
  const [search, setSearch] = useState("");
  const [videos, setVideos] = useState<VideoRow[]>([]);
  const [blogs, setBlogs] = useState<BlogRow[]>([]);
  const [loading, setLoading] = useState(false);
  const [editing, setEditing] = useState<{ id: string; type: "video" | "blog"; value: number } | null>(null);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    const res = await fetch(`/api/admin/view-counts?q=${encodeURIComponent(search)}&type=${tab}`);
    const data = await res.json();
    if (tab === "videos") setVideos(data.rows || []);
    else setBlogs(data.rows || []);
    setLoading(false);
  }, [search, tab]);

  useEffect(() => { load(); }, [load]);

  async function saveEdit() {
    if (!editing) return;
    setSaving(true);
    await fetch("/api/admin/view-counts", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id: editing.id, type: editing.type, value: editing.value }),
    });
    setSaving(false);
    setEditing(null);
    setSaved(editing.id);
    setTimeout(() => setSaved(null), 2000);
    load();
  }

  const tabs = [
    { key: "videos" as const, label: "📹 Videos", count: videos.length },
    { key: "blog" as const, label: "📝 Blog Posts", count: blogs.length },
  ];

  return (
    <div>
      <h2 className="text-lg font-semibold mb-1">View Count Manager</h2>
      <p className="text-xs text-neutral-500 mb-4">Search and edit view counts for videos and blog posts.</p>

      <div className="flex gap-2 mb-4">
        {tabs.map((t) => (
          <button key={t.key} onClick={() => { setTab(t.key); setSearch(""); }}
            className={`px-4 py-2 rounded-full text-sm font-medium transition-colors ${tab === t.key ? "bg-red-600 text-white" : "bg-neutral-800 text-neutral-400 hover:bg-neutral-700"}`}>
            {t.label}
          </button>
        ))}
      </div>

      <div className="mb-4">
        <input
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder={`Search ${tab === "videos" ? "videos" : "blog posts"}...`}
          className="w-full max-w-md bg-neutral-900 border border-neutral-800 rounded-lg px-4 py-2 text-sm outline-none focus:border-red-600"
        />
      </div>

      {loading ? (
        <p className="text-neutral-500 text-sm text-center py-10">Loading...</p>
      ) : (
        <div className="card overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-neutral-900 text-neutral-500 text-left">
              <tr>
                <th className="p-3">Title</th>
                <th className="p-3 w-32">Views</th>
                <th className="p-3 w-28">Date</th>
                <th className="p-3 w-20">Edit</th>
              </tr>
            </thead>
            <tbody>
              {tab === "videos" && videos.map((v) => (
                <tr key={v.id} className="border-t border-neutral-800 hover:bg-neutral-900/40">
                  <td className="p-3">{v.title}</td>
                  <td className="p-3">
                    {editing?.id === v.id ? (
                      <div className="flex items-center gap-1.5">
                        <input
                          type="number"
                          value={editing.value}
                          onChange={(e) => setEditing({ ...editing, value: parseInt(e.target.value) || 0 })}
                          className="w-20 bg-neutral-800 border border-neutral-700 rounded px-2 py-1 text-sm"
                          autoFocus
                        />
                        <button onClick={saveEdit} disabled={saving} className="text-green-500 hover:text-green-400 font-bold text-sm">
                          {saving ? "…" : "✓"}
                        </button>
                        <button onClick={() => setEditing(null)} className="text-neutral-500 hover:text-white text-sm">✕</button>
                      </div>
                    ) : (
                      <span className={saved === v.id ? "text-green-500" : ""}>{v.views.toLocaleString()}</span>
                    )}
                  </td>
                  <td className="p-3 text-neutral-500 text-xs">{v.createdAt ? new Date(v.createdAt).toLocaleDateString() : "—"}</td>
                  <td className="p-3">
                    <button onClick={() => setEditing({ id: v.id, type: "video", value: v.views })} className="text-xs text-neutral-400 hover:text-white">Edit</button>
                  </td>
                </tr>
              ))}
              {tab === "blog" && blogs.map((b) => (
                <tr key={b.id} className="border-t border-neutral-800 hover:bg-neutral-900/40">
                  <td className="p-3">{b.title}</td>
                  <td className="p-3">
                    {editing?.id === b.id ? (
                      <div className="flex items-center gap-1.5">
                        <input
                          type="number"
                          value={editing.value}
                          onChange={(e) => setEditing({ ...editing, value: parseInt(e.target.value) || 0 })}
                          className="w-20 bg-neutral-800 border border-neutral-700 rounded px-2 py-1 text-sm"
                          autoFocus
                        />
                        <button onClick={saveEdit} disabled={saving} className="text-green-500 hover:text-green-400 font-bold text-sm">
                          {saving ? "…" : "✓"}
                        </button>
                        <button onClick={() => setEditing(null)} className="text-neutral-500 hover:text-white text-sm">✕</button>
                      </div>
                    ) : (
                      <span className={saved === b.id ? "text-green-500" : ""}>{b.viewCount.toLocaleString()}</span>
                    )}
                  </td>
                  <td className="p-3 text-neutral-500 text-xs">{b.publishedAt ? new Date(b.publishedAt).toLocaleDateString() : "—"}</td>
                  <td className="p-3">
                    <button onClick={() => setEditing({ id: b.id, type: "blog", value: b.viewCount })} className="text-xs text-neutral-400 hover:text-white">Edit</button>
                  </td>
                </tr>
              ))}
              {((tab === "videos" && videos.length === 0) || (tab === "blog" && blogs.length === 0)) && (
                <tr><td colSpan={4} className="p-8 text-center text-neutral-500">No results.</td></tr>
              )}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
