<template>
  <div class="restaurant-management">
    <header class="page-header">
      <div>
        <h1>🏪 Restaurant Management</h1>
        <p class="subtitle">Manage all restaurants in the system</p>
      </div>
      <button @click="showCreateModal = true" class="btn-primary">
        <span>➕</span>
        <span>Add Restaurant</span>
      </button>
    </header>

    <!-- Stats -->
    <div class="stats-row">
      <div class="stat-box">
        <span class="stat-icon">🏪</span>
        <div>
          <p class="stat-label">Total Restaurants</p>
          <h3>{{ restaurants.length }}</h3>
        </div>
      </div>
      <div class="stat-box">
        <span class="stat-icon">✅</span>
        <div>
          <p class="stat-label">Active</p>
          <h3>{{ activeCount }}</h3>
        </div>
      </div>
      <div class="stat-box">
        <span class="stat-icon">⏳</span>
        <div>
          <p class="stat-label">Pending</p>
          <h3>{{ pendingCount }}</h3>
        </div>
      </div>
      <div class="stat-box">
        <span class="stat-icon">🚫</span>
        <div>
          <p class="stat-label">Suspended</p>
          <h3>{{ suspendedCount }}</h3>
        </div>
      </div>
    </div>

    <!-- Payment Stats -->
    <div class="payment-stats">
      <h2>💰 Payment Overview</h2>
      <div class="stats-row">
        <div class="stat-box payment-stat">
          <span class="stat-icon">💵</span>
          <div>
            <p class="stat-label">Total Monthly Revenue</p>
            <h3>${{ formatNumber(totalMonthlyRevenue) }}</h3>
          </div>
        </div>
        <div class="stat-box payment-stat">
          <span class="stat-icon">✅</span>
          <div>
            <p class="stat-label">Paid This Month</p>
            <h3>{{ paidThisMonth }}</h3>
          </div>
        </div>
        <div class="stat-box payment-stat">
          <span class="stat-icon">⚠️</span>
          <div>
            <p class="stat-label">Overdue Payments</p>
            <h3>{{ overdueCount }}</h3>
          </div>
        </div>
        <div class="stat-box payment-stat">
          <span class="stat-icon">📈</span>
          <div>
            <p class="stat-label">Avg Commission Rate</p>
            <h3>{{ avgCommissionRate }}%</h3>
          </div>
        </div>
      </div>
    </div>

    <!-- Filters -->
    <div class="filters">
      <div class="search-box">
        <span class="search-icon">🔍</span>
        <input v-model="search" placeholder="Search restaurants..." class="search-input">
      </div>
      <select v-model="statusFilter" class="filter-select">
        <option value="all">All Status</option>
        <option value="active">Active</option>
        <option value="pending">Pending Approval</option>
        <option value="suspended">Suspended</option>
      </select>
      <select v-model="sortBy" class="filter-select">
        <option value="name">Sort by Name</option>
        <option value="created">Newest First</option>
        <option value="orders">Most Orders</option>
      </select>
    </div>

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

    <!-- Restaurant Grid -->
    <div v-else class="restaurant-grid">
      <div v-for="restaurant in filteredRestaurants" :key="restaurant.id" class="restaurant-card">
        <div class="card-header">
          <div class="restaurant-avatar">{{ restaurant.name.charAt(0) }}</div>
          <div class="restaurant-info">
            <h3>{{ restaurant.name }}</h3>
            <p>{{ restaurant.address }}</p>
          </div>
          <select @change="changeStatus(restaurant, $event)" @click.stop :value="restaurant.status" class="status-dropdown">
            <option value="approved">✅ Approved</option>
            <option value="pending">⏳ Pending</option>
            <option value="suspended">🚫 Suspended</option>
            <option value="rejected">❌ Rejected</option>
          </select>
        </div>

        <div class="card-body">
          <div class="info-row">
            <span class="label">📞 Phone:</span>
            <span>{{ restaurant.phone || 'N/A' }}</span>
          </div>
          <div class="info-row">
            <span class="label">📧 Email:</span>
            <span>{{ restaurant.email || 'N/A' }}</span>
          </div>
          <div class="info-row">
            <span class="label">⭐ Rating:</span>
            <span>{{ restaurant.rating || '0.0' }} / 5.0</span>
          </div>
          <div class="info-row">
            <span class="label">📦 Orders:</span>
            <span>{{ restaurant.orders_count || 0 }}</span>
          </div>
        </div>

        <div class="card-actions">
          <button @click="viewDetails(restaurant)" class="btn-view" title="View Details">
            👁️ View
          </button>
          <button @click="editRestaurant(restaurant)" class="btn-edit" title="Edit">
            ✏️ Edit
          </button>
          <button @click="deleteRestaurant(restaurant)" class="btn-delete" title="Delete">
            🗑️
          </button>
        </div>
      </div>
    </div>

    <!-- Empty State -->
    <div v-if="!loading && filteredRestaurants.length === 0" class="empty-state">
      <span class="empty-icon">🏪</span>
      <h3>No restaurants found</h3>
      <p>Try adjusting your filters or add a new restaurant</p>
    </div>

    <!-- View Details Modal -->
    <div v-if="showDetailsModal" class="modal-overlay" @click="showDetailsModal = false">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h2>🏪 Restaurant Details</h2>
          <button @click="showDetailsModal = false" class="close-btn">✕</button>
        </div>
        <div class="modal-body">
          <div class="detail-section">
            <h3>📍 Location & Map</h3>
            <div class="detail-grid">
              <div class="detail-item full-width">
                <span class="detail-label">Address:</span>
                <span>{{ selectedRestaurant.address }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">Latitude:</span>
                <span>{{ selectedRestaurant.latitude || 'N/A' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">Longitude:</span>
                <span>{{ selectedRestaurant.longitude || 'N/A' }}</span>
              </div>
            </div>
            <div class="map-container">
              <iframe 
                v-if="selectedRestaurant.latitude && selectedRestaurant.longitude"
                :src="`https://maps.google.com/maps?q=${selectedRestaurant.latitude},${selectedRestaurant.longitude}&z=15&output=embed`"
                width="100%" 
                height="250" 
                frameborder="0" 
                style="border:0; border-radius: 8px;"
              ></iframe>
              <div v-else class="map-placeholder">
                <span>🗺️</span>
                <p>No location data available</p>
              </div>
            </div>
          </div>

          <div class="detail-section">
            <h3>🏪 Restaurant Information</h3>
            <div class="detail-grid">
              <div class="detail-item">
                <span class="detail-label">Name:</span>
                <span>{{ selectedRestaurant.name }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">Phone:</span>
                <span>{{ selectedRestaurant.phone || 'N/A' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">Email:</span>
                <span>{{ selectedRestaurant.email || 'N/A' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">Status:</span>
                <span :class="['status-badge', getStatusClass(selectedRestaurant)]">
                  {{ getStatusText(selectedRestaurant) }}
                </span>
              </div>
            </div>
          </div>

          <div class="detail-section">
            <h3>👤 Owner Details</h3>
            <div class="detail-grid">
              <div class="detail-item">
                <span class="detail-label">Owner Name:</span>
                <span>{{ selectedRestaurant.owner?.name || 'N/A' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">Owner Email:</span>
                <span>{{ selectedRestaurant.owner?.email || 'N/A' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">Owner Phone:</span>
                <span>{{ selectedRestaurant.owner?.phone || 'N/A' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">Login Status:</span>
                <span :class="selectedRestaurant.owner ? 'text-success' : 'text-warning'">
                  {{ selectedRestaurant.owner ? '✅ Active' : '⚠️ Not Created' }}
                </span>
              </div>
            </div>
            <button v-if="!selectedRestaurant.owner" @click="createOwnerLogin(selectedRestaurant)" class="btn-create-login">
              🔑 Create Owner Login
            </button>
          </div>

          <div class="detail-section">
            <h3>💰 Subscription & Fees</h3>
            <div class="detail-grid">
              <div class="detail-item">
                <span class="detail-label">Monthly Fee:</span>
                <span class="fee-amount">${{ selectedRestaurant.monthly_fee || '0.00' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">Commission Rate:</span>
                <span>{{ selectedRestaurant.commission_rate || '0' }}%</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">Payment Status:</span>
                <span :class="getPaymentStatusClass(selectedRestaurant)">
                  {{ getPaymentStatus(selectedRestaurant) }}
                </span>
              </div>
              <div class="detail-item">
                <span class="detail-label">Next Payment:</span>
                <span>{{ formatDate(selectedRestaurant.next_payment_date) || 'N/A' }}</span>
              </div>
            </div>
            <div class="fee-actions">
              <button @click="updateMonthlyFee(selectedRestaurant)" class="btn-update-fee">
                💳 Update Monthly Fee
              </button>
              <button @click="recordPayment(selectedRestaurant)" class="btn-record-payment">
                ✅ Record Payment
              </button>
            </div>
          </div>

          <div class="detail-section">
            <h3>📊 Performance</h3>
            <div class="detail-grid">
              <div class="detail-item">
                <span class="detail-label">Rating:</span>
                <span>⭐ {{ selectedRestaurant.rating || '0.0' }} / 5.0</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">Total Orders:</span>
                <span>{{ selectedRestaurant.orders_count || 0 }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">Total Revenue:</span>
                <span>${{ formatNumber(selectedRestaurant.total_revenue || 0) }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">Joined:</span>
                <span>{{ formatDate(selectedRestaurant.created_at) }}</span>
              </div>
            </div>
          </div>

          <div class="detail-section">
            <h3>💳 Payment History</h3>
            <div class="payment-history">
              <div v-for="payment in selectedRestaurant.payments" :key="payment.id" class="payment-item">
                <div class="payment-info">
                  <span class="payment-date">{{ formatDate(payment.payment_date) }}</span>
                  <span class="payment-amount">${{ payment.amount }}</span>
                </div>
                <span :class="['payment-status', payment.status]">
                  {{ payment.status }}
                </span>
              </div>
              <div v-if="!selectedRestaurant.payments || selectedRestaurant.payments.length === 0" class="no-payments">
                <span>📝</span>
                <p>No payment history</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Payment Recording Modal -->
    <div v-if="showPaymentModal" class="modal-overlay" @click="showPaymentModal = false">
      <div class="modal payment-modal" @click.stop>
        <div class="modal-header">
          <h2>💰 Record Payment</h2>
          <button @click="showPaymentModal = false" class="close-btn">✕</button>
        </div>
        <div class="modal-body">
          <div class="restaurant-info-banner">
            <div class="restaurant-avatar">{{ selectedRestaurant.name?.charAt(0) }}</div>
            <div>
              <h3>{{ selectedRestaurant.name }}</h3>
              <p>Monthly Fee: ${{ selectedRestaurant.monthly_fee || '0.00' }}</p>
            </div>
          </div>

          <form @submit.prevent="submitPayment">
            <div class="form-group">
              <label>💵 Payment Amount *</label>
              <input v-model="paymentForm.amount" type="number" step="0.01" required class="form-input" placeholder="Enter amount">
            </div>

            <div class="form-group">
              <label>📅 Payment Date *</label>
              <input v-model="paymentForm.payment_date" type="date" required class="form-input">
            </div>

            <div class="form-group">
              <label>💳 Payment Method *</label>
              <select v-model="paymentForm.payment_method" required class="form-input">
                <option value="cash">💵 Cash</option>
                <option value="bank_transfer">🏦 Bank Transfer</option>
                <option value="card">💳 Card Payment</option>
                <option value="other">📝 Other</option>
              </select>
            </div>

            <div class="form-group">
              <label>🔢 Transaction ID (Optional)</label>
              <input v-model="paymentForm.transaction_id" class="form-input" placeholder="e.g., TXN123456">
              <p class="form-hint">Enter bank reference or transaction number</p>
            </div>

            <div class="form-group">
              <label>📝 Notes (Optional)</label>
              <textarea v-model="paymentForm.notes" class="form-textarea" rows="3" placeholder="Additional notes about this payment"></textarea>
            </div>

            <div class="payment-summary">
              <div class="summary-row">
                <span>Amount:</span>
                <strong>${{ paymentForm.amount || '0.00' }}</strong>
              </div>
              <div class="summary-row">
                <span>Method:</span>
                <strong>{{ paymentForm.payment_method }}</strong>
              </div>
              <div class="summary-row">
                <span>Date:</span>
                <strong>{{ paymentForm.payment_date }}</strong>
              </div>
            </div>

            <div class="form-actions">
              <button type="button" @click="showPaymentModal = false" class="btn-cancel">Cancel</button>
              <button type="submit" class="btn-submit">✅ Record Payment</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- Create/Edit Modal -->
    <div v-if="showCreateModal || showEditModal" class="modal-overlay" @click="closeModal">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h2>{{ showEditModal ? '✏️ Edit Restaurant' : '➕ Add Restaurant' }}</h2>
          <button @click="closeModal" class="close-btn">✕</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveRestaurant">
            <div class="form-section">
              <h3>🏪 Restaurant Information</h3>
              <div class="form-group">
                <label>Restaurant Name *</label>
                <input v-model="form.name" required class="form-input" placeholder="Enter restaurant name">
              </div>
              <div class="form-group">
                <label>Description</label>
                <textarea v-model="form.description" class="form-textarea" rows="3" placeholder="Restaurant description"></textarea>
              </div>
              <div class="form-row">
                <div class="form-group">
                  <label>Phone *</label>
                  <input v-model="form.phone" required class="form-input" placeholder="Phone number">
                </div>
                <div class="form-group">
                  <label>Email *</label>
                  <input v-model="form.email" required type="email" class="form-input" placeholder="Email address">
                </div>
              </div>
            </div>

            <div class="form-section">
              <h3>📍 Location Details</h3>
              <div class="form-group">
                <label>Address *</label>
                <input v-model="form.address" required class="form-input" placeholder="Full address">
              </div>
              <div class="form-row">
                <div class="form-group">
                  <label>Latitude</label>
                  <input v-model="form.latitude" type="number" step="any" class="form-input" placeholder="e.g., 6.9271">
                </div>
                <div class="form-group">
                  <label>Longitude</label>
                  <input v-model="form.longitude" type="number" step="any" class="form-input" placeholder="e.g., 79.8612">
                </div>
              </div>
              <p class="form-hint">💡 Tip: Use Google Maps to get coordinates</p>
            </div>

            <div class="form-section">
              <h3>💰 Subscription & Fees</h3>
              <div class="form-row">
                <div class="form-group">
                  <label>Monthly Fee ($)</label>
                  <input v-model="form.monthly_fee" type="number" step="0.01" class="form-input" placeholder="e.g., 99.99">
                </div>
                <div class="form-group">
                  <label>Commission Rate (%)</label>
                  <input v-model="form.commission_rate" type="number" step="0.01" class="form-input" placeholder="e.g., 15">
                </div>
              </div>
              <p class="form-hint">💳 Monthly fee will be charged automatically</p>
            </div>

            <div v-if="!showEditModal" class="form-section">
              <h3>👤 Owner Account (Optional)</h3>
              <div class="form-checkbox">
                <input type="checkbox" id="createOwner" v-model="createOwner">
                <label for="createOwner">Create owner login account</label>
              </div>
              <div v-if="createOwner" class="owner-fields">
                <div class="form-group">
                  <label>Owner Name *</label>
                  <input v-model="form.owner_name" :required="createOwner" class="form-input" placeholder="Owner full name">
                </div>
                <div class="form-group">
                  <label>Owner Email *</label>
                  <input v-model="form.owner_email" :required="createOwner" type="email" class="form-input" placeholder="Owner email for login">
                </div>
                <div class="form-group">
                  <label>Owner Phone</label>
                  <input v-model="form.owner_phone" class="form-input" placeholder="Owner phone number">
                </div>
                <div class="form-group">
                  <label>Password *</label>
                  <input v-model="form.owner_password" :required="createOwner" type="password" class="form-input" placeholder="Minimum 8 characters">
                </div>
                <div class="alert-info">
                  📝 Owner will receive login credentials via email
                </div>
              </div>
            </div>

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

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

export default {
  setup() {
    const restaurants = ref([])
    const loading = ref(true)
    const search = ref('')
    const statusFilter = ref('all')
    const sortBy = ref('name')
    const showDetailsModal = ref(false)
    const showCreateModal = ref(false)
    const showEditModal = ref(false)
    const showPaymentModal = ref(false)
    const selectedRestaurant = ref({})
    const createOwner = ref(false)
    const paymentForm = ref({
      amount: '',
      payment_date: new Date().toISOString().split('T')[0],
      payment_method: 'cash',
      transaction_id: '',
      notes: ''
    })
    const form = ref({ 
      name: '', address: '', phone: '', email: '', description: '',
      latitude: '', longitude: '',
      monthly_fee: '', commission_rate: '',
      owner_name: '', owner_email: '', owner_phone: '', owner_password: ''
    })

    const activeCount = computed(() => restaurants.value.filter(r => r.status === 'approved').length)
    const pendingCount = computed(() => restaurants.value.filter(r => r.status === 'pending').length)
    const suspendedCount = computed(() => restaurants.value.filter(r => r.status === 'suspended').length)

    // Payment stats
    const totalMonthlyRevenue = computed(() => {
      return restaurants.value.reduce((sum, r) => sum + (parseFloat(r.monthly_fee) || 0), 0)
    })

    const paidThisMonth = computed(() => {
      const today = new Date()
      return restaurants.value.filter(r => {
        if (!r.last_payment_date) return false
        const lastPayment = new Date(r.last_payment_date)
        return lastPayment.getMonth() === today.getMonth() && lastPayment.getFullYear() === today.getFullYear()
      }).length
    })

    const overdueCount = computed(() => {
      return restaurants.value.filter(r => r.payment_status === 'overdue').length
    })

    const avgCommissionRate = computed(() => {
      const total = restaurants.value.reduce((sum, r) => sum + (parseFloat(r.commission_rate) || 0), 0)
      return restaurants.value.length > 0 ? (total / restaurants.value.length).toFixed(2) : 0
    })

    const filteredRestaurants = computed(() => {
      let result = restaurants.value

      if (search.value) {
        result = result.filter(r => 
          r.name.toLowerCase().includes(search.value.toLowerCase()) ||
          r.address.toLowerCase().includes(search.value.toLowerCase())
        )
      }

      if (statusFilter.value === 'active') result = result.filter(r => r.status === 'approved')
      if (statusFilter.value === 'pending') result = result.filter(r => r.status === 'pending')
      if (statusFilter.value === 'suspended') result = result.filter(r => r.status === 'suspended')

      if (sortBy.value === 'name') result.sort((a, b) => a.name.localeCompare(b.name))
      if (sortBy.value === 'created') result.sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
      if (sortBy.value === 'orders') result.sort((a, b) => (b.orders_count || 0) - (a.orders_count || 0))

      return result
    })

    const loadRestaurants = async () => {
      try {
        const { data } = await api.get('/admin/restaurants')
        restaurants.value = data.data
      } finally {
        loading.value = false
      }
    }

    const viewDetails = async (restaurant) => {
      selectedRestaurant.value = restaurant
      
      // Load payment history
      try {
        const { data } = await api.get(`/admin/restaurants/${restaurant.id}/payment-history`)
        selectedRestaurant.value.payments = data.data
      } catch (error) {
        console.error('Failed to load payment history:', error)
        selectedRestaurant.value.payments = []
      }
      
      showDetailsModal.value = true
    }

    const editRestaurant = (restaurant) => {
      form.value = {
        id: restaurant.id,
        name: restaurant.name,
        address: restaurant.address,
        phone: restaurant.phone,
        email: restaurant.email,
        description: restaurant.description,
        latitude: restaurant.latitude,
        longitude: restaurant.longitude,
        monthly_fee: restaurant.monthly_fee,
        commission_rate: restaurant.commission_rate
      }
      showEditModal.value = true
    }

    const saveRestaurant = async () => {
      try {
        loading.value = true
        
        const payload = {
          name: form.value.name,
          address: form.value.address,
          phone: form.value.phone,
          email: form.value.email,
          description: form.value.description,
          latitude: form.value.latitude || null,
          longitude: form.value.longitude || null,
          monthly_fee: form.value.monthly_fee || 0,
          commission_rate: form.value.commission_rate || 0
        }

        // Add owner details if creating account
        if (createOwner.value && !showEditModal.value) {
          payload.create_owner = true
          payload.owner_name = form.value.owner_name
          payload.owner_email = form.value.owner_email
          payload.owner_phone = form.value.owner_phone
          payload.owner_password = form.value.owner_password
        }

        if (showEditModal.value) {
          const { data } = await api.put(`/admin/restaurants/${form.value.id}`, payload)
          const index = restaurants.value.findIndex(r => r.id === form.value.id)
          if (index !== -1) {
            restaurants.value[index] = data.data
          }
          alert('Restaurant updated successfully!')
        } else {
          const { data } = await api.post('/admin/restaurants', payload)
          restaurants.value.unshift(data.data)
          alert('Restaurant created successfully!')
        }
        
        closeModal()
        await loadRestaurants()
      } catch (error) {
        console.error('Save error:', error)
        const message = error.response?.data?.message || 'Failed to save restaurant'
        alert(message)
      } finally {
        loading.value = false
      }
    }

    const approveRestaurant = async (restaurant) => {
      if (confirm(`Approve ${restaurant.name}?`)) {
        await api.post(`/admin/restaurants/${restaurant.id}/approve`)
        restaurant.is_verified = true
      }
    }

    const toggleStatus = async (restaurant) => {
      const action = restaurant.is_active ? 'suspend' : 'activate'
      if (confirm(`${action} ${restaurant.name}?`)) {
        await api.post(`/admin/restaurants/${restaurant.id}/${action}`)
        restaurant.is_active = !restaurant.is_active
      }
    }

    const deleteRestaurant = async (restaurant) => {
      if (confirm(`Delete ${restaurant.name}? This cannot be undone.`)) {
        await api.delete(`/admin/restaurants/${restaurant.id}`)
        restaurants.value = restaurants.value.filter(r => r.id !== restaurant.id)
      }
    }

    const changeStatus = async (restaurant, event) => {
      const newStatus = event.target.value
      if (confirm(`Change ${restaurant.name} status to ${newStatus}?`)) {
        try {
          await api.put(`/admin/restaurants/${restaurant.id}`, { status: newStatus })
          restaurant.status = newStatus
          await loadRestaurants()
          alert('Status updated successfully!')
        } catch (error) {
          alert('Failed to update status')
          event.target.value = restaurant.status
        }
      } else {
        event.target.value = restaurant.status
      }
    }

    const createOwnerLogin = async (restaurant) => {
      const ownerName = prompt('Enter owner name:')
      const ownerEmail = prompt('Enter owner email:')
      const ownerPassword = prompt('Enter password (min 8 characters):')
      
      if (ownerName && ownerEmail && ownerPassword) {
        try {
          await api.post(`/admin/restaurants/${restaurant.id}/create-owner`, {
            name: ownerName,
            email: ownerEmail,
            password: ownerPassword
          })
          alert('Owner login created successfully!')
          loadRestaurants()
          showDetailsModal.value = false
        } catch (error) {
          alert('Failed to create owner login')
        }
      }
    }

    const closeModal = () => {
      showCreateModal.value = false
      showEditModal.value = false
      createOwner.value = false
      form.value = { 
        name: '', address: '', phone: '', email: '', description: '',
        latitude: '', longitude: '',
        monthly_fee: '', commission_rate: '',
        owner_name: '', owner_email: '', owner_phone: '', owner_password: ''
      }
    }

    const updateMonthlyFee = async (restaurant) => {
      const newFee = prompt(`Enter new monthly fee for ${restaurant.name}:`, restaurant.monthly_fee || '0')
      if (newFee !== null) {
        try {
          await api.post(`/admin/restaurants/${restaurant.id}/update-fee`, {
            monthly_fee: parseFloat(newFee)
          })
          restaurant.monthly_fee = newFee
          alert('Monthly fee updated successfully!')
        } catch (error) {
          alert('Failed to update monthly fee')
        }
      }
    }

    const recordPayment = (restaurant) => {
      selectedRestaurant.value = restaurant
      paymentForm.value.amount = restaurant.monthly_fee || '0'
      showPaymentModal.value = true
    }

    const submitPayment = async () => {
      try {
        await api.post(`/admin/restaurants/${selectedRestaurant.value.id}/record-payment`, paymentForm.value)
        alert('✅ Payment recorded successfully!')
        showPaymentModal.value = false
        paymentForm.value = {
          amount: '',
          payment_date: new Date().toISOString().split('T')[0],
          payment_method: 'cash',
          transaction_id: '',
          notes: ''
        }
        await loadRestaurants()
        if (showDetailsModal.value) {
          viewDetails(selectedRestaurant.value)
        }
      } catch (error) {
        alert('❌ Failed to record payment')
      }
    }

    const getPaymentStatus = (restaurant) => {
      if (!restaurant.next_payment_date) return 'No Schedule'
      const nextDate = new Date(restaurant.next_payment_date)
      const today = new Date()
      if (nextDate < today) return '⚠️ Overdue'
      if (nextDate - today < 7 * 24 * 60 * 60 * 1000) return '🔔 Due Soon'
      return '✅ Paid'
    }

    const getPaymentStatusClass = (restaurant) => {
      const status = getPaymentStatus(restaurant)
      if (status.includes('Overdue')) return 'text-danger'
      if (status.includes('Due Soon')) return 'text-warning'
      return 'text-success'
    }

    const formatNumber = (num) => new Intl.NumberFormat().format(num || 0)

    const getStatusClass = (restaurant) => {
      if (restaurant.status === 'approved') return 'active'
      if (restaurant.status === 'pending') return 'pending'
      if (restaurant.status === 'suspended') return 'suspended'
      return 'pending'
    }

    const getStatusText = (restaurant) => {
      if (restaurant.status === 'approved') return 'Approved'
      if (restaurant.status === 'pending') return 'Pending'
      if (restaurant.status === 'suspended') return 'Suspended'
      if (restaurant.status === 'rejected') return 'Rejected'
      return 'Unknown'
    }

    const formatDate = (date) => {
      return new Date(date).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' })
    }

    onMounted(loadRestaurants)

    return {
      restaurants, loading, search, statusFilter, sortBy,
      showDetailsModal, showCreateModal, showEditModal, showPaymentModal,
      selectedRestaurant, createOwner, form, paymentForm,
      activeCount, pendingCount, suspendedCount,
      totalMonthlyRevenue, paidThisMonth, overdueCount, avgCommissionRate,
      filteredRestaurants, viewDetails, editRestaurant, saveRestaurant,
      approveRestaurant, toggleStatus, deleteRestaurant, createOwnerLogin, closeModal,
      updateMonthlyFee, recordPayment, submitPayment, getPaymentStatus, getPaymentStatusClass,
      getStatusClass, getStatusText, formatDate, formatNumber, changeStatus
    }
  }
}
</script>

<style scoped>
.restaurant-management { padding: 2rem; }

.page-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 2rem; }
.page-header h1 { margin: 0; font-size: 1.75rem; font-weight: 700; color: #1f2937; }
.subtitle { margin: 0.5rem 0 0; color: #6b7280; font-size: 0.875rem; }

.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); }

.stats-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 2rem; }

.stat-box {
  background: white;
  padding: 1.5rem;
  border-radius: 12px;
  display: flex;
  align-items: center;
  gap: 1rem;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}

.stat-icon { font-size: 2rem; }
.stat-label { margin: 0; font-size: 0.875rem; color: #6b7280; }
.stat-box h3 { margin: 0; font-size: 1.5rem; font-weight: 700; color: #1f2937; }

.payment-stats { margin-bottom: 2rem; }
.payment-stats h2 { margin: 0 0 1rem; font-size: 1.25rem; font-weight: 700; color: #1f2937; }
.payment-stat { border-left: 4px solid #10b981; }

.filters { 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); } }

.restaurant-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(350px, 1fr)); gap: 1.5rem; }

.restaurant-card {
  background: white;
  border-radius: 16px;
  padding: 1.5rem;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  transition: all 0.3s;
  border: 1px solid #f1f5f9;
}

.restaurant-card:hover { transform: translateY(-4px); box-shadow: 0 8px 24px rgba(0,0,0,0.12); }

.card-header { display: flex; align-items: flex-start; gap: 1rem; margin-bottom: 1rem; }

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

.restaurant-info { flex: 1; }
.restaurant-info h3 { margin: 0 0 0.25rem; font-size: 1.125rem; font-weight: 600; color: #1f2937; }
.restaurant-info p { margin: 0; font-size: 0.875rem; color: #6b7280; }

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

.status-badge.active { background: #d1fae5; color: #10b981; }
.status-badge.pending { background: #fef3c7; color: #f59e0b; }
.status-badge.suspended { background: #fee2e2; color: #ef4444; }

.card-body { margin-bottom: 1rem; }

.info-row {
  display: flex;
  justify-content: space-between;
  padding: 0.5rem 0;
  border-bottom: 1px solid #f3f4f6;
  font-size: 0.875rem;
}

.info-row:last-child { border-bottom: none; }
.label { color: #6b7280; font-weight: 500; }

.card-actions {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.card-actions button {
  flex: 1;
  min-width: 80px;
  padding: 0.5rem;
  border: none;
  border-radius: 8px;
  font-size: 0.75rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-view { background: #dbeafe; color: #3b82f6; }
.btn-edit { background: #e0e7ff; color: #6366f1; }
.btn-approve { background: #d1fae5; color: #10b981; }
.btn-toggle.activate { background: #d1fae5; color: #10b981; }
.btn-toggle.suspend { background: #fee2e2; color: #ef4444; }
.btn-delete { background: #fee2e2; color: #ef4444; }

.card-actions button:hover { transform: translateY(-2px); }

.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: 600px;
  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; }

.detail-section { margin-bottom: 1.5rem; }
.detail-section h3 { margin: 0 0 1rem; font-size: 1rem; color: #1f2937; }
.detail-grid { display: grid; gap: 1rem; }
.detail-item { display: flex; justify-content: space-between; padding: 0.75rem; background: #f9fafb; border-radius: 8px; }
.detail-item.full-width { flex-direction: column; gap: 0.5rem; }
.detail-label { font-weight: 600; color: #6b7280; }

.map-container { margin-top: 1rem; }
.map-placeholder { 
  height: 250px; 
  background: #f3f4f6; 
  border-radius: 8px; 
  display: flex; 
  flex-direction: column;
  align-items: center; 
  justify-content: center;
  color: #9ca3af;
}
.map-placeholder span { font-size: 3rem; margin-bottom: 0.5rem; }
.map-placeholder p { margin: 0; }

.btn-create-login {
  width: 100%;
  margin-top: 1rem;
  padding: 0.75rem;
  background: linear-gradient(135deg, #10b981, #059669);
  color: white;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-create-login:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3); }

.text-success { color: #10b981; font-weight: 600; }
.text-warning { color: #f59e0b; font-weight: 600; }
.text-danger { color: #ef4444; font-weight: 600; }

.fee-amount { font-size: 1.25rem; font-weight: 700; color: #10b981; }

.fee-actions { display: flex; gap: 0.75rem; margin-top: 1rem; }

.btn-update-fee, .btn-record-payment {
  flex: 1;
  padding: 0.75rem;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.btn-update-fee { background: #dbeafe; color: #3b82f6; }
.btn-record-payment { background: #d1fae5; color: #10b981; }
.btn-update-fee:hover, .btn-record-payment:hover { transform: translateY(-2px); }

.status-dropdown {
  padding: 0.375rem 0.75rem;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  font-size: 0.75rem;
  font-weight: 600;
  cursor: pointer;
  background: white;
  transition: all 0.3s;
}

.status-dropdown:hover { border-color: #ff6b35; }
.status-dropdown:focus { outline: none; border-color: #ff6b35; box-shadow: 0 0 0 3px rgba(255,107,53,0.1); }

.payment-history { max-height: 300px; overflow-y: auto; }

.payment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem;
  background: #f9fafb;
  border-radius: 8px;
  margin-bottom: 0.5rem;
}

.payment-info { display: flex; flex-direction: column; gap: 0.25rem; }
.payment-date { font-size: 0.875rem; color: #6b7280; }
.payment-amount { font-size: 1rem; font-weight: 700; color: #1f2937; }

.payment-status {
  padding: 0.25rem 0.75rem;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 600;
  text-transform: capitalize;
}

.payment-status.paid { background: #d1fae5; color: #10b981; }
.payment-status.pending { background: #fef3c7; color: #f59e0b; }
.payment-status.failed { background: #fee2e2; color: #ef4444; }

.no-payments {
  text-align: center;
  padding: 2rem;
  color: #9ca3af;
}

.no-payments span { font-size: 2rem; display: block; margin-bottom: 0.5rem; }
.no-payments p { margin: 0; }

.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, .form-textarea { 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-section { margin-bottom: 1.5rem; padding-bottom: 1.5rem; border-bottom: 1px solid #e5e7eb; }
.form-section:last-of-type { border-bottom: none; }
.form-section h3 { margin: 0 0 1rem; font-size: 1rem; color: #1f2937; }

.form-hint { margin: 0.5rem 0 0; font-size: 0.75rem; color: #6b7280; }

.form-checkbox { display: flex; align-items: center; gap: 0.5rem; margin-bottom: 1rem; }
.form-checkbox input[type="checkbox"] { width: 18px; height: 18px; cursor: pointer; }
.form-checkbox label { cursor: pointer; font-weight: 500; }

.owner-fields { padding: 1rem; background: #f9fafb; border-radius: 8px; border-left: 3px solid #ff6b35; }

.alert-info { 
  padding: 0.75rem; 
  background: #dbeafe; 
  color: #1e40af; 
  border-radius: 8px; 
  font-size: 0.875rem;
  margin-top: 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; }

.payment-modal { max-width: 500px; }

.restaurant-info-banner {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  background: linear-gradient(135deg, #ff6b35, #f7931e);
  border-radius: 12px;
  color: white;
  margin-bottom: 1.5rem;
}

.restaurant-info-banner .restaurant-avatar {
  width: 50px;
  height: 50px;
  background: rgba(255,255,255,0.2);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  font-weight: 700;
}

.restaurant-info-banner h3 { margin: 0; font-size: 1.125rem; }
.restaurant-info-banner p { margin: 0.25rem 0 0; opacity: 0.9; font-size: 0.875rem; }

.payment-summary {
  background: #f9fafb;
  border-radius: 12px;
  padding: 1rem;
  margin-bottom: 1.5rem;
  border-left: 4px solid #10b981;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  padding: 0.5rem 0;
  border-bottom: 1px solid #e5e7eb;
}

.summary-row:last-child { border-bottom: none; }
.summary-row span { color: #6b7280; }
.summary-row strong { color: #1f2937; }
</style>
