/**
 * Organization list page.
 *
 * ⚠️ AUTO-GENERATED BY PRISM (GENERATE_ONCE) — safe to edit
 */

import { useEffect, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import {
  listMyOrganizations,
  type Organization,
  type OrganizationListResponse,
} from '../../lib/orgApi';

export default function OrgList() {
  const navigate = useNavigate();
  const [data, setData] = useState<OrganizationListResponse | null>(null);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    listMyOrganizations()
      .then(setData)
      .catch((e) => setError(e.message))
      .finally(() => setLoading(false));
  }, []);

  if (loading) return <div className="p-6">Loading organizations...</div>;
  if (error) return <div className="p-6 text-red-600">Error: {error}</div>;

  return (
    <div className="p-6 max-w-4xl mx-auto">
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold">Organizations</h1>
{% if allow_multiple_orgs %}
        <button
          onClick={() => navigate('/organizations/new')}
          className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
        >
          Create Organization
        </button>
{% endif %}
      </div>

      {data && data.organizations.length === 0 ? (
        <div className="text-center py-12">
          <p className="text-gray-500 mb-4">You don't belong to any organizations yet.</p>
{% if allow_multiple_orgs %}
          <button
            onClick={() => navigate('/organizations/new')}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
          >
            Create your first organization
          </button>
{% endif %}
        </div>
      ) : (
        <div className="space-y-3">
          {data?.organizations.map((org: Organization) => (
            <Link
              key={org.id}
              to={`/organizations/${org.{{ slug_field }}}`}
              className="block p-4 border rounded-lg hover:bg-gray-50 transition-colors"
            >
              <div className="flex items-center justify-between">
                <div>
                  <h2 className="font-semibold text-lg">{org.name}</h2>
                  {org.description && (
                    <p className="text-gray-500 text-sm mt-1">{org.description}</p>
                  )}
                </div>
                <div className="flex items-center gap-4 text-sm text-gray-500">
                  <span className="px-2 py-1 bg-gray-100 rounded">{org.current_user_role}</span>
                  <span>{org.member_count} member{org.member_count !== 1 ? 's' : ''}</span>
                </div>
              </div>
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}
