import { Link } from 'react-router-dom';
import { Button, Badge, SectionHeader, useToast } from '@cameleer/design-system';
import { PageLoader } from '../../components/PageLoader';
import {
  useOutboundConnections,
  useDeleteOutboundConnection,
  type OutboundConnectionDto,
  type TrustMode,
} from '../../api/queries/admin/outboundConnections';
import { describeApiError } from '../../api/errors';
import sectionStyles from '../../styles/section-card.module.css';

export default function OutboundConnectionsPage() {
  const { data, isLoading, error } = useOutboundConnections();
  const deleteMut = useDeleteOutboundConnection();
  const { toast } = useToast();

  if (isLoading) return <PageLoader />;
  if (error) return <div>Failed to load outbound connections: {describeApiError(error)}</div>;

  const rows = data ?? [];

  const onDelete = (c: OutboundConnectionDto) => {
    if (!confirm(`Delete outbound connection "${c.name}"?`)) return;
    deleteMut.mutate(c.id, {
      onSuccess: () => toast({ title: 'Deleted', description: c.name, variant: 'success' }),
      onError: (e) => toast({ title: 'Delete failed', description: describeApiError(e), variant: 'error' }),
    });
  };

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
        <SectionHeader>Outbound Connections</SectionHeader>
        <Link to="/admin/outbound-connections/new">
          <Button variant="primary">New connection</Button>
        </Link>
      </div>
      <div className={sectionStyles.section}>
        {rows.length === 0 ? (
          <p>No outbound connections yet. Create one to enable alerting webhooks or other outbound integrations.</p>
        ) : (
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={{ textAlign: 'left' }}>Name</th>
                <th style={{ textAlign: 'left' }}>Host</th>
                <th style={{ textAlign: 'left' }}>Method</th>
                <th style={{ textAlign: 'left' }}>Trust</th>
                <th style={{ textAlign: 'left' }}>Auth</th>
                <th style={{ textAlign: 'left' }}>Envs</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {rows.map((c) => (
                <tr key={c.id}>
                  <td><Link to={`/admin/outbound-connections/${c.id}`}>{c.name}</Link></td>
                  <td><code>{safeHost(c.url)}</code></td>
                  <td>{c.method}</td>
                  <td><TrustBadge mode={c.tlsTrustMode} /></td>
                  <td>{c.authKind}</td>
                  <td>{c.allowedEnvironmentIds.length > 0 ? c.allowedEnvironmentIds.length : 'all'}</td>
                  <td>
                    <Button variant="secondary" onClick={() => onDelete(c)} disabled={deleteMut.isPending}>
                      Delete
                    </Button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}

function safeHost(url: string): string {
  try { return new URL(url).host; }
  catch { return url; }
}

function TrustBadge({ mode }: { mode: TrustMode }) {
  if (mode === 'TRUST_ALL') return <Badge label="Trust all" color="error" variant="filled" />;
  if (mode === 'TRUST_PATHS') return <Badge label="Custom CA" color="warning" variant="filled" />;
  return <Badge label="System" color="auto" variant="filled" />;
}
