'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { apiFetch } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { ShieldCheck } from 'lucide-react';

interface AdminTemplate {
  id: string;
  slug: string;
  title: string;
  shortDescription: string;
  category: string;
  status: 'draft' | 'public' | 'hidden' | 'takedown';
  verified: boolean;
  takedownReason: string | null;
  forkCount: number;
  activeDeployments: number;
  ownerEmail: string | null;
  ownerOrgName: string | null;
  createdAt: string;
}

const STATUS_FILTERS = ['', 'public', 'hidden', 'takedown', 'draft'];

export default function AdminTemplatesPage() {
  const [rows, setRows] = useState<AdminTemplate[] | null>(null);
  const [statusFilter, setStatusFilter] = useState('');

  async function reload() {
    const r = await apiFetch<{ templates: AdminTemplate[] }>('/v1/admin/templates');
    setRows(r.templates);
  }

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

  async function toggleVerified(t: AdminTemplate) {
    if (!confirm(`${t.verified ? 'Unverify' : 'Verify'} "${t.title}"?`)) return;
    await apiFetch(`/v1/admin/templates/${t.id}`, {
      method: 'PATCH',
      body: JSON.stringify({ verified: !t.verified }),
    });
    reload();
  }

  async function takedown(t: AdminTemplate) {
    if (t.status === 'takedown') {
      if (!confirm(`Lift takedown on "${t.title}"? Forked servers stay paused — owners must re-deploy.`)) return;
      await apiFetch(`/v1/admin/templates/${t.id}`, {
        method: 'PATCH',
        body: JSON.stringify({ status: 'public', takedownReason: null }),
      });
    } else {
      const reason = prompt(
        `Take down "${t.title}"? This pauses ALL ${t.activeDeployments} active fork containers. Reason:`,
        '',
      );
      if (reason === null) return;
      await apiFetch(`/v1/admin/templates/${t.id}`, {
        method: 'PATCH',
        body: JSON.stringify({ status: 'takedown', takedownReason: reason || 'Removed by admin' }),
      });
    }
    reload();
  }

  async function toggleHidden(t: AdminTemplate) {
    const next = t.status === 'public' ? 'hidden' : 'public';
    await apiFetch(`/v1/admin/templates/${t.id}`, {
      method: 'PATCH',
      body: JSON.stringify({ status: next }),
    });
    reload();
  }

  const visible = rows?.filter((t) => (statusFilter ? t.status === statusFilter : true));

  return (
    <div className="px-8 py-8">
      <header className="mb-6">
        <h1 className="text-[22px] font-semibold tracking-tight">Templates moderation</h1>
        <p className="mt-1 text-[13px] text-[--color-fg-muted]">
          Verify quality templates, hide low-effort ones, take down anything malicious. Takedowns
          cascade-pause every fork container.
        </p>
      </header>

      <div className="mb-4 flex gap-2">
        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="h-8 rounded-md border border-[--color-border] bg-[--color-bg-subtle] px-2 text-[13px] focus:border-[--color-accent] focus:outline-none"
        >
          {STATUS_FILTERS.map((s) => (
            <option key={s} value={s}>
              {s ? s : 'All statuses'}
            </option>
          ))}
        </select>
      </div>

      <div className="panel">
        {rows === null && (
          <p className="px-4 py-3 text-[12.5px] text-[--color-fg-muted]">Loading…</p>
        )}
        {visible && visible.length === 0 && (
          <p className="px-4 py-12 text-center text-[13px] text-[--color-fg-muted]">
            No templates yet.
          </p>
        )}
        {visible && visible.length > 0 && (
          <table className="w-full text-[12.5px]">
            <thead className="border-b border-[--color-border] text-[--color-fg-subtle]">
              <tr>
                <th className="px-4 py-2 text-left font-medium">Title</th>
                <th className="px-4 py-2 text-left font-medium">Owner</th>
                <th className="px-4 py-2 text-left font-medium">Category</th>
                <th className="px-4 py-2 text-left font-medium">Status</th>
                <th className="px-4 py-2 text-left font-medium">Stats</th>
                <th className="px-4 py-2 text-right font-medium">Actions</th>
              </tr>
            </thead>
            <tbody>
              {visible.map((t) => (
                <tr key={t.id} className="border-b border-[--color-border] last:border-0">
                  <td className="px-4 py-2.5">
                    <div className="flex items-center gap-1.5">
                      <Link
                        href={`/templates/${t.slug}`}
                        target="_blank"
                        className="font-medium hover:text-[--color-accent]"
                      >
                        {t.title}
                      </Link>
                      {t.verified && (
                        <ShieldCheck size={11} className="text-[--color-accent]" />
                      )}
                    </div>
                    <div className="mono text-[11px] text-[--color-fg-subtle]">{t.slug}</div>
                  </td>
                  <td className="px-4 py-2.5 mono text-[--color-fg-muted]">{t.ownerEmail ?? '—'}</td>
                  <td className="px-4 py-2.5">
                    <span className="mono rounded-full border border-[--color-border] bg-[--color-bg-subtle] px-2 py-0.5 text-[11px]">
                      {t.category}
                    </span>
                  </td>
                  <td className="px-4 py-2.5">
                    <StatusBadge status={t.status} reason={t.takedownReason} />
                  </td>
                  <td className="px-4 py-2.5 mono text-[--color-fg-muted]">
                    {t.forkCount} forks · {t.activeDeployments} live
                  </td>
                  <td className="px-4 py-2.5 text-right">
                    <div className="inline-flex gap-1">
                      <Button variant="ghost" size="sm" onClick={() => toggleVerified(t)}>
                        {t.verified ? 'unverify' : 'verify'}
                      </Button>
                      {t.status !== 'takedown' && (
                        <Button variant="ghost" size="sm" onClick={() => toggleHidden(t)}>
                          {t.status === 'public' ? 'hide' : 'show'}
                        </Button>
                      )}
                      <Button variant="danger" size="sm" onClick={() => takedown(t)}>
                        {t.status === 'takedown' ? 'restore' : 'takedown'}
                      </Button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}

function StatusBadge({
  status,
  reason,
}: {
  status: AdminTemplate['status'];
  reason: string | null;
}) {
  const styles: Record<AdminTemplate['status'], string> = {
    public: 'border-emerald-400/40 bg-emerald-400/10 text-emerald-300',
    hidden: 'border-amber-400/40 bg-amber-400/10 text-amber-300',
    takedown: 'border-red-400/40 bg-red-400/10 text-red-300',
    draft: 'border-zinc-400/40 bg-zinc-400/10 text-zinc-300',
  };
  return (
    <span
      className={`mono inline-flex rounded-full border px-2 py-0.5 text-[11px] ${styles[status]}`}
      title={reason ?? ''}
    >
      {status}
    </span>
  );
}
