<template>
  <div class="delivery-boy-management">
    <!-- Page Header -->
    <div class="page-header">
      <div>
        <h1>🚴 Delivery Boy Management</h1>
        <p class="subtitle">Manage all delivery boys in the system</p>
      </div>
      <button @click="openAddModal" class="btn-primary">
        <span>➕</span>
        <span>Add Delivery Boy</span>
      </button>
    </div>

    <!-- Filters -->
    <div class="filters-section">
      <div class="search-box">
        <span class="search-icon">🔍</span>
        <input v-model="search" placeholder="Search by name, phone..." class="search-input">
      </div>
      <select v-model="statusFilter" class="filter-select">
        <option value="">All Status</option>
        <option value="online">Online</option>
        <option value="offline">Offline</option>
        <option value="on_delivery">On Delivery</option>
        <option value="blocked">Blocked</option>
      </select>
    </div>

    <!-- Loading -->
    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      <p>Loading delivery boys...</p>
    </div>

    <!-- Table -->
    <div v-else class="table-container">
      <table class="data-table">
        <thead>
          <tr>
            <th>Profile</th>
            <th>Name</th>
            <th>Phone</th>
            <th>Vehicle</th>
            <th>Area</th>
            <th>Status</th>
            <th>Rating</th>
            <th>Deliveries</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="boy in filteredDeliveryBoys" :key="boy.id">
            <td>
              <div class="profile-img">{{ boy.full_name.charAt(0) }}</div>
            </td>
            <td class="name-cell">{{ boy.full_name }}</td>
            <td>{{ boy.phone }}</td>
            <td>
              <span v-if="boy.vehicles && boy.vehicles.length > 0" class="vehicle-badge">
                {{ getVehicleIcon(boy.vehicles[0].vehicle_type) }} {{ boy.vehicles[0].vehicle_type }}
              </span>
              <span v-else class="vehicle-badge empty">No Vehicle</span>
            </td>
            <td>{{ boy.city || (boy.areas && boy.areas.length > 0 ? boy.areas[0].city : 'N/A') }}</td>
            <td>
              <span :class="['status-badge', boy.status]">
                {{ getStatusText(boy.status) }}
              </span>
            </td>
            <td>
              <span class="rating">⭐ {{ parseFloat(boy.rating || 0).toFixed(1) }}</span>
            </td>
            <td>{{ parseInt(boy.total_deliveries || 0) }}</td>
            <td>
              <div class="action-buttons">
                <button @click="editDeliveryBoy(boy)" class="btn-icon" title="Edit">✏️</button>
                <button @click="deleteDeliveryBoy(boy)" class="btn-icon delete" title="Delete">🗑️</button>
                <button @click="toggleBlock(boy)" class="btn-icon" :class="boy.status === 'blocked' ? 'unblock' : 'block'">
                  {{ boy.status === 'blocked' ? '✅' : '🚫' }}
                </button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>

      <!-- Empty State -->
      <div v-if="filteredDeliveryBoys.length === 0" class="empty-state">
        <span class="empty-icon">🚴</span>
        <h3>No delivery boys found</h3>
        <p>Try adjusting your filters or add a new delivery boy</p>
      </div>
    </div>

    <!-- Add/Edit Modal -->
    <div v-if="showModal" class="modal-overlay" @click="closeModal">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h2>{{ editMode ? '✏️ Edit Delivery Boy' : '➕ Add Delivery Boy' }}</h2>
          <button @click="closeModal" class="close-btn">✕</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveDeliveryBoy">
            <!-- Personal Info -->
            <div class="form-section">
              <h3>👤 Personal Information</h3>
              <div class="form-group">
                <label>Full Name *</label>
                <input v-model="form.full_name" required class="form-input" placeholder="Enter full name">
              </div>
              <div class="form-row">
                <div class="form-group">
                  <label>Phone *</label>
                  <input v-model="form.phone" required class="form-input" placeholder="0771234567">
                </div>
                <div class="form-group">
                  <label>Email *</label>
                  <input v-model="form.email" required type="email" class="form-input" placeholder="email@example.com">
                </div>
              </div>
              <div class="form-group" v-if="!editMode">
                <label>Password *</label>
                <input v-model="form.password" :required="!editMode" type="password" class="form-input" placeholder="Min 8 characters">
              </div>
              <div class="form-row">
                <div class="form-group">
                  <label>City</label>
                  <input v-model="form.city" class="form-input" placeholder="City">
                </div>
                <div class="form-group">
                  <label>Address</label>
                  <input v-model="form.address" class="form-input" placeholder="Address">
                </div>
              </div>
            </div>

            <!-- Vehicle Info -->
            <div class="form-section">
              <h3>🏍️ Vehicle Information</h3>
              <div class="form-row">
                <div class="form-group">
                  <label>Vehicle Type</label>
                  <select v-model="form.vehicle_type" class="form-input">
                    <option value="">Select Vehicle</option>
                    <option value="bike">🏍️ Bike</option>
                    <option value="scooter">🛵 Scooter</option>
                    <option value="bicycle">🚲 Bicycle</option>
                    <option value="car">🚗 Car</option>
                  </select>
                </div>
                <div class="form-group">
                  <label>Vehicle Number</label>
                  <input v-model="form.vehicle_number" class="form-input" placeholder="ABC-1234">
                </div>
              </div>
              <div class="form-row">
                <div class="form-group">
                  <label>Vehicle Model</label>
                  <input v-model="form.vehicle_model" class="form-input" placeholder="Honda CB 150">
                </div>
                <div class="form-group">
                  <label>Vehicle Color</label>
                  <input v-model="form.vehicle_color" class="form-input" placeholder="Red">
                </div>
              </div>
            </div>

            <!-- Commission -->
            <div class="form-section">
              <h3>💰 Commission Settings</h3>
              <div class="form-group">
                <label>Commission Rate (%)</label>
                <input v-model="form.commission_rate" type="number" step="0.01" class="form-input" placeholder="15">
              </div>
            </div>

            <div class="form-actions">
              <button type="button" @click="closeModal" class="btn-cancel">Cancel</button>
              <button type="submit" class="btn-submit">{{ editMode ? 'Update' : 'Create' }}</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import api from '@/services/api'

