<template>
  <div
    class="batch-group-header"
    :class="{ 'is-expanded': isExpanded, 'has-active-processing': hasActiveProcessing }"
    @click="$emit('toggle')"
  >
    <div class="batch-header-content">
      <i
        class="pi chevron-icon"
        :class="isExpanded ? 'pi-chevron-down' : 'pi-chevron-right'"
      ></i>

      <div class="batch-info">
        <span class="batch-label">
          <template v-if="batchId">
            Batch {{ shortBatchId }}
          </template>
          <template v-else>
            Alte bonuri
          </template>
        </span>

        <span class="batch-separator">•</span>

        <span class="batch-date" v-if="formattedDate">
          {{ formattedDate }}
        </span>
        <span class="batch-date" v-else>
          Creat manual
        </span>

        <span class="batch-separator">•</span>

        <span class="batch-count">
          {{ itemsCount }} {{ itemsCount === 1 ? 'fișier' : 'fișiere' }}
        </span>
      </div>

      <!-- Processing status indicator -->
      <div v-if="hasActiveProcessing" class="batch-status-indicator processing">
        <i class="pi pi-spin pi-spinner"></i>
        <span>{{ activeProcessingCount }} în procesare</span>
        <!-- US-021: Cancel All button - visible when there are pending/processing jobs -->
        <button
          v-if="batchId"
          class="cancel-all-btn"
          @click.stop="handleCancelAll"
          title="Anulează toate fișierele în așteptare"
        >
          <i class="pi pi-times"></i>
          <span class="cancel-btn-text">Anulează tot</span>
        </button>
      </div>
      <div v-else-if="failedCount > 0" class="batch-status-indicator failed">
        <i class="pi pi-exclamation-circle"></i>
        <span>{{ failedCount }} cu erori</span>
        <!-- US-006: Retry All Failed button -->
        <button
          v-if="batchId && !retrying"
          class="retry-all-btn"
          @click.stop="handleRetryAll"
          title="Reîncercă toate erorile"
        >
          <i class="pi pi-refresh"></i>
          <span class="retry-btn-text">Reîncercă</span>
        </button>
        <span v-if="retrying" class="retry-loading">
          <i class="pi pi-spin pi-spinner"></i>
        </span>
      </div>
      <div v-else-if="allCompleted" class="batch-status-indicator completed">
        <i class="pi pi-check-circle"></i>
        <span>Procesat</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'

