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

import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import {
  getOrganization,
  listMembers,
  updateMemberRole,
  removeMember,
  inviteMember,
  listInvitations,
  revokeInvitation,
  type Organization,
  type Member,
  type Invitation,
} from '../../lib/orgApi';

const ORG_ROLES = [
{% for role in org_roles %}
  { name: '{{ role.name }}', description: '{{ role.description }}' },
{% endfor %}
];

export default function OrgMembers() {
  const { slug } = useParams<{ slug: string }>();
  const [org, setOrg] = useState<Organization | null>(null);
  const [members, setMembers] = useState<Member[]>([]);
  const [invitations, setInvitations] = useState<Invitation[]>([]);
  const [inviteEmail, setInviteEmail] = useState('');
  const [inviteRole, setInviteRole] = useState('{{ default_org_role }}');
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [loading, setLoading] = useState(true);

  const canManage =
    org?.current_user_role === 'owner' || org?.current_user_role === 'admin';

  useEffect(() => {
    if (!slug) return;
    Promise.all([
      getOrganization(slug),
      listMembers(slug),
      canManageCheck(slug),
    ])
      .then(([o, m]) => {
        setOrg(o);
        setMembers(m.members);
      })
      .catch((e) => setError(e.message))
      .finally(() => setLoading(false));
  }, [slug]);

  async function canManageCheck(slug: string) {
    try {
      const invs = await listInvitations(slug);
      setInvitations(invs);
    } catch {
      // User may not have permission to list invitations
    }
  }

  async function handleInvite(e: React.FormEvent) {
    e.preventDefault();
    if (!slug) return;
    setError('');
    setSuccess('');

    try {
      await inviteMember(slug, { email: inviteEmail, role: inviteRole });
      setSuccess(`Invitation sent to ${inviteEmail}`);
      setInviteEmail('');
      const invs = await listInvitations(slug);
      setInvitations(invs);
    } catch (err: any) {
      setError(err.message);
    }
  }

  async function handleRoleChange(userId: number, newRole: string) {
    if (!slug) return;
    setError('');
    try {
      await updateMemberRole(slug, userId, newRole);
      const m = await listMembers(slug);
      setMembers(m.members);
    } catch (err: any) {
      setError(err.message);
    }
  }

  async function handleRemove(userId: number) {
    if (!slug) return;
    if (!confirm('Remove this member from the organization?')) return;
    setError('');
    try {
      await removeMember(slug, userId);
      const m = await listMembers(slug);
      setMembers(m.members);
    } catch (err: any) {
      setError(err.message);
    }
  }

  async function handleRevokeInvitation(invitationId: number) {
    if (!slug) return;
    try {
      await revokeInvitation(slug, invitationId);
      const invs = await listInvitations(slug);
      setInvitations(invs);
    } catch (err: any) {
      setError(err.message);
    }
  }

  if (loading) return <div className="p-6">Loading members...</div>;
  if (!org) return <div className="p-6 text-red-600">Organization not found</div>;

  return (
    <div className="p-6 max-w-4xl">
      <h2 className="text-xl font-bold mb-6">Members</h2>

      {error && (
        <div className="mb-4 p-3 bg-red-50 border border-red-200 text-red-700 rounded-lg text-sm">
          {error}
        </div>
      )}
      {success && (
        <div className="mb-4 p-3 bg-green-50 border border-green-200 text-green-700 rounded-lg text-sm">
          {success}
        </div>
      )}

      {/* Invite form */}
      {canManage && (
        <form onSubmit={handleInvite} className="mb-8 p-4 border rounded-lg bg-gray-50">
          <h3 className="font-medium mb-3">Invite Member</h3>
          <div className="flex gap-3">
            <input
              type="email"
              value={inviteEmail}
              onChange={(e) => setInviteEmail(e.target.value)}
              placeholder="email@example.com"
              required
              className="flex-1 px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
            <select
              value={inviteRole}
              onChange={(e) => setInviteRole(e.target.value)}
              className="px-3 py-2 border rounded-lg"
            >
              {ORG_ROLES.map((r) => (
                <option key={r.name} value={r.name}>
                  {r.name}
                </option>
              ))}
            </select>
            <button
              type="submit"
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
            >
              Invite
            </button>
          </div>
        </form>
      )}

      {/* Members table */}
      <div className="border rounded-lg overflow-hidden">
        <table className="w-full">
          <thead className="bg-gray-50">
            <tr>
              <th className="px-4 py-3 text-left text-sm font-medium text-gray-600">User ID</th>
              <th className="px-4 py-3 text-left text-sm font-medium text-gray-600">Role</th>
              <th className="px-4 py-3 text-left text-sm font-medium text-gray-600">Joined</th>
              {canManage && (
                <th className="px-4 py-3 text-right text-sm font-medium text-gray-600">Actions</th>
              )}
            </tr>
          </thead>
          <tbody className="divide-y">
            {members.map((member) => (
              <tr key={member.id}>
                <td className="px-4 py-3 text-sm">{member.user_id}</td>
                <td className="px-4 py-3 text-sm">
                  {canManage ? (
                    <select
                      value={member.role}
                      onChange={(e) => handleRoleChange(member.user_id, e.target.value)}
                      className="px-2 py-1 border rounded text-sm"
                    >
                      {ORG_ROLES.map((r) => (
                        <option key={r.name} value={r.name}>
                          {r.name}
                        </option>
                      ))}
                    </select>
                  ) : (
                    <span className="px-2 py-1 bg-gray-100 rounded text-sm">{member.role}</span>
                  )}
                </td>
                <td className="px-4 py-3 text-sm text-gray-500">
                  {new Date(member.joined_at).toLocaleDateString()}
                </td>
                {canManage && (
                  <td className="px-4 py-3 text-right">
                    <button
                      onClick={() => handleRemove(member.user_id)}
                      className="text-sm text-red-600 hover:text-red-800"
                    >
                      Remove
                    </button>
                  </td>
                )}
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Pending invitations */}
      {canManage && invitations.length > 0 && (
        <div className="mt-8">
          <h3 className="font-medium mb-3">Pending Invitations</h3>
          <div className="border rounded-lg overflow-hidden">
            <table className="w-full">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-4 py-3 text-left text-sm font-medium text-gray-600">Email</th>
                  <th className="px-4 py-3 text-left text-sm font-medium text-gray-600">Role</th>
                  <th className="px-4 py-3 text-left text-sm font-medium text-gray-600">Expires</th>
                  <th className="px-4 py-3 text-right text-sm font-medium text-gray-600">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y">
                {invitations.map((inv) => (
                  <tr key={inv.id}>
                    <td className="px-4 py-3 text-sm">{inv.email}</td>
                    <td className="px-4 py-3 text-sm">
                      <span className="px-2 py-1 bg-gray-100 rounded">{inv.role}</span>
                    </td>
                    <td className="px-4 py-3 text-sm text-gray-500">
                      {new Date(inv.expires_at).toLocaleDateString()}
                    </td>
                    <td className="px-4 py-3 text-right">
                      <button
                        onClick={() => handleRevokeInvitation(inv.id)}
                        className="text-sm text-red-600 hover:text-red-800"
                      >
                        Revoke
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}
