<template>
  <div>
    <ToastContainer />
    <div class="p-8">
      <div class="flex justify-between items-center mb-6">
        <h1 class="text-3xl font-bold">Staff Management</h1>
        <button @click="showAddModal = true" class="bg-green-500 text-white px-6 py-3 rounded-lg hover:bg-green-600">➕ Add Cashier</button>
      </div>

      <div class="bg-white rounded-lg shadow overflow-x-auto">
        <table class="w-full">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left">Name</th>
              <th class="px-6 py-3 text-left">Email</th>
              <th class="px-6 py-3 text-left">Phone</th>
              <th class="px-6 py-3 text-left">Role</th>
              <th class="px-6 py-3 text-right">Actions</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in users" :key="user.id" class="border-t">
              <td class="px-6 py-4">{{ user.name }}</td>
              <td class="px-6 py-4">{{ user.email }}</td>
              <td class="px-6 py-4">{{ user.phone }}</td>
              <td class="px-6 py-4">
                <span class="px-2 py-1 bg-blue-100 text-blue-800 rounded text-sm">{{ user.roles?.[0]?.name || 'customer' }}</span>
              </td>
              <td class="px-6 py-4 text-right">
                <button @click="editUser(user)" class="text-blue-600 hover:text-blue-800 mr-3">Edit</button>
                <button @click="deleteUser(user.id)" class="text-red-600 hover:text-red-800">Delete</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- Add/Edit Modal -->
    <div v-if="showAddModal || showEditModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg w-full max-w-lg p-6">
        <h3 class="text-2xl font-bold mb-4">{{ showEditModal ? 'Edit' : 'Add' }} Cashier</h3>
        <div class="space-y-4">
          <input v-model="form.name" placeholder="Name" class="w-full px-4 py-2 border rounded">
          <input v-model="form.email" type="email" placeholder="Email" class="w-full px-4 py-2 border rounded">
          <input v-model="form.phone" placeholder="Phone" class="w-full px-4 py-2 border rounded">
          <input v-if="!showEditModal" v-model="form.password" type="password" placeholder="Password" class="w-full px-4 py-2 border rounded">
          <select v-model="form.role" class="w-full px-4 py-2 border rounded">
            <option value="cashier">Cashier</option>
          </select>
        </div>
        <div class="flex justify-end space-x-3 mt-6">
          <button @click="closeModal" class="px-6 py-2 border rounded">Cancel</button>
          <button @click="saveUser" class="px-6 py-2 bg-blue-500 text-white rounded">Save</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import api from '../../services/api';
import { useToast } from '../../composables/useToast';
import ToastContainer from '../../components/ToastContainer.vue';

const { success, error } = useToast();

const users = ref([]);
const showAddModal = ref(false);
const showEditModal = ref(false);
const form = ref({ name: '', email: '', phone: '', password: '', role: 'cashier' });
const editingId = ref(null);

const fetchUsers = async () => {
  try {
    const { data } = await api.get('/admin/users');
    users.value = data.data || [];
  } catch (err) {
    error('Failed to load users');
  }
};

const editUser = (user) => {
  form.value = { name: user.name, email: user.email, phone: user.phone, role: user.roles?.[0]?.name || 'customer' };
  editingId.value = user.id;
  showEditModal.value = true;
};

const saveUser = async () => {
  try {
    if (editingId.value) {
      const { data } = await api.put(`/admin/users/${editingId.value}`, form.value);
      const index = users.value.findIndex(u => u.id === editingId.value);
      if (index !== -1) users.value[index] = data.data;
      success('User updated successfully');
    } else {
      const { data } = await api.post('/admin/users', form.value);
      users.value.unshift(data.data);
      success('User created successfully');
    }
    closeModal();
  } catch (err) {
    console.error('Save error:', err.response?.data);
    error(err.response?.data?.message || 'Failed to save user');
  }
};

const deleteUser = async (id) => {
  if (confirm('Delete this user?')) {
    try {
      await api.delete(`/admin/users/${id}`);
      users.value = users.value.filter(u => u.id !== id);
      success('User deleted successfully');
    } catch (err) {
      error('Failed to delete user');
    }
  }
};

const closeModal = () => {
  showAddModal.value = false;
  showEditModal.value = false;
  form.value = { name: '', email: '', phone: '', password: '', role: 'cashier' };
  editingId.value = null;
};

onMounted(fetchUsers);
</script>
