// Equipe — PAC Advogados

const ROLE_LABELS = {
  socio_admin: 'Sócio Administrador',
  socio: 'Sócio',
  advogado: 'Advogado(a)',
  paralegal: 'Paralegal',
  cliente_externo: 'Cliente externo',
};

const TeamMemberCard = ({ member, isSelf, canEdit, onSaved }) => {
  const [editing, setEditing] = React.useState(false);
  const [form, setForm] = React.useState({
    phone: member.phone || '',
    cpf: member.cpf || '',
    oab: member.oab || '',
    address: member.address || '',
  });
  const [saving, setSaving] = React.useState(false);
  const [error, setError] = React.useState('');
  const [avatarUploading, setAvatarUploading] = React.useState(false);
  const fileInputRef = React.useRef(null);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const onSave = async () => {
    setSaving(true); setError('');
    try {
      // Próprio perfil → /profile; admin editando outro membro → /users/:id
      if (isSelf) await window.OctaleApi.users.updateProfile(form);
      else await window.OctaleApi.users.updateUser(member.id, form);
      onSaved({ ...member, ...form });
      setEditing(false);
    } catch (e) {
      setError(e.message || 'Erro ao salvar.');
    } finally {
      setSaving(false);
    }
  };

  const onCancel = () => {
    setForm({ phone: member.phone || '', cpf: member.cpf || '', oab: member.oab || '', address: member.address || '' });
    setEditing(false);
    setError('');
  };

  const onAvatarChange = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    if (!file.type.startsWith('image/')) { alert('Selecione uma imagem (JPG, PNG, etc.).'); return; }

    const reader = new FileReader();
    reader.onload = (ev) => {
      const img = new Image();
      img.onload = async () => {
        // Redimensiona para no máximo 256×256
        const MAX = 256;
        const ratio = Math.min(MAX / img.width, MAX / img.height, 1);
        const w = Math.round(img.width * ratio);
        const h = Math.round(img.height * ratio);
        const canvas = document.createElement('canvas');
        canvas.width = w; canvas.height = h;
        canvas.getContext('2d').drawImage(img, 0, 0, w, h);
        const dataUrl = canvas.toDataURL('image/jpeg', 0.88);

        setAvatarUploading(true);
        try {
          const updated = await window.OctaleApi.users.uploadAvatar(dataUrl);
          onSaved({ ...member, avatar_url: updated.avatar_url });
        } catch (err) {
          alert('Erro ao salvar foto: ' + (err.message || 'tente novamente.'));
        } finally {
          setAvatarUploading(false);
        }
      };
      img.src = ev.target.result;
    };
    reader.readAsDataURL(file);
    // Limpa o input para permitir reselecionar o mesmo arquivo
    e.target.value = '';
  };

  const onRemoveAvatar = async () => {
    if (!member.avatar_url) return;
    if (!confirm('Remover foto de perfil?')) return;
    try {
      await window.OctaleApi.users.deleteAvatar();
      onSaved({ ...member, avatar_url: null });
    } catch (err) {
      alert('Erro ao remover foto: ' + (err.message || 'tente novamente.'));
    }
  };

  const initials = member.initials || member.name?.split(' ').map(w => w[0]).join('').slice(0, 2).toUpperCase() || '?';
  const color = member.color || 'var(--octale-navy)';

  return (
    <div style={{
      background: 'var(--surface)',
      border: '1px solid var(--border)',
      borderRadius: 10,
      padding: 24,
      display: 'flex',
      flexDirection: 'column',
      gap: 14,
      position: 'relative',
    }}>
      {/* Avatar + nome */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        {/* Avatar clicável para upload — apenas o próprio usuário pode trocar */}
        <div style={{ position: 'relative', flexShrink: 0 }}>
          <input
            ref={fileInputRef}
            type="file"
            accept="image/*"
            style={{ display: 'none' }}
            onChange={onAvatarChange}
          />
          <div
            onClick={() => isSelf && !avatarUploading && fileInputRef.current?.click()}
            title={isSelf ? 'Clique para trocar a foto' : undefined}
            style={{ cursor: isSelf ? 'pointer' : 'default', position: 'relative' }}
          >
            <UserAvatar
              user={member}
              size={52}
              style={{ fontWeight: 800, fontSize: 18, letterSpacing: '-.01em', opacity: avatarUploading ? 0.5 : 1 }}
            />
            {isSelf && !avatarUploading && (
              <div style={{
                position: 'absolute', bottom: 0, right: 0,
                width: 18, height: 18, borderRadius: 999,
                background: 'var(--octale-navy)', border: '2px solid #fff',
                display: 'grid', placeItems: 'center',
              }}>
                <Icon name="pen" size={8} style={{ color: '#fff' }} />
              </div>
            )}
            {avatarUploading && (
              <div style={{
                position: 'absolute', inset: 0, borderRadius: 999,
                display: 'grid', placeItems: 'center', background: 'rgba(0,0,0,.3)',
              }}>
                <span className="spinner" style={{ width: 16, height: 16, borderColor: '#fff', borderTopColor: 'transparent' }} />
              </div>
            )}
          </div>
          {isSelf && member.avatar_url && !avatarUploading && (
            <button
              onClick={onRemoveAvatar}
              title="Remover foto"
              style={{
                position: 'absolute', top: -4, right: -4,
                width: 16, height: 16, borderRadius: 999,
                background: '#C2253E', border: '2px solid #fff',
                display: 'grid', placeItems: 'center', cursor: 'pointer',
                padding: 0,
              }}
            >
              <Icon name="x" size={7} style={{ color: '#fff' }} />
            </button>
          )}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 700, fontSize: 14, color: 'var(--octale-black)', lineHeight: 1.2, marginBottom: 3 }}>
            {member.name}
            {isSelf && (
              <span style={{ marginLeft: 8, fontSize: 10, fontWeight: 600, background: 'var(--octale-navy)', color: '#fff', borderRadius: 4, padding: '1px 6px', verticalAlign: 'middle' }}>
                Você
              </span>
            )}
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--octale-navy)', fontWeight: 600 }}>
            {ROLE_LABELS[member.role] || member.role}
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--fg-muted)', marginTop: 2, wordBreak: 'break-all' }}>
            {member.email}
          </div>
        </div>
      </div>

      {/* Campos de perfil */}
      {editing ? (
        <div style={{ display: 'grid', gap: 10 }}>
          {error && (
            <div style={{ padding: '7px 10px', background: 'rgba(194,37,62,.08)', border: '1px solid rgba(194,37,62,.2)', borderRadius: 5, color: '#C2253E', fontSize: 12 }}>
              {error}
            </div>
          )}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            <div className="field-w">
              <label>Telefone</label>
              <input value={form.phone} onChange={e => set('phone', e.target.value)} placeholder="(00) 00000-0000" />
            </div>
            <div className="field-w">
              <label>CPF</label>
              <input value={form.cpf} onChange={e => set('cpf', e.target.value)} placeholder="000.000.000-00" />
            </div>
            <div className="field-w" style={{ gridColumn: '1 / -1' }}>
              <label>OAB</label>
              <input value={form.oab} onChange={e => set('oab', e.target.value)} placeholder="OAB/SP 000.000" />
            </div>
            <div className="field-w" style={{ gridColumn: '1 / -1' }}>
              <label>Endereço</label>
              <input value={form.address} onChange={e => set('address', e.target.value)} placeholder="Rua, número, cidade" />
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
            <button className="btn ghost sm" onClick={onCancel}>Cancelar</button>
            <button className="btn sm" onClick={onSave} disabled={saving}>
              {saving ? <><span className="spinner" style={{ width: 12, height: 12, borderWidth: 2, marginRight: 6 }} />Salvando…</> : 'Salvar'}
            </button>
          </div>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {[
            { label: 'Telefone', value: member.phone },
            { label: 'CPF', value: member.cpf },
            { label: 'OAB', value: member.oab },
            { label: 'Endereço', value: member.address },
          ].map(({ label, value }) => (
            <div key={label} style={{ display: 'flex', gap: 8, fontSize: 12 }}>
              <span style={{ color: 'var(--fg-muted)', minWidth: 64, fontWeight: 600 }}>{label}</span>
              <span style={{ color: value ? 'var(--octale-black)' : 'var(--fg-muted)', fontStyle: value ? 'normal' : 'italic' }}>
                {value || 'Não informado'}
              </span>
            </div>
          ))}
          {canEdit && (
            <button
              className="btn ghost sm"
              style={{ marginTop: 6, alignSelf: 'flex-start' }}
              onClick={() => setEditing(true)}
            >
              <Icon name="edit" size={12} /> {isSelf ? 'Editar meus dados' : 'Editar dados'}
            </button>
          )}
        </div>
      )}
    </div>
  );
};

