<template>
  <div class="min-h-screen bg-gray-50 pb-20">
    <!-- Header -->
    <div class="bg-gradient-to-r from-green-600 to-green-700 text-white p-6">
      <h1 class="text-2xl font-bold">My Earnings</h1>
      <p class="text-green-100 text-sm mt-1">Track your commission and payments</p>
    </div>

    <!-- Stats Cards -->
    <div class="p-4 -mt-8">
      <div class="grid grid-cols-2 gap-4 mb-4">
        <div class="bg-white rounded-xl shadow-lg p-4 border-l-4 border-green-500">
          <p class="text-xs text-gray-600 mb-1">Total Earnings</p>
          <p class="text-2xl font-bold text-gray-900">Rs. {{ formatNumber(stats.total) }}</p>
          <p class="text-xs text-gray-500 mt-1">{{ stats.count }} deliveries</p>
        </div>
        <div class="bg-white rounded-xl shadow-lg p-4 border-l-4 border-orange-500">
          <p class="text-xs text-gray-600 mb-1">Pending</p>
          <p class="text-2xl font-bold text-orange-600">Rs. {{ formatNumber(stats.pending) }}</p>
          <p class="text-xs text-gray-500 mt-1">Not paid yet</p>
        </div>
      </div>
      <div class="bg-white rounded-xl shadow-lg p-4 border-l-4 border-blue-500">
        <p class="text-xs text-gray-600 mb-1">Paid Amount</p>
        <p class="text-2xl font-bold text-blue-600">Rs. {{ formatNumber(stats.paid) }}</p>
        <p class="text-xs text-gray-500 mt-1">Successfully received</p>
      </div>
    </div>

    <!-- Filters -->
    <div class="p-4">
      <div class="bg-white rounded-xl shadow-sm p-4 mb-4">
        <h3 class="font-semibold text-gray-900 mb-3 flex items-center gap-2">
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" />
          </svg>
          Filters
        </h3>
        
        <div class="space-y-3">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Status</label>
            <select
              v-model="filters.status"
              @change="loadEarnings"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent"
            >
              <option value="">All Status</option>
              <option value="pending">Pending</option>
              <option value="paid">Paid</option>
            </select>
          </div>

          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">Type</label>
            <select
              v-model="filters.type"
              @change="loadEarnings"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent"
            >
              <option value="">All Types</option>
              <option value="commission">Commission</option>
              <option value="bonus">Bonus</option>
              <option value="tip">Tip</option>
            </select>
          </div>

          <div class="grid grid-cols-2 gap-3">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">From</label>
              <input
                v-model="filters.date_from"
                type="date"
                @change="loadEarnings"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent"
              />
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">To</label>
              <input
                v-model="filters.date_to"
                type="date"
                @change="loadEarnings"
                class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-transparent"
              />
            </div>
          </div>

          <button
            @click="resetFilters"
            class="w-full px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition"
          >
            Reset Filters
          </button>
        </div>
      </div>

      <!-- Earnings List -->
      <div class="space-y-3">
        <div v-if="loading" v-for="i in 3" :key="i" class="bg-white rounded-xl shadow-sm p-4 animate-pulse">
          <div class="h-4 bg-gray-200 rounded w-3/4 mb-2"></div>
          <div class="h-3 bg-gray-200 rounded w-1/2"></div>
        </div>

        <div v-else-if="earnings.length === 0" class="bg-white rounded-xl shadow-sm p-8 text-center">
          <svg class="w-16 h-16 mx-auto text-gray-400 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" />
          </svg>
          <p class="text-gray-600 font-medium">No earnings found</p>
          <p class="text-sm text-gray-500 mt-1">Try adjusting your filters</p>
        </div>

        <div
          v-else
          v-for="earning in earnings"
          :key="earning.id"
          class="bg-white rounded-xl shadow-sm p-4 border-l-4"
          :class="getStatusBorderClass(earning.status)"
        >
          <div class="flex justify-between items-start mb-2">
            <div>
              <div class="flex items-center gap-2 mb-1">
                <span class="text-xs font-semibold px-2 py-1 rounded-full" :class="getTypeClass(earning.earning_type)">
                  {{ earning.earning_type }}
                </span>
                <span class="text-xs font-semibold px-2 py-1 rounded-full" :class="getStatusClass(earning.status)">
                  {{ earning.status }}
                </span>
              </div>
              <p class="text-sm text-gray-600">Order: {{ earning.order_number || 'N/A' }}</p>
              <p class="text-xs text-gray-500 mt-1">{{ formatDate(earning.created_at) }}</p>
            </div>
            <div class="text-right">
              <p class="text-2xl font-bold text-gray-900">Rs. {{ formatNumber(earning.amount) }}</p>
              <p class="text-xs text-gray-500">{{ earning.commission_rate }}% rate</p>
            </div>
          </div>
          <p v-if="earning.description" class="text-xs text-gray-600 mt-2 pt-2 border-t border-gray-100">
            {{ earning.description }}
          </p>
        </div>
      </div>
    </div>

    <!-- Bottom Navigation -->
    <div class="fixed bottom-0 left-0 right-0 bg-white flex shadow-lg border-t border-gray-200">
      <a href="/delivery-boy" class="flex-1 flex flex-col items-center gap-1 py-3 text-gray-400 no-underline">
        <span class="text-2xl">📋</span>
        <span class="text-xs">Available</span>
      </a>
      <a href="/delivery-boy" class="flex-1 flex flex-col items-center gap-1 py-3 text-gray-400 no-underline">
        <span class="text-2xl">🚚</span>
        <span class="text-xs">My Orders</span>
      </a>
      <a href="/delivery-boy/earnings" class="flex-1 flex flex-col items-center gap-1 py-3 text-green-600 no-underline">
        <span class="text-2xl">💰</span>
        <span class="text-xs">Earnings</span>
      </a>
      <a href="/delivery-boy/profile" class="flex-1 flex flex-col items-center gap-1 py-3 text-gray-400 no-underline">
        <span class="text-2xl">👤</span>
        <span class="text-xs">Profile</span>
      </a>
    </div>
  </div>
