'use client';

/**
 * TeamMembers — org roster with inline role changes + removal.
 *
 * Calls the canonical, correctly-typed member APIs (the old /admin forms POSTed
 * to a PATCH-only role route and a non-existent /remove route — both silently
 * broken):
 *   • role change → PATCH /api/orgs/[id]/members/[userId]/role   (owner only)
 *   • remove      → DELETE /api/orgs/[id]/members/[userId]        (admin+)
 *
 * Last-owner protection is enforced server-side; the resulting message is shown
 * inline. Role editing is offered only to owners; you cannot change or remove
 * your own row.
 */

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { UserMinus } from 'lucide-react';

const ROLE_TONES = { owner: 'mars', admin: 'ready', member: 'neutral', viewer: 'neutral' };
const ROLES = ['owner', 'admin', 'member', 'viewer'];

function initials(name = '', email = '') {
  const source = name || email || '';
  return (
    source.split(/[\s@.]+/).map((p) => p[0]).filter(Boolean).slice(0, 2).join('').toUpperCase() || '·'
  );
}

export default function TeamMembers({ orgId, members, currentUserId, canManage, isOwner }) {
  const router = useRouter();
  const [busy, setBusy] = useState('');
  const [error, setError] = useState('');

  async function changeRole(userId, role) {
    setError('');
    setBusy(userId);
    try {
      const res = await fetch(`/api/orgs/${orgId}/members/${userId}/role`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ role }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || data.message || 'Could not change role.');
      router.refresh();
    } catch (err) {
      setError(err.message);
    } finally {
      setBusy('');
    }
  }

  async function remove(userId, label) {
    if (!window.confirm(`Remove ${label} from this organization?`)) return;
    setError('');
    setBusy(userId);
    try {
      const res = await fetch(`/api/orgs/${orgId}/members/${userId}`, { method: 'DELETE' });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || data.message || 'Could not remove member.');
      router.refresh();
    } catch (err) {
      setError(err.message);
    } finally {
      setBusy('');
    }
  }

  if (!members || members.length === 0) {
    return (
      <div className="admin-card-list">
        <div className="admin-record admin-muted">No members yet. Invite teammates below.</div>
      </div>
    );
  }

  return (
    <div className="admin-card-list">
      {error ? (
        <div className="admin-record" role="alert" style={{ borderColor: 'var(--accent-500)', color: 'var(--accent-600)' }}>
          {error}
        </div>
      ) : null}

      <table className="admin-table">
        <thead>
          <tr>
            <th>Member</th>
            <th>Role</th>
            <th>Joined</th>
            {canManage ? <th aria-label="Actions" /> : null}
          </tr>
        </thead>
        <tbody>
          {members.map((m) => {
            const isSelf = m.user_id === currentUserId;
            const label = m.display_name || m.email || m.user_id;
            const rowBusy = busy === m.user_id;
            return (
              <tr key={m.user_id}>
                <td>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
                    <div className="org-card-avatar small" aria-hidden="true">{initials(m.display_name, m.email)}</div>
                    <div>
                      <div style={{ fontWeight: 600 }}>
                        {m.display_name || <span className="admin-muted">—</span>}
                        {isSelf ? <span className="admin-muted" style={{ fontWeight: 400 }}> · you</span> : null}
                      </div>
                      <div className="admin-muted" style={{ fontSize: '0.85em' }}>{m.email || '—'}</div>
                    </div>
                  </div>
                </td>
                <td>
                  {isOwner && !isSelf ? (
                    <select
                      className="admin-select"
                      defaultValue={m.role}
                      disabled={rowBusy}
                      onChange={(e) => changeRole(m.user_id, e.target.value)}
                      aria-label={`Role for ${label}`}
                    >
                      {ROLES.map((r) => <option key={r} value={r}>{r}</option>)}
                    </select>
                  ) : (
                    <StatusPill tone={ROLE_TONES[m.role] || 'neutral'}>{m.role}</StatusPill>
                  )}
                </td>
                <td className="admin-muted">{m.accepted_at ? m.accepted_at.slice(0, 10) : '—'}</td>
                {canManage ? (
                  <td style={{ textAlign: 'right' }}>
                    {!isSelf ? (
                      <button
                        type="button"
                        className="admin-btn-danger-sm"
                        disabled={rowBusy}
                        onClick={() => remove(m.user_id, label)}
                        style={{ display: 'inline-flex', alignItems: 'center', gap: '0.35rem' }}
                      >
                        <UserMinus className="settings-rail-icon" strokeWidth={1.75} aria-hidden="true" />
                        {rowBusy ? 'Removing…' : 'Remove'}
                      </button>
                    ) : null}
                  </td>
                ) : null}
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

function StatusPill({ tone, children }) {
  return <span className={`admin-pill ${tone}`}>{children}</span>;
}
