import { FormEvent, useCallback, useEffect, useState } from 'react';
import Layout from '../../components/Layout';
import { api } from '../../lib/api';
import { useRequireAuth } from '../../lib/auth-context';

interface MemberRow {
  role: string;
  createdAt: string;
  user: { id: string; email: string; name: string };
}

const ROLES = ['ORG_ADMIN', 'MEMBER', 'VIEWER'];

export default function MembersPage() {
  const { user, activeOrg, loading } = useRequireAuth();
  const orgId = activeOrg?.org.id ?? null;
  const isAdmin = activeOrg?.role === 'ORG_ADMIN';

  const [members, setMembers] = useState<MemberRow[]>([]);
  const [email, setEmail] = useState('');
  const [role, setRole] = useState('MEMBER');
  const [error, setError] = useState<string | null>(null);

  const reload = useCallback(() => {
    if (!orgId) {
      return;
    }
    api
      .get<MemberRow[]>(`/api/orgs/${orgId}/members`)
      .then((rows) => {
        setMembers(rows);
        setError(null);
      })
      .catch((err) => setError(err.message));
  }, [orgId]);

  useEffect(reload, [reload]);

  const addMember = async (e: FormEvent) => {
    e.preventDefault();
    try {
      await api.post(`/api/orgs/${orgId}/members`, { email, role });
      setEmail('');
      reload();
    } catch (err: any) {
      setError(err.message);
    }
  };

  const changeRole = async (userId: string, newRole: string) => {
    try {
      await api.patch(`/api/orgs/${orgId}/members/${userId}`, { role: newRole });
      reload();
    } catch (err: any) {
      setError(err.message);
    }
  };

  const remove = async (userId: string) => {
    try {
      await api.delete(`/api/orgs/${orgId}/members/${userId}`);
      reload();
    } catch (err: any) {
      setError(err.message);
    }
  };

  if (loading || !user) {
    return null;
  }

  return (
    <Layout title="Members">
      <h1>Members</h1>
      {error && <p style={{ color: '#c62828' }}>{error}</p>}

      {isAdmin && (
        <form onSubmit={addMember} style={{ display: 'flex', gap: '0.5rem', marginBottom: '1.5rem' }}>
          <input
            type="email"
            placeholder="registered user's email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
            style={{ padding: '0.4rem', width: 280 }}
          />
          <select value={role} onChange={(e) => setRole(e.target.value)}>
            {ROLES.map((r) => (
              <option key={r} value={r}>
                {r}
              </option>
            ))}
          </select>
          <button type="submit">Add member</button>
        </form>
      )}

      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead>
          <tr style={{ textAlign: 'left', borderBottom: '2px solid #ddd' }}>
            <th style={{ padding: '0.5rem' }}>Name</th>
            <th>Email</th>
            <th>Role</th>
            <th>Since</th>
            {isAdmin && <th />}
          </tr>
        </thead>
        <tbody>
          {members.map((m) => (
            <tr key={m.user.id} style={{ borderBottom: '1px solid #eee' }}>
              <td style={{ padding: '0.5rem' }}>{m.user.name}</td>
              <td>{m.user.email}</td>
              <td>
                {isAdmin && m.user.id !== user.id ? (
                  <select value={m.role} onChange={(e) => changeRole(m.user.id, e.target.value)}>
                    {ROLES.map((r) => (
                      <option key={r} value={r}>
                        {r}
                      </option>
                    ))}
                  </select>
                ) : (
                  m.role
                )}
              </td>
              <td>{new Date(m.createdAt).toLocaleDateString()}</td>
              {isAdmin && (
                <td style={{ textAlign: 'right' }}>
                  {m.user.id !== user.id && <button onClick={() => remove(m.user.id)}>Remove</button>}
                </td>
              )}
            </tr>
          ))}
        </tbody>
      </table>
    </Layout>
  );
}
