<%# app/views/usuarios/_form.html.erb %>
<div class="max-w-2xl mx-auto space-y-6">

  <div>
    <h1 class="text-2xl font-bold text-white">
      <%= usuario.new_record? ? 'Novo Usuário' : "Editar: #{usuario.name}" %>
    </h1>
    <p class="text-gray-400 text-sm mt-0.5">
      <%= usuario.new_record? ? 'Preencha os dados para criar um novo acesso' : 'Atualize as informações do usuário' %>
    </p>
  </div>

  <%= render 'shared/flash' %>

  <%= form_with(model: usuario, url: usuario.new_record? ? usuarios_path : usuario_path(usuario),
                method: usuario.new_record? ? :post : :patch,
                class: 'bg-[#1a1a1a] rounded-2xl border border-white/5 p-8 space-y-6') do |f| %>

    <% if usuario.errors.any? %>
      <div class="p-4 bg-red-900/30 border border-red-500/40 rounded-xl">
        <p class="text-red-400 text-sm font-medium mb-2">
          <%= pluralize(usuario.errors.count, 'erro', 'erros') %> encontrado<%= usuario.errors.count > 1 ? 's' : '' %>:
        </p>
        <ul class="list-disc list-inside space-y-1">
          <% usuario.errors.full_messages.each do |msg| %>
            <li class="text-red-300 text-sm"><%= msg %></li>
          <% end %>
        </ul>
      </div>
    <% end %>

    <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
      <%# Nome %>
      <div class="sm:col-span-2">
        <%= f.label :name, 'Nome completo', class: 'block text-sm font-medium text-gray-300 mb-1.5' %>
        <%= f.text_field :name,
              class: 'w-full px-4 py-3 bg-[#0a0a0a] border border-white/10 rounded-xl text-white
                      placeholder-gray-600 focus:outline-none focus:border-[#f97316] focus:ring-1
                      focus:ring-[#f97316] transition-colors',
              placeholder: 'João da Silva' %>
      </div>

      <%# Perfil %>
      <div>
        <%= f.label :role, 'Perfil de acesso', class: 'block text-sm font-medium text-gray-300 mb-1.5' %>
        <%= f.select :role,
              options_for_select(role_options_for_select, usuario.role),
              {},
              class: 'w-full px-4 py-3 bg-[#0a0a0a] border border-white/10 rounded-xl text-white
                      focus:outline-none focus:border-[#f97316] focus:ring-1 focus:ring-[#f97316]
                      transition-colors cursor-pointer' %>
      </div>

      <%# Ativo toggle %>
      <div class="flex items-center">
        <div class="flex-1">
          <%= f.label :ativo, 'Usuário ativo', class: 'block text-sm font-medium text-gray-300' %>
          <p class="text-gray-500 text-xs mt-0.5">Usuários inativos não conseguem fazer login</p>
        </div>
        <label class="relative inline-flex items-center cursor-pointer ml-4">
          <%= f.check_box :ativo, class: 'sr-only peer' %>
          <div class="w-11 h-6 bg-gray-700 peer-focus:outline-none rounded-full peer
                      peer-checked:after:translate-x-full peer-checked:after:border-white
                      after:content-[''] after:absolute after:top-[2px] after:left-[2px]
                      after:bg-white after:border-gray-300 after:border after:rounded-full
                      after:h-5 after:w-5 after:transition-all peer-checked:bg-[#f97316]"></div>
        </label>
      </div>
    </div>

    <%# E-mail e senha (não motorista) %>
    <div id="fields-email" class="space-y-6">
      <div class="border-t border-white/5 pt-6">
        <p class="text-sm font-medium text-gray-300 mb-4">Credenciais de acesso</p>
        <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
          <div class="sm:col-span-2">
            <%= f.label :email, 'E-mail', class: 'block text-sm font-medium text-gray-300 mb-1.5' %>
            <%= f.email_field :email,
                  class: 'w-full px-4 py-3 bg-[#0a0a0a] border border-white/10 rounded-xl text-white
                          placeholder-gray-600 focus:outline-none focus:border-[#f97316] focus:ring-1
                          focus:ring-[#f97316] transition-colors',
                  placeholder: 'usuario@gade.com' %>
          </div>
          <div>
            <%= f.label :password,
                  usuario.new_record? ? 'Senha' : 'Nova senha (deixe em branco para manter)',
                  class: 'block text-sm font-medium text-gray-300 mb-1.5' %>
            <%= f.password_field :password,
                  class: 'w-full px-4 py-3 bg-[#0a0a0a] border border-white/10 rounded-xl text-white
                          placeholder-gray-600 focus:outline-none focus:border-[#f97316] focus:ring-1
                          focus:ring-[#f97316] transition-colors',
                  placeholder: '••••••••' %>
          </div>
          <div>
            <%= f.label :password_confirmation, 'Confirmar senha',
                  class: 'block text-sm font-medium text-gray-300 mb-1.5' %>
            <%= f.password_field :password_confirmation,
                  class: 'w-full px-4 py-3 bg-[#0a0a0a] border border-white/10 rounded-xl text-white
                          placeholder-gray-600 focus:outline-none focus:border-[#f97316] focus:ring-1
                          focus:ring-[#f97316] transition-colors',
                  placeholder: '••••••••' %>
          </div>
        </div>
      </div>
    </div>

    <%# PIN (motorista) %>
    <div id="fields-pin" class="hidden border-t border-white/5 pt-6">
      <p class="text-sm font-medium text-gray-300 mb-4">PIN de acesso</p>
      <div class="max-w-xs">
        <%= f.label :pin_acesso, 'PIN (4 dígitos)', class: 'block text-sm font-medium text-gray-300 mb-1.5' %>
        <%= f.text_field :pin_acesso,
              maxlength: 4,
              pattern: '\d{4}',
              inputmode: 'numeric',
              class: 'w-full px-4 py-3 bg-[#0a0a0a] border border-white/10 rounded-xl text-white
                      placeholder-gray-600 focus:outline-none focus:border-[#f97316] focus:ring-1
                      focus:ring-[#f97316] transition-colors text-center text-2xl tracking-[0.5em] font-bold',
              placeholder: '0000' %>
        <p class="text-gray-500 text-xs mt-1.5">Deve ser único entre todos os motoristas</p>
      </div>
    </div>

    <%# Botões %>
    <div class="flex items-center justify-between pt-2 border-t border-white/5">
      <%= link_to 'Cancelar', usuarios_path,
            class: 'px-6 py-3 text-gray-400 hover:text-white border border-white/10
                    hover:border-white/20 rounded-xl transition-colors' %>
      <%= f.submit usuario.new_record? ? 'Criar Usuário' : 'Salvar Alterações',
            class: 'px-8 py-3 bg-[#f97316] hover:bg-orange-500 text-white font-semibold
                    rounded-xl transition-colors cursor-pointer min-h-[48px]' %>
    </div>
  <% end %>
</div>

<script>
  const roleSelect = document.querySelector('select[name="user[role]"]');
  const fieldsEmail = document.getElementById('fields-email');
  const fieldsPin   = document.getElementById('fields-pin');

  function toggleFields() {
    if (roleSelect.value === 'motorista') {
      fieldsEmail.classList.add('hidden');
      fieldsPin.classList.remove('hidden');
    } else {
      fieldsEmail.classList.remove('hidden');
      fieldsPin.classList.add('hidden');
    }
  }

  roleSelect.addEventListener('change', toggleFields);
  toggleFields(); // run on load
</script>
