<template>
  <div class="modal-overlay" @click="$emit('close')">
    <div class="control-modal" @click.stop>
      <div class="modal-header">
        <h2>🎛️ Order Controls</h2>
        <div class="order-info">
          <span class="order-number">#{{ order.order_number }}</span>
          <span class="order-status" :class="order.status">{{ order.status }}</span>
        </div>
        <button @click="$emit('close')" class="close-btn">✕</button>
      </div>

      <div class="modal-body">
        <!-- Quick Actions -->
        <div class="action-section">
          <h3>⚡ Quick Actions</h3>
          <div class="action-grid">
            <button 
              @click="showForceCancel = true" 
              class="action-card cancel"
              :disabled="!canCancel"
            >
              <div class="action-icon">🚫</div>
              <div class="action-content">
                <div class="action-title">Force Cancel</div>
                <div class="action-desc">Cancel order with reason</div>
              </div>
            </button>

            <button 
              @click="showReassign = true" 
              class="action-card reassign"
              :disabled="!canReassign"
            >
              <div class="action-icon">🔄</div>
              <div class="action-content">
                <div class="action-title">Reassign Delivery</div>
                <div class="action-desc">Change delivery boy</div>
              </div>
            </button>

            <button 
              @click="showRefund = true" 
              class="action-card refund"
              :disabled="!canRefund"
            >
              <div class="action-icon">💰</div>
              <div class="action-content">
                <div class="action-title">Process Refund</div>
                <div class="action-desc">Issue customer refund</div>
              </div>
            </button>

            <button 
              @click="showStatusOverride = true" 
              class="action-card override"
            >
              <div class="action-icon">⚙️</div>
              <div class="action-content">
                <div class="action-title">Status Override</div>
                <div class="action-desc">Force status change</div>
              </div>
            </button>
          </div>
        </div>

        <!-- Order Information -->
        <div class="info-section">
          <h3>📋 Order Information</h3>
          <div class="info-grid">
            <div class="info-item">
              <span class="info-label">Customer</span>
              <span class="info-value">{{ order.customer_name }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">Total Amount</span>
              <span class="info-value">Rs. {{ formatCurrency(order.total) }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">Delivery Boy</span>
              <span class="info-value">{{ order.delivery_boy || 'Not Assigned' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">Created</span>
              <span class="info-value">{{ formatDateTime(order.created_at) }}</span>
            </div>
          </div>
        </div>

        <!-- Risk Indicators -->
        <div v-if="order.flags?.length > 0" class="risk-section">
          <h3>🚩 Risk Flags</h3>
          <div class="flags-list">
            <div 
              v-for="flag in order.flags" 
              :key="flag.id"
              class="flag-item"
              :class="flag.severity"
            >
              <div class="flag-icon">{{ getFlagIcon(flag.type) }}</div>
              <div class="flag-content">
                <div class="flag-type">{{ flag.type.replace('_', ' ').toUpperCase() }}</div>
                <div class="flag-desc">{{ flag.description }}</div>
              </div>
              <div class="flag-severity">{{ flag.severity }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- Action Modals -->
      <div v-if="showForceCancel" class="action-modal">
        <div class="action-form">
          <h4>🚫 Force Cancel Order</h4>
          <textarea 
            v-model="cancelReason" 
            placeholder="Enter cancellation reason..."
            class="reason-input"
            rows="3"
          ></textarea>
          <div class="form-actions">
            <button @click="showForceCancel = false" class="btn-secondary">Cancel</button>
            <button @click="executeForceCancel" class="btn-danger">Force Cancel Order</button>
          </div>
        </div>
      </div>

      <div v-if="showReassign" class="action-modal">
        <div class="action-form">
          <h4>🔄 Reassign Delivery Boy</h4>
          <select v-model="selectedDeliveryBoy" class="delivery-select">
            <option value="">Select Delivery Boy</option>
            <option 
              v-for="boy in availableDeliveryBoys" 
              :key="boy.id" 
              :value="boy.id"
            >
              {{ boy.name }} - {{ boy.phone }}
            </option>
          </select>
          <textarea 
            v-model="reassignReason" 
            placeholder="Enter reassignment reason..."
            class="reason-input"
            rows="2"
          ></textarea>
          <div class="form-actions">
            <button @click="showReassign = false" class="btn-secondary">Cancel</button>
            <button @click="executeReassign" class="btn-primary">Reassign</button>
          </div>
        </div>
      </div>

      <div v-if="showRefund" class="action-modal">
        <div class="action-form">
          <h4>💰 Process Refund</h4>
          <div class="refund-info">
            <div class="refund-item">
              <span>Order Total:</span>
              <span>Rs. {{ formatCurrency(order.total) }}</span>
            </div>
            <div class="refund-item">
              <span>Already Refunded:</span>
              <span>Rs. {{ formatCurrency(order.refund_amount || 0) }}</span>
            </div>
            <div class="refund-item">
              <span>Available for Refund:</span>
              <span>Rs. {{ formatCurrency(order.total - (order.refund_amount || 0)) }}</span>
            </div>
          </div>
          <input 
            v-model="refundAmount" 
            type="number" 
            :max="order.total - (order.refund_amount || 0)"
            placeholder="Refund amount"
            class="amount-input"
          >
          <textarea 
            v-model="refundReason" 
            placeholder="Enter refund reason..."
            class="reason-input"
            rows="2"
          ></textarea>
          <div class="form-actions">
            <button @click="showRefund = false" class="btn-secondary">Cancel</button>
            <button @click="executeRefund" class="btn-success">Process Refund</button>
          </div>
        </div>
      </div>

      <div v-if="showStatusOverride" class="action-modal">
        <div class="action-form">
          <h4>⚙️ Status Override</h4>
          <select v-model="newStatus" class="status-select">
            <option value="">Select New Status</option>
            <option value="pending">Pending</option>
            <option value="accepted">Accepted</option>
            <option value="preparing">Preparing</option>
            <option value="ready_for_pickup">Ready for Pickup</option>
            <option value="picked_up">Picked Up</option>
            <option value="delivered">Delivered</option>
            <option value="cancelled">Cancelled</option>
          </select>
          <textarea 
            v-model="overrideReason" 
            placeholder="Enter override reason..."
            class="reason-input"
            rows="2"
          ></textarea>
          <div class="form-actions">
            <button @click="showStatusOverride = false" class="btn-secondary">Cancel</button>
            <button @click="executeStatusOverride" class="btn-warning">Override Status</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'

export default {
  name: 'OrderControlsModal',
  props: {
    order: {
      type: Object,
      required: true
    }
  },
  emits: ['close', 'action'],
  setup(props, { emit }) {
    const showForceCancel = ref(false)
    const showReassign = ref(false)
    const showRefund = ref(false)
    const showStatusOverride = ref(false)
    
    const cancelReason = ref('')
    const reassignReason = ref('')
    const refundReason = ref('')
    const overrideReason = ref('')
    const refundAmount = ref(0)
    const newStatus = ref('')
    const selectedDeliveryBoy = ref('')
    
    const availableDeliveryBoys = ref([
      { id: 1, name: 'John Doe', phone: '0771234567' },
      { id: 2, name: 'Jane Smith', phone: '0779876543' },
      { id: 3, name: 'Mike Johnson', phone: '0775555555' }
    ])

    const canCancel = computed(() => {
      return !['cancelled', 'delivered'].includes(props.order.status)
    })

    const canReassign = computed(() => {
      return ['accepted', 'preparing', 'ready_for_pickup', 'picked_up'].includes(props.order.status)
    })

    const canRefund = computed(() => {
      return ['delivered', 'cancelled'].includes(props.order.status)
    })

    const formatCurrency = (amount) => {
      return parseFloat(amount || 0).toLocaleString('en-US', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    }

    const formatDateTime = (dateString) => {
      return new Date(dateString).toLocaleString('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    const getFlagIcon = (type) => {
      const icons = {
        late_delivery: '⏰',
        payment_issue: '💳',
        customer_complaint: '😠',
        quality_issue: '🍽️',
        multiple_rejects: '🔄'
      }
      return icons[type] || '🚩'
    }

    const executeForceCancel = () => {
      if (!cancelReason.value.trim()) {
        alert('Please enter a cancellation reason')
        return
      }
      
      emit('action', 'force_cancel', {
        order_id: props.order.id,
        reason: cancelReason.value
      })
      
      showForceCancel.value = false
      emit('close')
    }

    const executeReassign = () => {
      if (!selectedDeliveryBoy.value || !reassignReason.value.trim()) {
        alert('Please select a delivery boy and enter a reason')
        return
      }
      
      emit('action', 'reassign_delivery', {
        order_id: props.order.id,
        delivery_boy_id: selectedDeliveryBoy.value,
        reason: reassignReason.value
      })
      
      showReassign.value = false
      emit('close')
    }

    const executeRefund = () => {
      if (!refundAmount.value || !refundReason.value.trim()) {
        alert('Please enter refund amount and reason')
        return
      }
      
      emit('action', 'process_refund', {
        order_id: props.order.id,
        refund_amount: refundAmount.value,
        reason: refundReason.value
      })
      
      showRefund.value = false
      emit('close')
    }

    const executeStatusOverride = () => {
      if (!newStatus.value || !overrideReason.value.trim()) {
        alert('Please select new status and enter a reason')
        return
      }
      
      emit('action', 'status_override', {
        order_id: props.order.id,
        status: newStatus.value,
        reason: overrideReason.value
      })
      
      showStatusOverride.value = false
      emit('close')
    }

    return {
      showForceCancel,
      showReassign,
      showRefund,
      showStatusOverride,
      cancelReason,
      reassignReason,
      refundReason,
      overrideReason,
      refundAmount,
      newStatus,
      selectedDeliveryBoy,
      availableDeliveryBoys,
      canCancel,
      canReassign,
      canRefund,
      formatCurrency,
      formatDateTime,
      getFlagIcon,
      executeForceCancel,
      executeReassign,
      executeRefund,
      executeStatusOverride
    }
  }
}
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(10px);
}

.control-modal {
  background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
  border-radius: 24px;
  border: 1px solid rgba(59, 130, 246, 0.3);
  max-width: 800px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.5);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 2rem;
  border-bottom: 1px solid rgba(59, 130, 246, 0.2);
  background: rgba(59, 130, 246, 0.05);
}

.modal-header h2 {
  color: #f8fafc;
  margin: 0;
  font-size: 1.5rem;
  font-weight: 700;
}

.order-info {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.order-number {
  font-weight: 700;
  color: #3b82f6;
  font-size: 1.125rem;
}

.order-status {
  padding: 0.5rem 1rem;
  border-radius: 8px;
  font-size: 0.875rem;
  font-weight: 600;
  text-transform: uppercase;
}

.order-status.pending { background: rgba(245, 158, 11, 0.2); color: #f59e0b; }
.order-status.delivered { background: rgba(16, 185, 129, 0.2); color: #10b981; }
.order-status.cancelled { background: rgba(239, 68, 68, 0.2); color: #ef4444; }

.close-btn {
  background: rgba(239, 68, 68, 0.2);
  border: 1px solid rgba(239, 68, 68, 0.3);
  border-radius: 8px;
  color: #ef4444;
  padding: 0.5rem;
  cursor: pointer;
  font-size: 1.2rem;
  width: 40px;
  height: 40px;
}

.modal-body {
  padding: 2rem;
}

.action-section, .info-section, .risk-section {
  margin-bottom: 2rem;
}

.action-section h3, .info-section h3, .risk-section h3 {
  color: #f8fafc;
  margin-bottom: 1rem;
  font-size: 1.125rem;
  font-weight: 600;
}

.action-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 1rem;
}

.action-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
  padding: 1.5rem;
  border-radius: 16px;
  border: 1px solid;
  cursor: pointer;
  transition: all 0.3s ease;
  background: rgba(30, 41, 59, 0.6);
}

.action-card:hover:not(:disabled) {
  transform: translateY(-4px);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
}

.action-card:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.action-card.cancel {
  border-color: rgba(239, 68, 68, 0.3);
  color: #ef4444;
}

.action-card.reassign {
  border-color: rgba(245, 158, 11, 0.3);
  color: #f59e0b;
}

.action-card.refund {
  border-color: rgba(16, 185, 129, 0.3);
  color: #10b981;
}

.action-card.override {
  border-color: rgba(139, 92, 246, 0.3);
  color: #8b5cf6;
}

.action-icon {
  font-size: 2rem;
}

.action-content {
  text-align: center;
}

.action-title {
  font-weight: 600;
  margin-bottom: 0.25rem;
}

.action-desc {
  font-size: 0.875rem;
  opacity: 0.8;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 1rem;
  background: rgba(30, 41, 59, 0.6);
  border-radius: 12px;
  border: 1px solid rgba(59, 130, 246, 0.2);
}

.info-label {
  color: #94a3b8;
  font-size: 0.875rem;
}

.info-value {
  color: #f8fafc;
  font-weight: 600;
}

.flags-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.flag-item {
  display: flex;
  align-items: center;
  gap: 1rem;
  padding: 1rem;
  border-radius: 12px;
  border: 1px solid;
}

.flag-item.high {
  border-color: rgba(245, 158, 11, 0.5);
  background: rgba(245, 158, 11, 0.1);
}

.flag-item.critical {
  border-color: rgba(239, 68, 68, 0.5);
  background: rgba(239, 68, 68, 0.1);
}

.flag-icon {
  font-size: 1.5rem;
}

.flag-content {
  flex: 1;
}

.flag-type {
  font-weight: 600;
  color: #f8fafc;
  margin-bottom: 0.25rem;
}

.flag-desc {
  color: #94a3b8;
  font-size: 0.875rem;
}

.flag-severity {
  padding: 0.25rem 0.75rem;
  border-radius: 6px;
  font-size: 0.75rem;
  font-weight: 600;
  text-transform: uppercase;
  background: rgba(245, 158, 11, 0.2);
  color: #f59e0b;
}

.action-modal {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 24px;
}

.action-form {
  background: linear-gradient(135deg, #1e293b 0%, #334155 100%);
  border-radius: 16px;
  padding: 2rem;
  border: 1px solid rgba(59, 130, 246, 0.3);
  min-width: 400px;
}

.action-form h4 {
  color: #f8fafc;
  margin-bottom: 1.5rem;
  font-size: 1.25rem;
  font-weight: 600;
}

.reason-input, .amount-input, .delivery-select, .status-select {
  width: 100%;
  padding: 1rem;
  background: rgba(30, 41, 59, 0.8);
  border: 1px solid rgba(59, 130, 246, 0.3);
  border-radius: 8px;
  color: #f8fafc;
  margin-bottom: 1rem;
  font-size: 1rem;
}

.reason-input::placeholder, .amount-input::placeholder {
  color: #64748b;
}

.refund-info {
  background: rgba(30, 41, 59, 0.6);
  border-radius: 8px;
  padding: 1rem;
  margin-bottom: 1rem;
}

.refund-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.5rem;
  color: #f8fafc;
}

.refund-item:last-child {
  margin-bottom: 0;
  font-weight: 600;
  border-top: 1px solid rgba(59, 130, 246, 0.2);
  padding-top: 0.5rem;
}

.form-actions {
  display: flex;
  gap: 1rem;
  justify-content: flex-end;
}

.btn-secondary, .btn-danger, .btn-primary, .btn-success, .btn-warning {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-secondary {
  background: rgba(107, 114, 128, 0.2);
  color: #9ca3af;
  border: 1px solid rgba(107, 114, 128, 0.3);
}

.btn-danger {
  background: rgba(239, 68, 68, 0.2);
  color: #ef4444;
  border: 1px solid rgba(239, 68, 68, 0.3);
}

.btn-primary {
  background: rgba(59, 130, 246, 0.2);
  color: #3b82f6;
  border: 1px solid rgba(59, 130, 246, 0.3);
}

.btn-success {
  background: rgba(16, 185, 129, 0.2);
  color: #10b981;
  border: 1px solid rgba(16, 185, 129, 0.3);
}

.btn-warning {
  background: rgba(245, 158, 11, 0.2);
  color: #f59e0b;
  border: 1px solid rgba(245, 158, 11, 0.3);
}

.btn-secondary:hover, .btn-danger:hover, .btn-primary:hover, .btn-success:hover, .btn-warning:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}
</style>