'use client';

import { Download, KeyRound, PauseCircle, PlayCircle, RefreshCw, ShieldCheck } from 'lucide-react';
import { useEffect, useState } from 'react';

import { RoleGate } from '@/components/auth/RoleGate';
import { Button } from '@/components/ui/Button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/Card';

type Environment = 'sandbox' | 'production';

export default function OpenPaydAdminPage() {
  return (
    <RoleGate
      allowedRoles={['admin', 'tenant-admin', 'ADMIN', 'TENANT_ADMIN']}
      callbackUrl="/admin/openpayd"
      badge="OpenPayd Admin"
      title="OpenPayd operator access required"
      subtitle="Sign in with a tenant-admin or internal-admin account to manage the OpenPayd connector."
    >
      <OpenPaydAdminWorkbench />
    </RoleGate>
  );
}

function OpenPaydAdminWorkbench() {
  const [environment, setEnvironment] = useState<Environment>('sandbox');
  const [status, setStatus] = useState<Record<string, unknown> | null>(null);
  const [message, setMessage] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  async function load() {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch(`/api/openpayd/status?environment=${environment}`, { cache: 'no-store' });
      const payload = await res.json();
      if (!res.ok) throw new Error(payload.error || payload.message || 'Status load failed');
      setStatus(payload);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Status load failed');
    } finally {
      setLoading(false);
    }
  }

  async function command(name: string, payload: Record<string, unknown> = {}) {
    setLoading(true);
    setError(null);
    setMessage(null);
    try {
      const res = await fetch(`/api/openpayd/commands/${name}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ environment, payload }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.status || data.error || data.message || `${name} failed`);
      setMessage(`${name}: ${data.status || 'ok'}`);
      await load();
    } catch (e) {
      setError(e instanceof Error ? e.message : `${name} failed`);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    void load();
  }, [environment]);

  return (
    <main className="mx-auto max-w-6xl px-4 py-10 text-white">
      <div className="mb-8 flex flex-col gap-4 md:flex-row md:items-end md:justify-between">
        <div>
          <p className="text-sm font-medium uppercase tracking-wide text-orange-400">Operator Console</p>
          <h1 className="mt-1 text-3xl font-bold">OpenPayd Connector Admin</h1>
          <p className="mt-2 max-w-3xl text-gray-400">
            Manage environment probes, lifecycle state, credential rotation workflow, evidence exports, and
            production gates without exposing raw OpenPayd credentials.
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant={environment === 'sandbox' ? 'primary' : 'outline'} onClick={() => setEnvironment('sandbox')}>
            Sandbox
          </Button>
          <Button variant={environment === 'production' ? 'primary' : 'outline'} onClick={() => setEnvironment('production')}>
            Production
          </Button>
          <Button variant="secondary" onClick={load} disabled={loading}>
            <RefreshCw className="mr-2 h-4 w-4" /> Refresh
          </Button>
        </div>
      </div>

      {message ? <div className="mb-4 rounded-md border border-emerald-800 bg-emerald-950/40 p-3 text-sm text-emerald-200">{message}</div> : null}
      {error ? <div className="mb-4 rounded-md border border-red-800 bg-red-950/40 p-3 text-sm text-red-200">{error}</div> : null}

      <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
        <ActionCard icon={PlayCircle} title="Run Probe" text="Token and read-only account probe." action={() => command('probeEnvironment')} disabled={loading} />
        <ActionCard icon={KeyRound} title="Rotate Credential" text="Record a credential rotation through secret adapter." action={() => command('rotateCredential')} disabled={loading} />
        <ActionCard icon={ShieldCheck} title="Production Gate" text="Enable production mutating traffic for approved tenants." action={() => command('setProductionMutatingGate', { enabled: true })} disabled={loading || environment !== 'production'} />
        <ActionCard icon={PauseCircle} title="Suspend Tenant" text="Block new mutating actions and keep read-only reconciliation." action={() => command('suspendTenant')} disabled={loading} />
        <ActionCard icon={Download} title="Export Evidence" text="Generate redacted compliance evidence pack." action={() => command('exportComplianceEvidencePack')} disabled={loading} />
      </div>

      <Card className="mt-6 border-gray-800 bg-gray-900">
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-white">
            <ShieldCheck className="h-5 w-5 text-orange-400" /> Connector State
          </CardTitle>
        </CardHeader>
        <CardContent>
          <pre className="max-h-[36rem] overflow-auto rounded-md bg-black/30 p-3 text-xs text-gray-300">
            {JSON.stringify(status || {}, null, 2)}
          </pre>
        </CardContent>
      </Card>
    </main>
  );
}

function ActionCard({
  icon: Icon,
  title,
  text,
  action,
  disabled,
}: {
  icon: typeof PlayCircle;
  title: string;
  text: string;
  action: () => void;
  disabled: boolean;
}) {
  return (
    <Card className="border-gray-800 bg-gray-900">
      <CardHeader>
        <Icon className="h-6 w-6 text-orange-400" />
        <CardTitle className="text-white">{title}</CardTitle>
      </CardHeader>
      <CardContent>
        <p className="mb-4 text-sm text-gray-400">{text}</p>
        <Button variant="secondary" onClick={action} disabled={disabled}>Execute</Button>
      </CardContent>
    </Card>
  );
}