</template>

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

const earnings = ref([]);
const loading = ref(false);
const stats = ref({
  total: 0,
  pending: 0,
  paid: 0,
  count: 0,
});

const filters = ref({
  status: '',
  type: '',
  date_from: '',
  date_to: '',
});

const loadEarnings = async () => {
  loading.value = true;
  try {
    const { data } = await api.get('/delivery-boy/earnings/details', {
      params: filters.value,
    });
    earnings.value = data.data;
    stats.value = data.stats;
  } catch (error) {
    console.error('Failed to load earnings:', error);
  } finally {
    loading.value = false;
  }
};

const resetFilters = () => {
  filters.value = {
    status: '',
    type: '',
    date_from: '',
    date_to: '',
  };
  loadEarnings();
};

const formatNumber = (num) => {
  return parseFloat(num || 0).toFixed(2);
};

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

const getStatusClass = (status) => {
  const classes = {
    pending: 'bg-orange-100 text-orange-800',
    paid: 'bg-green-100 text-green-800',
    cancelled: 'bg-red-100 text-red-800',
  };
  return classes[status] || 'bg-gray-100 text-gray-800';
};

const getStatusBorderClass = (status) => {
  const classes = {
    pending: 'border-orange-500',
    paid: 'border-green-500',
    cancelled: 'border-red-500',
  };
  return classes[status] || 'border-gray-300';
};

const getTypeClass = (type) => {
  const classes = {
    commission: 'bg-blue-100 text-blue-800',
    bonus: 'bg-green-100 text-green-800',
    tip: 'bg-yellow-100 text-yellow-800',
    penalty: 'bg-red-100 text-red-800',
  };
  return classes[type] || 'bg-gray-100 text-gray-800';
};

onMounted(() => {
  loadEarnings();
});
</script>
