<template>
  <div class="earnings-management">
    <h1>💰 Earnings & Commission Management</h1>

    <!-- Summary Cards -->
    <div class="summary-cards">
      <div class="summary-card total">
        <div class="card-icon">💵</div>
        <div class="card-content">
          <p class="card-label">Total Payout</p>
          <h2 class="card-value">Rs {{ formatNumber(summary.total_payout) }}</h2>
          <p class="card-info">All time</p>
        </div>
      </div>

      <div class="summary-card pending">
        <div class="card-icon">⏳</div>
        <div class="card-content">
          <p class="card-label">Pending Payout</p>
          <h2 class="card-value">Rs {{ formatNumber(summary.pending_payout) }}</h2>
          <p class="card-info">{{ summary.pending_count }} delivery boys</p>
        </div>
      </div>

      <div class="summary-card commission">
        <div class="card-icon">📊</div>
        <div class="card-content">
          <p class="card-label">Platform Commission</p>
          <h2 class="card-value">Rs {{ formatNumber(summary.platform_commission) }}</h2>
          <p class="card-info">This month</p>
        </div>
      </div>
    </div>

    <!-- Filters -->
    <div class="filters-section">
      <select v-model="selectedMonth" class="filter-select">
        <option value="">All Months</option>
        <option value="2025-12">December 2025</option>
        <option value="2025-11">November 2025</option>
        <option value="2025-10">October 2025</option>
      </select>
      <select v-model="statusFilter" class="filter-select">
        <option value="">All Status</option>
        <option value="pending">Pending</option>
        <option value="paid">Paid</option>
      </select>
      <button @click="markSelectedAsPaid" :disabled="selectedEarnings.length === 0" class="btn-primary">
        ✅ Mark as Paid ({{ selectedEarnings.length }})
      </button>
    </div>

    <!-- Earnings Table -->
    <div class="table-container">
      <table class="earnings-table">
        <thead>
          <tr>
            <th><input type="checkbox" @change="toggleSelectAll" :checked="allSelected"></th>
            <th>Delivery Boy</th>
            <th>Phone</th>
            <th>Total Deliveries</th>
            <th>Total Earnings</th>
            <th>Commission</th>
            <th>Net Payout</th>
            <th>Status</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="earning in filteredEarnings" :key="earning.id">
            <td><input type="checkbox" :value="earning.id" v-model="selectedEarnings"></td>
            <td class="name-cell">{{ earning.delivery_boy_name }}</td>
            <td>{{ earning.phone }}</td>
            <td>{{ earning.total_deliveries }}</td>
            <td class="amount">Rs {{ formatNumber(earning.total_earnings) }}</td>
            <td class="amount commission-amount">Rs {{ formatNumber(earning.commission) }}</td>
            <td class="amount net-amount">Rs {{ formatNumber(earning.net_payout) }}</td>
            <td>
              <span :class="['status-badge', earning.status]">{{ earning.status }}</span>
            </td>
            <td>
              <button @click="viewHistory(earning)" class="btn-icon" title="View History">📋</button>
              <button v-if="earning.status === 'pending'" @click="markAsPaid(earning)" class="btn-icon" title="Mark as Paid">✅</button>
            </td>
          </tr>
        </tbody>
      </table>

      <div v-if="filteredEarnings.length === 0" class="empty-state">
        <span class="empty-icon">💰</span>
        <h3>No earnings found</h3>
        <p>Try adjusting your filters</p>
      </div>
    </div>

    <!-- Payout History Modal -->
    <div v-if="showHistoryModal" class="modal-overlay" @click="showHistoryModal = false">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h2>📋 Payout History - {{ selectedEarning.delivery_boy_name }}</h2>
          <button @click="showHistoryModal = false" class="close-btn">✕</button>
        </div>
        <div class="modal-body">
          <div class="history-summary">
            <div class="summary-item">
              <span class="label">Total Paid:</span>
              <span class="value">Rs {{ formatNumber(selectedEarning.total_paid) }}</span>
            </div>
            <div class="summary-item">
              <span class="label">Pending:</span>
              <span class="value">Rs {{ formatNumber(selectedEarning.net_payout) }}</span>
            </div>
          </div>

          <h3>Payment History</h3>
          <div class="history-list">
            <div v-for="payment in paymentHistory" :key="payment.id" class="history-item">
              <div class="history-info">
                <p class="history-date">{{ payment.date }}</p>
                <p class="history-method">{{ payment.method }}</p>
              </div>
              <div class="history-amount">Rs {{ formatNumber(payment.amount) }}</div>
            </div>
          </div>

          <div v-if="paymentHistory.length === 0" class="empty-state">
            <p>No payment history</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

