import { useEffect, useState } from "react";
import { Alert } from "antd";
import { apiClient } from "@shared/api/client";

type EnterpriseRow = { id: string; name: string; slug: string; status: string };

export function AdminEnterprisesPanel(): JSX.Element {
  const [rows, setRows] = useState<EnterpriseRow[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    void (async () => {
      try {
        const { data } = await apiClient.get<EnterpriseRow[]>("/api/v1/admin/enterprises");
        setRows(Array.isArray(data) ? data : []);
        setError(null);
      } catch (loadError) {
        const message = loadError instanceof Error ? loadError.message : "Failed to load enterprises";
        setError(message);
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  if (loading) {
    return <p className="wesp-admin-block">Loading enterprises...</p>;
  }

  if (error) {
    return <Alert type="error" message={error} />;
  }

  return (
    <div>
      <h2>Enterprises</h2>
      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Slug</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody>
          {rows.map((r) => (
            <tr key={r.id}>
              <td>{r.name}</td>
              <td>{r.slug}</td>
              <td>{r.status}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
