'use client';

import { useEffect, useState } from 'react';
import { apiFetch } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { StatusPill } from '@/components/status-pill';
import { Trash2, RefreshCw } from 'lucide-react';

interface Row {
  server: {
    id: string;
    slug: string;
    name: string;
    status: string;
    currentVersion: number;
    publicUrl: string | null;
    hostPort: number | null;
    createdAt: string;
    updatedAt: string;
  };
  org: { id: string; name: string; slug: string; plan: string };
}

const STATUS_FILTERS = ['', 'live', 'building', 'deploying', 'generating', 'failed', 'paused', 'draft'];

export default function AdminServersPage() {
  const [rows, setRows] = useState<Row[] | null>(null);
  const [status, setStatus] = useState('');

  async function reload() {
    const r = await apiFetch<{ servers: Row[] }>(
      `/v1/admin/servers${status ? `?status=${status}` : ''}`,
    );
    setRows(r.servers);
  }

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

  async function rebuild(s: Row['server']) {
    if (!confirm(`Trigger a force rebuild of "${s.name}" (v${s.currentVersion} → v${s.currentVersion + 1})?`)) return;
    try {
      await apiFetch(`/v1/admin/servers/${s.id}/rebuild`, { method: 'POST' });
      reload();
    } catch (e) {
      alert(`Failed: ${(e as Error).message}`);
    }
  }

  async function remove(s: Row['server']) {
    if (!confirm(`Permanently delete "${s.name}" and stop its container?`)) return;
    await apiFetch(`/v1/admin/servers/${s.id}`, { method: 'DELETE' });
    reload();
  }

  return (
    <div className="px-8 py-8">
      <header className="mb-6">
        <h1 className="text-[22px] font-semibold tracking-tight">MCP servers</h1>
        <p className="mt-1 text-[13px] text-[--color-fg-muted]">
          Cross-organization view. Force rebuilds, deletions, status filtering.
        </p>
      </header>

      <div className="mb-4 flex gap-2">
        <select
          value={status}
          onChange={(e) => setStatus(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>
        )}
        {rows && rows.length === 0 && (
          <p className="px-4 py-12 text-center text-[13px] text-[--color-fg-muted]">No servers.</p>
        )}
        {rows && rows.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">Name</th>
                <th className="px-4 py-2 text-left font-medium">Org</th>
                <th className="px-4 py-2 text-left font-medium">Status</th>
                <th className="px-4 py-2 text-left font-medium">URL</th>
                <th className="px-4 py-2 text-left font-medium">Updated</th>
                <th className="px-4 py-2 text-right font-medium">Actions</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((r) => (
                <tr key={r.server.id} className="border-b border-[--color-border] last:border-0">
                  <td className="px-4 py-2.5">
                    <div className="font-medium">{r.server.name}</div>
                    <div className="mono text-[11px] text-[--color-fg-subtle]">
                      {r.server.slug} · v{r.server.currentVersion}
                    </div>
                  </td>
                  <td className="px-4 py-2.5">
                    <div>{r.org.name}</div>
                    <div className="mono text-[11px] text-[--color-fg-subtle]">
                      {r.org.plan}
                    </div>
                  </td>
                  <td className="px-4 py-2.5">
                    <StatusPill status={r.server.status as never} />
                  </td>
                  <td className="px-4 py-2.5 mono text-[--color-fg-muted]">
                    {r.server.publicUrl ? (
                      <a
                        href={`${r.server.publicUrl}/mcp`}
                        target="_blank"
                        rel="noreferrer"
                        className="hover:text-[--color-fg]"
                      >
                        {r.server.publicUrl}
                      </a>
                    ) : (
                      '—'
                    )}
                  </td>
                  <td className="px-4 py-2.5 text-[--color-fg-muted]">
                    {new Date(r.server.updatedAt).toLocaleString()}
                  </td>
                  <td className="px-4 py-2.5 text-right">
                    <div className="inline-flex gap-1">
                      <Button variant="ghost" size="sm" onClick={() => rebuild(r.server)}>
                        <RefreshCw size={11} /> rebuild
                      </Button>
                      <Button variant="danger" size="sm" onClick={() => remove(r.server)}>
                        <Trash2 size={11} />
                      </Button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