// ============================================================
// Team — view principal
// ============================================================
const Team = ({ currentUser }) => {
  const [members, setMembers] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    window.OctaleApi.users.list()
      .then(us => setMembers(us || []))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const onMemberSaved = (updated) => {
    setMembers(prev => prev.map(m => m.id === updated.id ? updated : m));
  };

  if (loading) return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: 300, gap: 12, color: 'var(--fg-muted)', fontSize: 13 }}>
      <div className="spinner" /> Carregando equipe…
    </div>
  );

  const orgName = currentUser?.organization?.name || 'Minha organização';

  return (
    <div style={{ padding: '0 2px' }}>
      <div style={{ marginBottom: 24 }}>
        <h1 style={{ fontSize: 22, fontWeight: 800, color: 'var(--octale-black)', marginBottom: 4 }}>{orgName}</h1>
        <p style={{ fontSize: 13, color: 'var(--fg-muted)' }}>
          {members.length} membro{members.length !== 1 ? 's' : ''} · Cada pessoa pode editar seus próprios dados
        </p>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: 16 }}>
        {members.map(m => (
          <TeamMemberCard
            key={m.id}
            member={m}
            isSelf={currentUser?.id === m.id}
            canEdit={currentUser?.id === m.id || currentUser?.role === 'socio_admin'}
            onSaved={onMemberSaved}
          />
        ))}
      </div>

      {members.length === 0 && (
        <div style={{ textAlign: 'center', padding: '60px 24px', color: 'var(--fg-muted)', fontSize: 13 }}>
          Nenhum membro encontrado.
        </div>
      )}
    </div>
  );
};

window.Team = Team;