export default {
  setup() {
    const deliveryBoys = ref([])
    const loading = ref(true)
    const search = ref('')
    const statusFilter = ref('')
    const showModal = ref(false)
    const editMode = ref(false)
    const editingId = ref(null)
    const form = ref({
      full_name: '',
      phone: '',
      email: '',
      password: '',
      city: '',
      address: '',
      vehicle_type: '',
      vehicle_number: '',
      vehicle_model: '',
      vehicle_color: '',
      commission_rate: 15
    })

    const filteredDeliveryBoys = computed(() => {
      let result = deliveryBoys.value

      if (search.value) {
        result = result.filter(b => 
          b.full_name.toLowerCase().includes(search.value.toLowerCase()) ||
          b.phone.includes(search.value)
        )
      }

      if (statusFilter.value) {
        result = result.filter(b => b.status === statusFilter.value)
      }

      return result
    })

    const loadDeliveryBoys = async () => {
      loading.value = true
      try {
        const { data } = await api.get('/super-admin/delivery-boys')
        deliveryBoys.value = (data.data.data || []).map(boy => ({
          ...boy,
          rating: boy.rating || 0,
          total_deliveries: boy.total_deliveries || 0,
          city: boy.city || null,
          address: boy.address || null
        }))
      } catch (error) {
        console.error('Failed to load:', error)
      } finally {
        loading.value = false
      }
    }

    const openAddModal = () => {
      editMode.value = false
      editingId.value = null
      form.value = {
        full_name: '',
        phone: '',
        email: '',
        password: '',
        city: '',
        address: '',
        vehicle_type: '',
        vehicle_number: '',
        vehicle_model: '',
        vehicle_color: '',
        commission_rate: 15
      }
      showModal.value = true
    }

    const saveDeliveryBoy = async () => {
      try {
        const payload = {
          full_name: form.value.full_name,
          phone: form.value.phone,
          email: form.value.email,
          city: form.value.city || null,
          address: form.value.address || null,
          commission_rate: parseFloat(form.value.commission_rate) || 15
        }

        if (!editMode.value) {
          payload.password = form.value.password
        }

        let deliveryBoyId = editingId.value

        if (editMode.value) {
          await api.put(`/super-admin/delivery-boys/${editingId.value}`, payload)
          
          // Update vehicle if exists
          const boy = deliveryBoys.value.find(b => b.id === editingId.value)
          if (form.value.vehicle_type) {
            if (boy.vehicles && boy.vehicles.length > 0) {
              await api.put(`/super-admin/delivery-boys/${editingId.value}/vehicles/${boy.vehicles[0].id}`, {
                vehicle_type: form.value.vehicle_type,
                vehicle_number: form.value.vehicle_number,
                vehicle_model: form.value.vehicle_model,
                vehicle_color: form.value.vehicle_color
              })
            } else {
              await api.post(`/super-admin/delivery-boys/${editingId.value}/vehicles`, {
                vehicle_type: form.value.vehicle_type,
                vehicle_number: form.value.vehicle_number,
                vehicle_model: form.value.vehicle_model,
                vehicle_color: form.value.vehicle_color
              })
            }
          }
          
          alert('✅ Updated successfully!')
        } else {
          const { data } = await api.post('/super-admin/delivery-boys', payload)
          deliveryBoyId = data.data.id
          
          // Add vehicle if provided
          if (form.value.vehicle_type && deliveryBoyId) {
            await api.post(`/super-admin/delivery-boys/${deliveryBoyId}/vehicles`, {
              vehicle_type: form.value.vehicle_type,
              vehicle_number: form.value.vehicle_number,
              vehicle_model: form.value.vehicle_model,
              vehicle_color: form.value.vehicle_color
            })
          }
          
          alert('✅ Created successfully!')
        }

        closeModal()
        await loadDeliveryBoys()
      } catch (error) {
        console.error('Failed to save:', error)
        alert('❌ ' + (error.response?.data?.message || 'Failed to save'))
      }
    }

    const editDeliveryBoy = (boy) => {
      editMode.value = true
      editingId.value = boy.id
      form.value = {
        full_name: boy.full_name || '',
        phone: boy.phone || '',
        email: boy.email || '',
        password: '',
        city: boy.city || (boy.areas?.[0]?.city || ''),
        address: boy.address || '',
        vehicle_type: boy.vehicles?.[0]?.vehicle_type || '',
        vehicle_number: boy.vehicles?.[0]?.vehicle_number || '',
        vehicle_model: boy.vehicles?.[0]?.vehicle_model || '',
        vehicle_color: boy.vehicles?.[0]?.vehicle_color || '',
        commission_rate: parseFloat(boy.commission_rate || 15)
      }
      showModal.value = true
    }

    const deleteDeliveryBoy = async (boy) => {
      if (confirm(`Delete ${boy.full_name}?`)) {
        try {
          await api.delete(`/super-admin/delivery-boys/${boy.id}`)
          alert('✅ Deleted successfully!')
          await loadDeliveryBoys()
        } catch (error) {
          alert('❌ Failed to delete')
        }
      }
    }

    const toggleBlock = async (boy) => {
      try {
        await api.post(`/super-admin/delivery-boys/${boy.id}/block`)
        boy.status = boy.status === 'blocked' ? 'offline' : 'blocked'
        alert('✅ Status updated!')
      } catch (error) {
        alert('❌ Failed to update')
      }
    }

    const closeModal = () => {
      showModal.value = false
      editMode.value = false
      editingId.value = null
    }

    const getStatusText = (status) => {
      const texts = {
        online: '🟢 Online',
        offline: '⚫ Offline',
        on_delivery: '🔵 On Delivery',
        blocked: '🔴 Blocked'
      }
      return texts[status] || status
    }

    const getVehicleIcon = (type) => {
      const icons = {
        bike: '🏍️',
        scooter: '🛵',
        bicycle: '🚲',
        car: '🚗'
      }
      return icons[type] || '🚗'
    }

    onMounted(loadDeliveryBoys)

    return {
      deliveryBoys,
      loading,
      search,
      statusFilter,
      showModal,
      editMode,
      form,
      filteredDeliveryBoys,
      openAddModal,
      saveDeliveryBoy,
      editDeliveryBoy,
      deleteDeliveryBoy,
      toggleBlock,
      closeModal,
      getStatusText,
      getVehicleIcon
    }
  }
}
</script>