export default {
  setup() {
    const summary = ref({
      total_payout: 45230.50,
      pending_payout: 8420.00,
      pending_count: 12,
      platform_commission: 6734.50
    })

    const earnings = ref([
      { id: 1, delivery_boy_name: 'John Doe', phone: '0771234567', total_deliveries: 45, total_earnings: 1250.00, commission: 187.50, net_payout: 1062.50, status: 'pending' },
      { id: 2, delivery_boy_name: 'Jane Smith', phone: '0772345678', total_deliveries: 38, total_earnings: 980.00, commission: 147.00, net_payout: 833.00, status: 'pending' },
      { id: 3, delivery_boy_name: 'Mike Johnson', phone: '0773456789', total_deliveries: 52, total_earnings: 1420.00, commission: 213.00, net_payout: 1207.00, status: 'paid' },
    ])

    const selectedMonth = ref('')
    const statusFilter = ref('')
    const selectedEarnings = ref([])
    const showHistoryModal = ref(false)
    const selectedEarning = ref({})
    const paymentHistory = ref([
      { id: 1, date: '2025-12-01', method: 'Bank Transfer', amount: 1200.00 },
      { id: 2, date: '2025-11-01', method: 'Bank Transfer', amount: 1150.00 },
      { id: 3, date: '2025-10-01', method: 'Cash', amount: 980.00 },
    ])

    const filteredEarnings = computed(() => {
      let result = earnings.value

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

      return result
    })

    const allSelected = computed(() => {
      return selectedEarnings.value.length === filteredEarnings.value.length && filteredEarnings.value.length > 0
    })

    const toggleSelectAll = () => {
      if (allSelected.value) {
        selectedEarnings.value = []
      } else {
        selectedEarnings.value = filteredEarnings.value.map(e => e.id)
      }
    }

    const markAsPaid = async (earning) => {
      if (confirm(`Mark payout as paid for ${earning.delivery_boy_name}?`)) {
        earning.status = 'paid'
        alert('✅ Marked as paid successfully!')
      }
    }

    const markSelectedAsPaid = async () => {
      if (confirm(`Mark ${selectedEarnings.value.length} payouts as paid?`)) {
        earnings.value.forEach(e => {
          if (selectedEarnings.value.includes(e.id)) {
            e.status = 'paid'
          }
        })
        selectedEarnings.value = []
        alert('✅ Marked as paid successfully!')
      }
    }

    const viewHistory = (earning) => {
      selectedEarning.value = earning
      showHistoryModal.value = true
    }

    const formatNumber = (num) => {
      return new Intl.NumberFormat('en-US', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }).format(num || 0)
    }

    return {
      summary,
      earnings,
      selectedMonth,
      statusFilter,
      selectedEarnings,
      showHistoryModal,
      selectedEarning,
      paymentHistory,
      filteredEarnings,
      allSelected,
      toggleSelectAll,
      markAsPaid,
      markSelectedAsPaid,
      viewHistory,
      formatNumber
    }
  }
}
</script>

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

h1 { margin: 0 0 2rem; font-size: 2rem; font-weight: 700; color: #1f2937; }

.summary-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.summary-card {
  background: white;
  border-radius: 16px;
  padding: 1.5rem;
  display: flex;
  gap: 1.25rem;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  border-left: 4px solid;
}

.summary-card.total { border-color: #10b981; }
.summary-card.pending { border-color: #f59e0b; }
.summary-card.commission { border-color: #3b82f6; }

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2rem;
  flex-shrink: 0;
}

.summary-card.total .card-icon { background: linear-gradient(135deg, #10b981, #059669); }
.summary-card.pending .card-icon { background: linear-gradient(135deg, #f59e0b, #d97706); }
.summary-card.commission .card-icon { background: linear-gradient(135deg, #3b82f6, #2563eb); }

.card-content { flex: 1; }
.card-label { margin: 0; font-size: 0.875rem; color: #6b7280; font-weight: 500; }
.card-value { margin: 0.5rem 0; font-size: 2rem; font-weight: 700; color: #1f2937; }
.card-info { margin: 0; font-size: 0.75rem; color: #9ca3af; }

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

.filter-select {
  padding: 0.75rem 1rem;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  font-size: 0.875rem;
  cursor: pointer;
}

.btn-primary {
  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:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

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

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

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

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

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

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

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

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

.amount {
  font-weight: 600;
  text-align: right;
}

.commission-amount { color: #ef4444; }
.net-amount { color: #10b981; font-size: 1rem; }

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

.status-badge.pending { background: #fef3c7; color: #f59e0b; }
.status-badge.paid { background: #d1fae5; color: #10b981; }

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

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

.history-summary {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
  margin-bottom: 2rem;
}

.summary-item {
  padding: 1rem;
  background: #f9fafb;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.summary-item .label { font-size: 0.875rem; color: #6b7280; }
.summary-item .value { font-size: 1.5rem; font-weight: 700; color: #1f2937; }

.modal-body h3 { margin: 0 0 1rem; font-size: 1.125rem; color: #1f2937; }

.history-list { display: flex; flex-direction: column; gap: 0.75rem; }

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  background: #f9fafb;
  border-radius: 12px;
}

.history-date { margin: 0; font-size: 0.875rem; color: #1f2937; font-weight: 600; }
.history-method { margin: 0.25rem 0 0; font-size: 0.75rem; color: #6b7280; }
.history-amount { font-size: 1.125rem; font-weight: 700; color: #10b981; }

@media (max-width: 768px) {
  .earnings-table { display: block; overflow-x: auto; }
}
</style>