const props = defineProps({
  batchId: {
    type: String,
    default: null
  },
  processingStartedAt: {
    type: String,
    default: null
  },
  items: {
    type: Array,
    required: true
  },
  isExpanded: {
    type: Boolean,
    default: false
  },
  // US-006: Whether retry is in progress
  retrying: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['toggle', 'retry-all', 'cancel-all'])

/**
 * Handle retry all button click.
 * Stops propagation to prevent toggle, emits retry-all event.
 */
const handleRetryAll = () => {
  if (props.batchId) {
    emit('retry-all', props.batchId)
  }
}

/**
 * Handle cancel all button click.
 * Stops propagation to prevent toggle, emits cancel-all event with batch info.
 *
 * @emits cancel-all - Emits batch ID and counts for confirmation dialog
 */
const handleCancelAll = () => {
  if (props.batchId) {
    emit('cancel-all', {
      batchId: props.batchId,
      pendingProcessingCount: pendingProcessingCount.value,
      completedCount: completedJobsCount.value
    })
  }
}

// Compute short batch ID (first 8 chars) - format: B-XXXXXXXX
const shortBatchId = computed(() => {
  if (!props.batchId) return ''
  // If batch_id is UUID-like, take first 8 chars
  const id = props.batchId.replace(/-/g, '').substring(0, 8).toUpperCase()
  return `B-${id}`
})

// Format date as "DD Mon YYYY"
const formattedDate = computed(() => {
  if (!props.processingStartedAt) return null

  const date = new Date(props.processingStartedAt)
  const months = ['Ian', 'Feb', 'Mar', 'Apr', 'Mai', 'Iun', 'Iul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

  const day = date.getDate().toString().padStart(2, '0')
  const month = months[date.getMonth()]
  const year = date.getFullYear()

  return `${day} ${month} ${year}`
})

// Count items
const itemsCount = computed(() => props.items.length)

// Check for active processing (pending or processing status)
const activeProcessingCount = computed(() => {
  return props.items.filter(
    item => item.processing_status === 'pending' || item.processing_status === 'processing'
  ).length
})

const hasActiveProcessing = computed(() => activeProcessingCount.value > 0)

/**
 * US-021: Count of pending/processing items that CAN be cancelled.
 * This is the same as activeProcessingCount but with a clearer name for cancel context.
 */
const pendingProcessingCount = computed(() => activeProcessingCount.value)

/**
 * US-021: Count of completed items that will REMAIN after cancel.
 * These are receipts already processed successfully.
 */
const completedJobsCount = computed(() => {
  return props.items.filter(item => item.processing_status === 'completed').length
})

// Failed items count
const failedCount = computed(() => {
  return props.items.filter(item => item.processing_status === 'failed').length
})

// Check if all completed
const allCompleted = computed(() => {
  if (!props.batchId) return false // Manual items don't show completed status
  return props.items.every(item => item.processing_status === 'completed')
})
</script>

<style scoped>
.batch-group-header {
  display: flex;
  align-items: center;
  padding: var(--space-sm) var(--space-md);
  background: var(--surface-ground);
  border: 1px solid var(--surface-border);
  border-radius: var(--radius-sm);
  cursor: pointer;
  user-select: none;
  transition: background var(--transition-fast), border-color var(--transition-fast);
  margin-bottom: var(--space-xs);
}

.batch-group-header:hover {
  background: var(--surface-hover);
}

.batch-group-header.is-expanded {
  border-bottom-left-radius: 0;
  border-bottom-right-radius: 0;
  margin-bottom: 0;
  border-bottom-color: transparent;
}

.batch-group-header.has-active-processing {
  border-left: 3px solid var(--blue-500);
}

.batch-header-content {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
  width: 100%;
}

.chevron-icon {
  font-size: var(--text-sm);
  color: var(--text-color-secondary);
  transition: transform var(--transition-fast);
  flex-shrink: 0;
}

.batch-info {
  display: flex;
  align-items: center;
  gap: var(--space-sm);
  flex: 1;
  min-width: 0;
  flex-wrap: wrap;
}

.batch-label {
  font-weight: var(--font-semibold);
  font-size: var(--text-sm);
  color: var(--text-color);
}

.batch-separator {
  color: var(--text-color-secondary);
  font-size: var(--text-xs);
}

.batch-date {
  font-size: var(--text-sm);
  color: var(--text-color-secondary);
}

.batch-count {
  font-size: var(--text-sm);
  color: var(--text-color-secondary);
}

/* Status indicators */
.batch-status-indicator {
  display: flex;
  align-items: center;
  gap: var(--space-xs);
  font-size: var(--text-xs);
  font-weight: var(--font-medium);
  padding: var(--space-xs) var(--space-sm);
  border-radius: var(--radius-sm);
  flex-shrink: 0;
}

.batch-status-indicator.processing {
  background: var(--blue-50);
  color: var(--blue-600);
}

.batch-status-indicator.failed {
  background: var(--red-50);
  color: var(--red-600);
}

.batch-status-indicator.completed {
  background: var(--green-50);
  color: var(--green-600);
}

/* US-006: Retry All Failed button */
.retry-all-btn {
  display: inline-flex;
  align-items: center;
  gap: var(--space-xs);
  margin-left: var(--space-sm);
  padding: var(--space-xs) var(--space-sm);
  background: var(--surface-card);
  border: 1px solid var(--red-300);
  border-radius: var(--radius-sm);
  color: var(--red-700);
  font-size: var(--text-xs);
  font-weight: var(--font-medium);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.retry-all-btn:hover {
  background: var(--red-100);
  border-color: var(--red-400);
}

.retry-all-btn:active {
  transform: scale(0.98);
}

.retry-loading {
  margin-left: var(--space-sm);
}

/* US-021: Cancel All button */
.cancel-all-btn {
  display: inline-flex;
  align-items: center;
  gap: var(--space-xs);
  margin-left: var(--space-sm);
  padding: var(--space-xs) var(--space-sm);
  background: var(--surface-card);
  border: 1px solid var(--surface-border);
  border-radius: var(--radius-sm);
  color: var(--text-color-secondary);
  font-size: var(--text-xs);
  font-weight: var(--font-medium);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.cancel-all-btn:hover {
  background: var(--red-50);
  border-color: var(--red-300);
  color: var(--red-700);
}

.cancel-all-btn:active {
  transform: scale(0.98);
}

/* Mobile responsive */
@media (max-width: 768px) {
  .batch-group-header {
    padding: var(--space-sm);
  }

  .batch-info {
    gap: var(--space-xs);
  }

  .batch-separator {
    display: none;
  }

  .batch-date,
  .batch-count {
    font-size: var(--text-xs);
  }

  .batch-status-indicator {
    padding: var(--space-xs);
  }

  .batch-status-indicator span {
    display: none;
  }

  .retry-all-btn .retry-btn-text {
    display: none;
  }

  .retry-all-btn {
    padding: var(--space-xs);
    margin-left: var(--space-xs);
  }

  /* US-021: Hide cancel button text on mobile, show only icon */
  .cancel-all-btn .cancel-btn-text {
    display: none;
  }

  .cancel-all-btn {
    padding: var(--space-xs);
    margin-left: var(--space-xs);
  }
}
</style>