<style scoped>
.delivery-boy-management { padding: 0; }

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 2rem;
}

.page-header h1 { margin: 0; font-size: 2rem; font-weight: 700; color: #1f2937; }
.subtitle { margin: 0.5rem 0 0; color: #6b7280; font-size: 1rem; }

.btn-primary {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1.5rem;
  background: linear-gradient(135deg, #ff6b35, #f7931e);
  color: white;
  border: none;
  border-radius: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-primary:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(255,107,53,0.3); }

.filters-section {
  display: flex;
  gap: 1rem;
  margin-bottom: 2rem;
  flex-wrap: wrap;
}

.search-box {
  flex: 1;
  min-width: 250px;
  position: relative;
  display: flex;
  align-items: center;
}

.search-icon { position: absolute; left: 1rem; font-size: 1.25rem; }
.search-input { flex: 1; padding: 0.75rem 1rem 0.75rem 3rem; border: 1px solid #e5e7eb; border-radius: 12px; font-size: 0.875rem; }
.filter-select { padding: 0.75rem 1rem; border: 1px solid #e5e7eb; border-radius: 12px; font-size: 0.875rem; cursor: pointer; }

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 4rem;
}

.spinner {
  width: 50px;
  height: 50px;
  border: 4px solid #e5e7eb;
  border-top-color: #ff6b35;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin { to { transform: rotate(360deg); } }

.table-container {
  background: white;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  overflow: hidden;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table thead {
  background: #f9fafb;
  border-bottom: 2px solid #e5e7eb;
}

.data-table th {
  padding: 1rem;
  text-align: left;
  font-size: 0.875rem;
  font-weight: 600;
  color: #374151;
}

.data-table td {
  padding: 1rem;
  border-bottom: 1px solid #f3f4f6;
  font-size: 0.875rem;
  color: #1f2937;
}

.data-table tbody tr:hover { background: #f9fafb; }

.profile-img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, #ff6b35, #f7931e);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  font-size: 1rem;
}

.name-cell { font-weight: 600; }

.vehicle-badge {
  display: inline-block;
  padding: 0.25rem 0.75rem;
  background: #e0e7ff;
  color: #4f46e5;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 600;
}

.vehicle-badge.empty { background: #f3f4f6; color: #6b7280; }

.status-badge {
  display: inline-block;
  padding: 0.25rem 0.75rem;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 600;
}

.status-badge.online { background: #d1fae5; color: #10b981; }
.status-badge.offline { background: #f3f4f6; color: #6b7280; }
.status-badge.on_delivery { background: #dbeafe; color: #3b82f6; }
.status-badge.blocked { background: #fee2e2; color: #ef4444; }

.rating { color: #f59e0b; font-weight: 600; }

.action-buttons { display: flex; gap: 0.5rem; }

.btn-icon {
  padding: 0.5rem;
  background: none;
  border: none;
  font-size: 1.25rem;
  cursor: pointer;
  border-radius: 8px;
  transition: background 0.3s;
}

.btn-icon:hover { background: #f3f4f6; }
.btn-icon.delete:hover { background: #fee2e2; }
.btn-icon.block:hover { background: #fee2e2; }
.btn-icon.unblock:hover { background: #d1fae5; }

.empty-state {
  text-align: center;
  padding: 4rem;
}

.empty-icon { font-size: 4rem; display: block; margin-bottom: 1rem; }
.empty-state h3 { margin: 0 0 0.5rem; color: #1f2937; }
.empty-state p { margin: 0; color: #6b7280; }

.modal-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0,0,0,0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(4px);
}

.modal {
  background: white;
  border-radius: 16px;
  width: 90%;
  max-width: 700px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid #e5e7eb;
}

.modal-header h2 { margin: 0; font-size: 1.25rem; }
.close-btn { background: #f3f4f6; border: none; width: 32px; height: 32px; border-radius: 8px; cursor: pointer; font-size: 1.25rem; }

.modal-body { padding: 1.5rem; }

.form-section {
  margin-bottom: 2rem;
  padding-bottom: 2rem;
  border-bottom: 1px solid #e5e7eb;
}

.form-section:last-of-type { border-bottom: none; }

.form-section h3 {
  margin: 0 0 1rem;
  font-size: 1rem;
  font-weight: 600;
  color: #374151;
}

.form-group { margin-bottom: 1rem; }
.form-group label { display: block; margin-bottom: 0.5rem; font-weight: 600; color: #374151; font-size: 0.875rem; }
.form-input { width: 100%; padding: 0.75rem; border: 1px solid #e5e7eb; border-radius: 8px; font-size: 0.875rem; }
.form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }

.form-actions { display: flex; gap: 1rem; margin-top: 1.5rem; }
.btn-cancel { flex: 1; padding: 0.75rem; background: #f3f4f6; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; }
.btn-submit { flex: 1; padding: 0.75rem; background: linear-gradient(135deg, #ff6b35, #f7931e); color: white; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; }

@media (max-width: 768px) {
  .data-table { display: block; overflow-x: auto; }
  .form-row { grid-template-columns: 1fr; }
}
</style>
