'use client';

import { useEffect, useState } from 'react';
import { apiFetch } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/input';

interface AdminOrg {
  id: string;
  slug: string;
  name: string;
  plan: string;
  monthlyCallQuota: number;
  callsThisPeriod: number;
  periodStartsAt: string;
  suspended: boolean;
  suspendedReason: string | null;
  createdAt: string;
  memberCount: number;
  serverCount: number;
}

export default function AdminOrgsPage() {
  const [orgs, setOrgs] = useState<AdminOrg[] | null>(null);
  const [search, setSearch] = useState('');

  async function reload() {
    const r = await apiFetch<{ orgs: AdminOrg[] }>('/v1/admin/orgs');
    setOrgs(r.orgs);
  }

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

  async function changePlan(o: AdminOrg) {
    const plan = prompt(
      `Change plan for "${o.name}". Current: ${o.plan}. Pick one of: hobby, pro, team, enterprise`,
      o.plan,
    );
    if (!plan || !['hobby', 'pro', 'team', 'enterprise'].includes(plan)) return;
    await apiFetch(`/v1/admin/orgs/${o.id}`, {
      method: 'PATCH',
      body: JSON.stringify({ plan }),
    });
    reload();
  }

  async function setQuota(o: AdminOrg) {
    const next = prompt(`New monthly call quota for "${o.name}":`, String(o.monthlyCallQuota));
    if (!next) return;
    const parsed = Number(next);
    if (!Number.isFinite(parsed) || parsed < 0) {
      alert('Invalid number');
      return;
    }
    await apiFetch(`/v1/admin/orgs/${o.id}`, {
      method: 'PATCH',
      body: JSON.stringify({ monthlyCallQuota: parsed }),
    });
    reload();
  }

  async function toggleSuspend(o: AdminOrg) {
    if (o.suspended) {
      if (!confirm(`Lift suspension on "${o.name}"?`)) return;
      await apiFetch(`/v1/admin/orgs/${o.id}`, {
        method: 'PATCH',
        body: JSON.stringify({ suspended: false, suspendedReason: null }),
      });
    } else {
      const reason = prompt(
        `Suspend "${o.name}"? This pauses ALL their MCP servers. Reason (visible in audit log):`,
        '',
      );
      if (reason === null) return;
      await apiFetch(`/v1/admin/orgs/${o.id}`, {
        method: 'PATCH',
        body: JSON.stringify({ suspended: true, suspendedReason: reason || 'Suspended by admin' }),
      });
    }
    reload();
  }

  const filtered = orgs?.filter((o) =>
    search
      ? o.name.toLowerCase().includes(search.toLowerCase()) ||
        o.slug.toLowerCase().includes(search.toLowerCase())
      : true,
  );

  return (
    <div className="px-8 py-8">
      <header className="mb-6">
        <h1 className="text-[22px] font-semibold tracking-tight">Organizations</h1>
        <p className="mt-1 text-[13px] text-[--color-fg-muted]">
          Plan management, quota overrides, suspension.
        </p>
      </header>

      <div className="mb-4">
        <Input
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Search by name or slug…"
          className="w-80"
        />
      </div>

      <div className="panel">
        {!filtered && (
          <p className="px-4 py-3 text-[12.5px] text-[--color-fg-muted]">Loading…</p>
        )}
        {filtered && filtered.length === 0 && (
          <p className="px-4 py-12 text-center text-[13px] text-[--color-fg-muted]">No matches.</p>
        )}
        {filtered && filtered.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">Plan</th>
                <th className="px-4 py-2 text-left font-medium">Members</th>
                <th className="px-4 py-2 text-left font-medium">Servers</th>
                <th className="px-4 py-2 text-left font-medium">Calls / quota</th>
                <th className="px-4 py-2 text-left font-medium">Status</th>
                <th className="px-4 py-2 text-right font-medium">Actions</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((o) => (
                <tr key={o.id} className="border-b border-[--color-border] last:border-0">
                  <td className="px-4 py-2.5">
                    <div>{o.name}</div>
                    <div className="mono text-[11px] text-[--color-fg-subtle]">{o.slug}</div>
                  </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]">
                      {o.plan}
                    </span>
                  </td>
                  <td className="px-4 py-2.5 mono text-[--color-fg-muted]">{o.memberCount}</td>
                  <td className="px-4 py-2.5 mono text-[--color-fg-muted]">{o.serverCount}</td>
                  <td className="px-4 py-2.5 mono text-[--color-fg-muted]">
                    {o.callsThisPeriod.toLocaleString()} / {o.monthlyCallQuota.toLocaleString()}
                  </td>
                  <td className="px-4 py-2.5">
                    {o.suspended ? (
                      <span
                        className="inline-flex items-center gap-1 rounded-full border border-red-400/40 bg-red-400/10 px-2 py-0.5 text-[11px] text-red-300"
                        title={o.suspendedReason ?? ''}
                      >
                        suspended
                      </span>
                    ) : (
                      <span className="inline-flex items-center gap-1 rounded-full border border-emerald-400/40 bg-emerald-400/10 px-2 py-0.5 text-[11px] text-emerald-300">
                        active
                      </span>
                    )}
                  </td>
                  <td className="px-4 py-2.5 text-right">
                    <div className="inline-flex gap-1">
                      <Button variant="ghost" size="sm" onClick={() => changePlan(o)}>
                        plan
                      </Button>
                      <Button variant="ghost" size="sm" onClick={() => setQuota(o)}>
                        quota
                      </Button>
                      <Button variant="danger" size="sm" onClick={() => toggleSuspend(o)}>
                        {o.suspended ? 'unsuspend' : 'suspend'}
                      </Button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}
