<template>
  <div>
    <div v-if="!isOnline || hasPendingActions" class="alert offline-indicator" :class="{
      'alert-error': !isOnline,
      'alert-warning': isOnline && hasPendingActions
    }" role="status">
      <div class="alert-content">
        <svg class="icon" aria-hidden="true">
          <use :xlink:href="!isOnline ? '#icon-wifi-off' : '#icon-sync'" />
        </svg>
        <span v-if="!isOnline" class="status-text">
          You are currently offline. Changes will be saved locally.
        </span>
        <span v-else class="status-text">
          Syncing {{ pendingActionCount }} pending {{ pendingActionCount === 1 ? 'change' : 'changes' }}...
        </span>
      </div>
      <button v-if="hasPendingActions" class="btn btn-sm btn-neutral" @click="showPendingActionsModal = true">
        View Changes
      </button>
    </div>

    <div v-if="showPendingActionsModal" class="modal-backdrop open" @click.self="showPendingActionsModal = false">
      <div class="modal-container" ref="pendingActionsModalRef" role="dialog" aria-modal="true"
        aria-labelledby="pendingActionsTitle">
        <div class="modal-header">
          <h3 id="pendingActionsTitle">Pending Changes</h3>
          <button class="close-button" @click="showPendingActionsModal = false" aria-label="Close">
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-close" />
            </svg>
          </button>
        </div>
        <div class="modal-body">
          <ul v-if="pendingActions.length" class="item-list">
            <li v-for="action in pendingActions" :key="action.id" class="list-item">
              <div class="list-item-content">
                <div class="action-info">
                  <span class="item-text">{{ getActionLabel(action) }}</span>
                  <small class="text-caption">{{ new Date(action.timestamp).toLocaleString() }}</small>
                </div>
                <button class="btn btn-sm btn-error" @click="removePendingAction(action.id)"
                  title="Remove this pending action">
                  <svg class="icon" aria-hidden="true">
                    <use xlink:href="#icon-trash" />
                  </svg>
                </button>
              </div>
            </li>
          </ul>
          <p v-else class="empty-state">No pending changes.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-primary" @click="showPendingActionsModal = false">Close</button>
        </div>
      </div>
    </div>

    <!-- Conflict Resolution Dialog -->
    <ConflictResolutionDialog v-model="offlineStore.showConflictDialog" :conflict-data="offlineStore.currentConflict"
      @resolve="offlineStore.handleConflictResolution" />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useNetwork, onClickOutside } from '@vueuse/core';
import { useOfflineStore } from '@/stores/offline';
import type { OfflineAction } from '@/stores/offline';
import ConflictResolutionDialog from '@/components/ConflictResolutionDialog.vue';

const offlineStore = useOfflineStore();
const showPendingActionsModal = ref(false);
const pendingActionsModalRef = ref<HTMLElement | null>(null);

const { isOnline } = useNetwork();

const {
  pendingActions,
  hasPendingActions,
  pendingActionCount,
} = offlineStore;

onClickOutside(pendingActionsModalRef, () => {
  showPendingActionsModal.value = false;
});

const removePendingAction = (actionId: string) => {
  offlineStore.pendingActions = offlineStore.pendingActions.filter(a => a.id !== actionId);
};

const getActionLabel = (action: OfflineAction) => {
  const data = action.payload as { title?: string; name?: string;[key: string]: unknown };
  const itemTitle = data.title || data.name || (typeof data === 'string' ? data : 'Untitled Item');

  switch (action.type) {
    case 'create_list':
      return `Create List: ${itemTitle}`;
    case 'update_list':
      return `Update List: ${itemTitle}`;
    case 'delete_list':
      return `Delete List: ${itemTitle}`;
    case 'create_list_item':
      return `Add Item: ${itemTitle}`;
    case 'update_list_item':
      return `Update Item: ${itemTitle}`;
    case 'delete_list_item':
      return `Delete Item: ${itemTitle}`;
    default:
      return `Unknown action: ${action.type} for ${itemTitle}`;
  }
};
</script>

<style scoped>
.offline-indicator {
  position: fixed;
  bottom: 1rem;
  right: 1rem;
  z-index: 1000;
  max-width: 400px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
  padding: 0.75rem 1rem;
  border-radius: 0.5rem;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
}

.alert-content {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.icon {
  width: 1.25rem;
  height: 1.25rem;
  flex-shrink: 0;
}

.status-text {
  font-weight: 500;
}

.text-caption {
  font-size: 0.85rem;
  color: var(--dark);
  opacity: 0.7;
}

.item-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.list-item {
  border-bottom: 1px solid var(--border-color);
}

.list-item:last-child {
  border-bottom: none;
}

.list-item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem 1rem;
  gap: 1rem;
}

.action-info {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.item-text {
  font-weight: 500;
}

.empty-state {
  text-align: center;
  color: var(--text-muted);
  padding: 2rem;
}

.btn-error {
  padding: 0.25rem;
  min-width: auto;
}

.btn-error .icon {
  width: 1rem;
  height: 1rem;
}
</style>