"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { Button, EmptyState, Modal, Spinner, useToast } from "@/components/ui";
import { api } from "@/lib/api-client";
import { formatCount, formatDate, timeAgo } from "@/lib/format";
import { CATEGORIES, VISIBILITIES } from "@/lib/constants";

type Upload = {
  id: string;
  title: string;
  views: number;
  likes: number;
  comments: number;
  visibility: string;
  status: string;
  monetized: boolean;
  copyrightStatus: string;
  duration: number;
  thumbnailUrl: string | null;
  publishedAt: string | null;
  scheduledFor: string | null;
  isShort: boolean;
};

export default function StudioContent() {
  const { toast, toastNode } = useToast();
  const [items, setItems] = useState<Upload[] | null>(null);
  const [editing, setEditing] = useState<Upload | null>(null);
  const [form, setForm] = useState({ title: "", description: "", visibility: "public", categorySlug: "entertainment", tags: "", monetized: false, isAgeRestricted: false });
  const [filter, setFilter] = useState<"all" | "public" | "private" | "draft" | "shorts">("all");

  const load = async () => {
    const data = await api<{ uploads: Upload[] }>("/api/studio/analytics").catch(() => null);
    setItems(data?.uploads ?? []);
  };

  useEffect(() => {
    void load();
    const interval = setInterval(() => void load(), 8000);
    return () => clearInterval(interval);
  }, []);

  const openEdit = (video: Upload) => {
    setEditing(video);
    setForm({ title: video.title, description: "", visibility: video.visibility, categorySlug: "entertainment", tags: "", monetized: video.monetized, isAgeRestricted: false });
  };

  const save = async () => {
    if (!editing) return;
    await api(`/api/videos/${editing.id}`, {
      method: "PATCH",
      json: {
        title: form.title,
        description: form.description,
        visibility: form.visibility,
        categorySlug: form.categorySlug,
        tags: form.tags.split(",").map((t) => t.trim()).filter(Boolean),
        monetized: form.monetized,
        isAgeRestricted: form.isAgeRestricted,
        instantPublish: form.visibility === "public",
      },
    }).catch((e) => toast(e.message));
    toast("Video updated");
    setEditing(null);
    await load();
  };

  const filtered = items?.filter((item) =>
    filter === "all" ? true : filter === "shorts" ? item.isShort : item.visibility === filter,
  );

  return (
    <div className="space-y-4">
      <header className="flex flex-wrap items-center justify-between gap-3">
        <h1 className="text-2xl font-bold">Channel content</h1>
        <Link href="/studio/upload"><Button>⬆️ Upload</Button></Link>
      </header>

      <div className="flex flex-wrap gap-2">
        {(["all", "public", "private", "draft", "shorts"] as const).map((key) => (
          <button key={key} onClick={() => setFilter(key)} className={`rounded-full px-3 py-1.5 text-xs font-semibold capitalize ${filter === key ? "bg-fg text-bg" : "bg-chip"}`}>
            {key}
          </button>
        ))}
      </div>

      {items === null ? <div className="grid place-items-center py-16"><Spinner /></div> : null}
      {items !== null && items.length === 0 ? (
        <EmptyState icon="🎬" title="No uploads yet" hint="Publish your first video to unlock analytics and monetization." action={<Link href="/studio/upload" className="text-sm font-semibold text-brand">Upload a video</Link>} />
      ) : null}

      <div className="overflow-x-auto rounded-xl border border-line">
        <table className="w-full min-w-[720px] text-sm">
          <thead className="bg-surface text-left text-xs uppercase tracking-wide text-muted">
            <tr>
              <th className="p-3">Video</th>
              <th className="p-3">Visibility</th>
              <th className="p-3">Views</th>
              <th className="p-3">Likes</th>
              <th className="p-3">Comments</th>
              <th className="p-3">Copyright</th>
              <th className="p-3">Actions</th>
            </tr>
          </thead>
          <tbody>
            {filtered?.map((video) => (
              <tr key={video.id} className="border-t border-line">
                <td className="p-3">
                  <div className="flex items-center gap-3">
                    <div className="h-12 w-20 shrink-0 overflow-hidden rounded bg-surface">
                      {video.thumbnailUrl ? (
                        // eslint-disable-next-line @next/next/no-img-element
                        <img src={video.thumbnailUrl} alt="" className="h-full w-full object-cover" />
                      ) : null}
                    </div>
                    <div className="min-w-0">
                      <p className="line-clamp-1 font-medium">{video.title}</p>
                      <p className="text-xs text-muted">
                        {video.status === "ready"
                          ? video.publishedAt
                            ? `Published ${timeAgo(video.publishedAt)}`
                            : video.scheduledFor
                              ? `Scheduled ${formatDate(video.scheduledFor)}`
                              : "Not published"
                          : `${video.status} · processing`}
                      </p>
                    </div>
                  </div>
                </td>
                <td className="p-3 text-xs uppercase text-muted">{video.visibility}</td>
                <td className="p-3">{formatCount(video.views)}</td>
                <td className="p-3">{formatCount(video.likes)}</td>
                <td className="p-3">{formatCount(video.comments)}</td>
                <td className="p-3 text-xs">{video.copyrightStatus}</td>
                <td className="p-3">
                  <div className="flex flex-wrap gap-1">
                    <button onClick={() => openEdit(video)} className="rounded bg-surface px-2 py-1 text-xs">Edit</button>
                    <Link href={`/watch/${video.id}`} className="rounded bg-surface px-2 py-1 text-xs">View</Link>
                    <button
                      onClick={async () => {
                        await api(`/api/videos/${video.id}/reprocess`, { method: "POST" }).catch((e) => toast(e.message));
                        toast("Re-processing queued");
                      }}
                      className="rounded bg-surface px-2 py-1 text-xs"
                    >
                      Retranscode
                    </button>
                    <button
                      onClick={async () => {
                        if (!confirm(`Delete "${video.title}"? This cannot be undone.`)) return;
                        await api(`/api/videos/${video.id}`, { method: "DELETE" }).catch((e) => toast(e.message));
                        toast("Video deleted");
                        await load();
                      }}
                      className="rounded bg-red-600/10 px-2 py-1 text-xs text-red-500"
                    >
                      Delete
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <Modal open={Boolean(editing)} onClose={() => setEditing(null)} title="Edit video metadata">
        <div className="space-y-3">
          <input value={form.title} onChange={(event) => setForm({ ...form, title: event.target.value })} className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm" />
          <textarea value={form.description} onChange={(event) => setForm({ ...form, description: event.target.value })} rows={4} placeholder="Description" className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm" />
          <input value={form.tags} onChange={(event) => setForm({ ...form, tags: event.target.value })} placeholder="Tags, comma separated" className="w-full rounded-lg border border-line bg-surface px-3 py-2 text-sm" />
          <div className="grid gap-3 sm:grid-cols-2">
            <select value={form.visibility} onChange={(event) => setForm({ ...form, visibility: event.target.value })} className="rounded-lg border border-line bg-surface px-3 py-2 text-sm">
              {VISIBILITIES.map((option) => (
                <option key={option.value} value={option.value}>{option.label} — {option.hint}</option>
              ))}
            </select>
            <select value={form.categorySlug} onChange={(event) => setForm({ ...form, categorySlug: event.target.value })} className="rounded-lg border border-line bg-surface px-3 py-2 text-sm">
              {CATEGORIES.filter((c) => c.slug !== "all").map((category) => (
                <option key={category.slug} value={category.slug}>{category.name}</option>
              ))}
            </select>
          </div>
          <div className="flex flex-wrap gap-4 text-sm">
            <label className="flex items-center gap-2"><input type="checkbox" checked={form.monetized} onChange={(event) => setForm({ ...form, monetized: event.target.checked })} /> Monetize</label>
            <label className="flex items-center gap-2"><input type="checkbox" checked={form.isAgeRestricted} onChange={(event) => setForm({ ...form, isAgeRestricted: event.target.checked })} /> Age restrict (18+)</label>
          </div>
          <Button onClick={() => void save()}>Save changes</Button>
        </div>
      </Modal>
      {toastNode}
    </div>
  );
}
