"use client";

import { useEffect, useState } from "react";
import { Button, EmptyState, Spinner, useToast } from "@/components/ui";
import { useSession } from "@/components/session-provider";
import { api } from "@/lib/api-client";
import { formatCount, formatDate, formatMoney } from "@/lib/format";

const SECTIONS = ["overview", "users", "channels", "videos", "comments", "reports", "categories", "ads", "monetization"] as const;
type Section = (typeof SECTIONS)[number];

export default function AdminPage() {
  const { user } = useSession();
  const { toast, toastNode } = useToast();
  const [section, setSection] = useState<Section>("overview");
  const [data, setData] = useState<Record<string, unknown> | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (user?.role !== "admin") return;
    setLoading(true);
    void api<Record<string, unknown>>(`/api/admin/${section}`)
      .then(setData)
      .catch((e) => toast(e.message))
      .finally(() => setLoading(false));
  }, [section, user]);

  if (!user) return <EmptyState icon="🔒" title="Sign in required" />;
  if (user.role !== "admin") return <EmptyState icon="🛡️" title="Admins only" hint="Your account does not have platform administration privileges." />;

  const act = async (payload: Record<string, unknown>) => {
    await api(`/api/admin/${section}`, { method: "POST", json: payload }).catch((e) => toast(e.message));
    toast("Action applied");
    const fresh = await api<Record<string, unknown>>(`/api/admin/${section}`).catch(() => null);
    if (fresh) setData(fresh);
  };

  const rows = (data?.items as Record<string, unknown>[] | undefined) ?? [];

  return (
    <div className="space-y-5 px-4 py-5">
      <header>
        <h1 className="text-2xl font-bold">Admin panel</h1>
        <p className="text-sm text-muted">Moderate content, manage users and monetization across PlayTube.</p>
      </header>

      <div className="no-scrollbar flex gap-2 overflow-x-auto">
        {SECTIONS.map((item) => (
          <button key={item} onClick={() => setSection(item)} className={`shrink-0 rounded-full px-3 py-1.5 text-xs font-semibold capitalize ${section === item ? "bg-fg text-bg" : "bg-chip"}`}>
            {item}
          </button>
        ))}
      </div>

      {loading ? <div className="grid place-items-center py-16"><Spinner /></div> : null}

      {section === "overview" && data ? (
        <div className="space-y-5">
          <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
            {Object.entries(data.counts as Record<string, number>).map(([key, value]) => (
              <div key={key} className="rounded-xl border border-line p-4">
                <p className="text-xs uppercase tracking-wide text-muted">{key}</p>
                <p className="mt-1 text-2xl font-bold">{formatCount(value)}</p>
              </div>
            ))}
            <div className="rounded-xl border border-line p-4">
              <p className="text-xs uppercase tracking-wide text-muted">Gross revenue</p>
              <p className="mt-1 text-2xl font-bold">{formatMoney((data.revenue as { earnedCents: number }).earnedCents)}</p>
            </div>
            <div className="rounded-xl border border-line p-4">
              <p className="text-xs uppercase tracking-wide text-muted">Active memberships</p>
              <p className="mt-1 text-2xl font-bold">{(data.revenue as { members: number }).members}</p>
            </div>
          </div>
          <div className="grid gap-4 lg:grid-cols-2">
            <div className="rounded-xl border border-line p-4">
              <h2 className="mb-2 text-sm font-bold uppercase text-muted">Newest users</h2>
              <div className="space-y-1 text-sm">
                {(data.recentUsers as { id: string; displayName: string; email: string; role: string }[]).map((row) => (
                  <p key={row.id} className="flex justify-between"><span>{row.displayName}</span><span className="text-xs text-muted">{row.role}</span></p>
                ))}
              </div>
            </div>
            <div className="rounded-xl border border-line p-4">
              <h2 className="mb-2 text-sm font-bold uppercase text-muted">Top videos</h2>
              <div className="space-y-1 text-sm">
                {(data.topVideos as { id: string; title: string; views: number }[]).map((row) => (
                  <p key={row.id} className="flex justify-between"><span className="line-clamp-1">{row.title}</span><span className="text-xs text-muted">{formatCount(row.views)}</span></p>
                ))}
              </div>
            </div>
          </div>
        </div>
      ) : null}

      {section !== "overview" && !loading ? (
        <div className="overflow-x-auto rounded-xl border border-line">
          {rows.length === 0 ? <p className="p-6 text-sm text-muted">Nothing to show in this section.</p> : null}
          {rows.length > 0 ? (
            <table className="w-full min-w-[760px] text-sm">
              <thead className="bg-surface text-left text-xs uppercase tracking-wide text-muted">
                <tr>
                  {Object.keys(rows[0]).filter((key) => key !== "id").map((key) => (
                    <th key={key} className="p-3">{key}</th>
                  ))}
                  <th className="p-3">Actions</th>
                </tr>
              </thead>
              <tbody>
                {rows.map((row) => (
                  <tr key={String(row.id)} className="border-t border-line align-top">
                    {Object.keys(rows[0]).filter((key) => key !== "id").map((key) => (
                      <td key={key} className="p-3 text-xs">
                        {typeof row[key] === "boolean" ? (row[key] ? "yes" : "no") : typeof row[key] === "number" ? formatCount(Number(row[key])) : row[key] instanceof Date || (typeof row[key] === "string" && String(row[key]).length > 10 && !Number.isNaN(Date.parse(String(row[key]))) && String(row[key]).includes("T")) ? formatDate(String(row[key])) : String(row[key] ?? "—").slice(0, 90)}
                      </td>
                    ))}
                    <td className="p-3">
                      <div className="flex flex-wrap gap-1">
                        {section === "users" ? (
                          <>
                            <button onClick={() => void act({ userId: row.id, action: row.isSuspended ? "reinstate" : "suspend", reason: "Policy violation" })} className="rounded bg-surface px-2 py-1 text-xs">
                              {row.isSuspended ? "Reinstate" : "Suspend"}
                            </button>
                            <button onClick={() => void act({ userId: row.id, action: "make_creator" })} className="rounded bg-surface px-2 py-1 text-xs">Make creator</button>
                            <button onClick={() => void act({ userId: row.id, action: "make_admin" })} className="rounded bg-surface px-2 py-1 text-xs">Make admin</button>
                          </>
                        ) : null}
                        {section === "channels" ? (
                          <>
                            <button onClick={() => void act({ channelId: row.id, action: row.isVerified ? "unverify" : "verify" })} className="rounded bg-surface px-2 py-1 text-xs">{row.isVerified ? "Unverify" : "Verify"}</button>
                            <button onClick={() => void act({ channelId: row.id, action: row.isMonetized ? "demonetize" : "monetize" })} className="rounded bg-surface px-2 py-1 text-xs">{row.isMonetized ? "Demonetize" : "Monetize"}</button>
                            <button onClick={() => void act({ channelId: row.id, action: row.isSuspended ? "reinstate" : "suspend" })} className="rounded bg-surface px-2 py-1 text-xs">{row.isSuspended ? "Reinstate" : "Suspend"}</button>
                          </>
                        ) : null}
                        {section === "videos" ? (
                          <>
                            <button onClick={() => void act({ videoId: row.id, action: row.visibility === "public" ? "unlist" : "publish" })} className="rounded bg-surface px-2 py-1 text-xs">{row.visibility === "public" ? "Unlist" : "Publish"}</button>
                            <button onClick={() => void act({ videoId: row.id, action: "age-restrict" })} className="rounded bg-surface px-2 py-1 text-xs">18+</button>
                            <button onClick={() => void act({ videoId: row.id, action: "copyright-flag" })} className="rounded bg-surface px-2 py-1 text-xs">© flag</button>
                            <button onClick={() => void act({ videoId: row.id, action: "remove" })} className="rounded bg-red-600/10 px-2 py-1 text-xs text-red-500">Remove</button>
                          </>
                        ) : null}
                        {section === "comments" ? (
                          <>
                            <button onClick={() => void act({ commentId: row.id, action: row.isModerated ? "restore" : "remove" })} className="rounded bg-surface px-2 py-1 text-xs">{row.isModerated ? "Restore" : "Remove"}</button>
                            <button onClick={() => void act({ commentId: row.id, action: "pin" })} className="rounded bg-surface px-2 py-1 text-xs">Pin</button>
                          </>
                        ) : null}
                        {section === "reports" ? (
                          <>
                            <button onClick={() => void act({ reportId: row.id, action: "resolve", note: "Handled" })} className="rounded bg-surface px-2 py-1 text-xs">Resolve</button>
                            <button onClick={() => void act({ reportId: row.id, action: "dismiss" })} className="rounded bg-surface px-2 py-1 text-xs">Dismiss</button>
                            <button onClick={() => void act({ reportId: row.id, action: "remove-content" })} className="rounded bg-red-600/10 px-2 py-1 text-xs text-red-500">Remove content</button>
                          </>
                        ) : null}
                        {section === "ads" ? (
                          <>
                            <button onClick={() => void act({ id: row.id, action: "toggle", isActive: !row.isActive })} className="rounded bg-surface px-2 py-1 text-xs">{row.isActive ? "Pause" : "Activate"}</button>
                            <button onClick={() => void act({ id: row.id, action: "delete" })} className="rounded bg-red-600/10 px-2 py-1 text-xs text-red-500">Delete</button>
                          </>
                        ) : null}
                        {section === "monetization" ? (
                          <button onClick={() => void act({ paymentId: row.id, action: "mark-paid" })} className="rounded bg-surface px-2 py-1 text-xs">Mark paid</button>
                        ) : null}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          ) : null}
        </div>
      ) : null}

      {section === "categories" ? (
        <div className="rounded-xl border border-line p-4">
          <h2 className="mb-3 text-sm font-bold uppercase text-muted">Add category</h2>
          <CategoryForm onSave={(payload) => void act({ action: "create", ...payload })} />
        </div>
      ) : null}

      {section === "ads" ? (
        <div className="rounded-xl border border-line p-4">
          <h2 className="mb-3 text-sm font-bold uppercase text-muted">Create advertisement</h2>
          <AdForm onSave={(payload) => void act({ action: "create", ...payload })} />
        </div>
      ) : null}
      {toastNode}
    </div>
  );
}

function CategoryForm({ onSave }: { onSave: (payload: Record<string, unknown>) => void }) {
  const [slug, setSlug] = useState("");
  const [name, setName] = useState("");
  const [emoji, setEmoji] = useState("🎬");
  return (
    <div className="grid gap-2 sm:grid-cols-4">
      <input value={slug} onChange={(event) => setSlug(event.target.value)} placeholder="slug" className="rounded-lg border border-line bg-surface px-3 py-2 text-sm" />
      <input value={name} onChange={(event) => setName(event.target.value)} placeholder="Name" className="rounded-lg border border-line bg-surface px-3 py-2 text-sm" />
      <input value={emoji} onChange={(event) => setEmoji(event.target.value)} placeholder="Emoji" className="rounded-lg border border-line bg-surface px-3 py-2 text-sm" />
      <Button onClick={() => onSave({ slug, name, emoji })}>Add</Button>
    </div>
  );
}

function AdForm({ onSave }: { onSave: (payload: Record<string, unknown>) => void }) {
  const [form, setForm] = useState({ advertiserName: "", headline: "", body: "", targetUrl: "https://example.com", placement: "preroll", cpmCents: 450 });
  return (
    <div className="grid gap-2 sm:grid-cols-2">
      <input value={form.advertiserName} onChange={(event) => setForm({ ...form, advertiserName: event.target.value })} placeholder="Advertiser" className="rounded-lg border border-line bg-surface px-3 py-2 text-sm" />
      <input value={form.headline} onChange={(event) => setForm({ ...form, headline: event.target.value })} placeholder="Headline" className="rounded-lg border border-line bg-surface px-3 py-2 text-sm" />
      <input value={form.targetUrl} onChange={(event) => setForm({ ...form, targetUrl: event.target.value })} placeholder="Target URL" className="rounded-lg border border-line bg-surface px-3 py-2 text-sm" />
      <select value={form.placement} onChange={(event) => setForm({ ...form, placement: event.target.value })} className="rounded-lg border border-line bg-surface px-3 py-2 text-sm">
        <option value="preroll">Preroll</option>
        <option value="in_feed">In-feed</option>
        <option value="display">Display</option>
        <option value="shorts">Shorts</option>
      </select>
      <Button onClick={() => onSave(form)}>Create ad</Button>
    </div>
  );
}
