'use client';

import { RefreshCw, ShieldAlert } from 'lucide-react';
import { useEffect, useState } from 'react';

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

type ConnectorStatus = {
  entitlementStatus?: string;
  connector?: {
    ok?: boolean;
    status?: string;
    data?: {
      tenantEnvironment?: Record<string, unknown>;
      recentCommands?: Record<string, unknown>[];
      recentWebhookEvents?: Record<string, unknown>[];
      reconciliationExceptions?: Record<string, unknown>[];
    };
  };
};

export default function OpenPaydTenantDashboardPage() {
  const [environment, setEnvironment] = useState<'sandbox' | 'production'>('sandbox');
  const [data, setData] = useState<ConnectorStatus | 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 || 'OpenPayd status failed');
      setData(payload);
    } catch (e) {
      setError(e instanceof Error ? e.message : 'OpenPayd status failed');
    } finally {
      setLoading(false);
    }
  }

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

  const status = data?.connector?.data?.tenantEnvironment || {};
  const commands = data?.connector?.data?.recentCommands || [];
  const events = data?.connector?.data?.recentWebhookEvents || [];
  const exceptions = data?.connector?.data?.reconciliationExceptions || [];

  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">OpenPayd Connector</p>
          <h1 className="mt-1 text-3xl font-bold">Tenant Dashboard</h1>
          <p className="mt-2 max-w-3xl text-gray-400">
            Read-only operational view for entitlement, lifecycle, environment health, commands, webhook facts,
            and reconciliation exceptions. Sensitive account and credential values are not rendered here.
          </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>

      {error ? (
        <Card className="mb-6 border-red-800 bg-red-950/40">
          <CardContent className="pt-6 text-red-200">{error}</CardContent>
        </Card>
      ) : null}

      <div className="grid gap-4 md:grid-cols-3">
        <Card className="border-gray-800 bg-gray-900">
          <CardHeader><CardTitle className="text-white">Entitlement</CardTitle></CardHeader>
          <CardContent className="text-sm text-gray-300">{data?.entitlementStatus || 'Loading'}</CardContent>
        </Card>
        <Card className="border-gray-800 bg-gray-900">
          <CardHeader><CardTitle className="text-white">Lifecycle</CardTitle></CardHeader>
          <CardContent className="text-sm text-gray-300">{String(status.state || 'unknown')}</CardContent>
        </Card>
        <Card className="border-gray-800 bg-gray-900">
          <CardHeader><CardTitle className="text-white">Mutating Gate</CardTitle></CardHeader>
          <CardContent className="text-sm text-gray-300">{String(status.mutatingActionsEnabled || false)}</CardContent>
        </Card>
      </div>

      <div className="mt-6 grid gap-6 lg:grid-cols-2">
        <RecordList title="Recent Commands" rows={commands} />
        <RecordList title="Webhook Facts" rows={events} />
      </div>

      <Card className="mt-6 border-gray-800 bg-gray-900">
        <CardHeader>
          <CardTitle className="flex items-center gap-2 text-white">
            <ShieldAlert className="h-5 w-5 text-orange-400" /> Reconciliation Exceptions
          </CardTitle>
        </CardHeader>
        <CardContent>
          {exceptions.length === 0 ? (
            <p className="text-sm text-gray-400">No reconciliation exceptions reported.</p>
          ) : (
            <pre className="overflow-x-auto rounded-md bg-black/30 p-3 text-xs text-gray-300">
              {JSON.stringify(exceptions, null, 2)}
            </pre>
          )}
        </CardContent>
      </Card>
    </main>
  );
}

function RecordList({ title, rows }: { title: string; rows: Record<string, unknown>[] }) {
  return (
    <Card className="border-gray-800 bg-gray-900">
      <CardHeader><CardTitle className="text-white">{title}</CardTitle></CardHeader>
      <CardContent>
        {rows.length === 0 ? (
          <p className="text-sm text-gray-400">No records yet.</p>
        ) : (
          <pre className="max-h-80 overflow-auto rounded-md bg-black/30 p-3 text-xs text-gray-300">
            {JSON.stringify(rows, null, 2)}
          </pre>
        )}
      </CardContent>
    </Card>
  );
}
