<template>
  <div class="table-container">
    <!-- Search Bar -->
    <div class="search-container">
      <input
          v-model="searchQuery"
          type="text"
          placeholder="Search..."
          class="search-input"
      />
    </div>

    <!-- Loading State -->
    <div v-if="loading" class="loading">
      Loading...
    </div>

    <!-- Error State -->
    <div v-else-if="error" class="error">
      Error: {{ error }}
    </div>

    <!-- Table -->
    <div v-else class="table-wrapper">
      <table class="data-table">
        <thead>
        <tr>
          <th v-for="column in columns" :key="column.key" class="table-header">
            {{ column.label }}
          </th>
        </tr>
        </thead>
        <tbody>
        <tr v-if="filteredData.length === 0" class="no-data">
          <td :colspan="columns.length" class="no-data-cell">
            {{ searchQuery ? 'No results found' : 'No data available' }}
          </td>
        </tr>
        <tr v-else v-for="(item, index) in filteredData" :key="index" class="table-row">
          <td v-for="column in columns" :key="column.key" class="table-cell">
            {{ getCellValue(item, column) }}
          </td>
        </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
export default {
  name: 'DataTable',
  props: {
    // Callback function that returns array of objects
    dataSource: {
      type: Function,
      required: true
    },
    // Array of column configurations
    // Each column should have: { key: 'fieldName', label: 'Display Name', formatter: fn (optional) }
    columns: {
      type: Array,
      required: true,
      validator(columns) {
        return columns.every(col => col.key && col.label);
      }
    },
    // Fields to search in (if not provided, searches all column keys)
    searchFields: {
      type: Array,
      default: () => []
    },
    // Auto-load data on mount
    autoLoad: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      data: [],
      loading: false,
      error: null,
      searchQuery: ''
    };
  },
  computed: {
    filteredData() {
      if (!this.searchQuery.trim()) {
        return this.data;
      }

      const query = this.searchQuery.toLowerCase().trim();
      const fieldsToSearch = this.searchFields.length > 0
          ? this.searchFields
          : this.columns.map(col => col.key);

      return this.data.filter(item => {
        return fieldsToSearch.some(field => {
          const value = this.getNestedValue(item, field);
          return value && value.toString().toLowerCase().includes(query);
        });
      });
    }
  },
  mounted() {
    if (this.autoLoad) {
      this.loadData();
    }
  },
  methods: {
    async loadData() {
      this.loading = true;
      this.error = null;

      try {
        const result = await this.dataSource();
        if (Array.isArray(result)) {
          this.data = result;
        } else {
          throw new Error('Data source must return an array');
        }
      } catch (err) {
        this.error = err.message || 'Failed to load data';
        this.data = [];
      } finally {
        this.loading = false;
      }
    },

    // Get nested object values using dot notation (e.g., 'user.profile.name')
    getNestedValue(obj, path) {
      return path.split('.').reduce((current, key) => {
        return current && current[key] !== undefined ? current[key] : null;
      }, obj);
    },

    // Get cell value with optional formatting
    getCellValue(item, column) {
      const rawValue = this.getNestedValue(item, column.key);

      if (column.formatter && typeof column.formatter === 'function') {
        return column.formatter(rawValue, item);
      }

      return rawValue !== null && rawValue !== undefined ? rawValue : '';
    },

    // Public method to refresh data
    refresh() {
      this.loadData();
    },

    // Public method to clear search
    clearSearch() {
      this.searchQuery = '';
    }
  }
};
</script>

<style scoped>
.table-container {
  width: 100%;
}

.search-container {
  margin-bottom: 16px;
}

.search-input {
  width: 100%;
  max-width: 300px;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.2s;
}

.search-input:focus {
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.loading, .error {
  padding: 20px;
  text-align: center;
  font-size: 14px;
}

.loading {
  color: #666;
}

.error {
  color: #dc3545;
  background-color: #f8d7da;
  border: 1px solid #f5c6cb;
  border-radius: 4px;
}

.table-wrapper {
  overflow-x: auto;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  background-color: white;
}

.table-header {
  background-color: #f8f9fa;
  color: #495057;
  font-weight: 600;
  padding: 12px 16px;
  text-align: left;
  border-bottom: 2px solid #dee2e6;
  position: sticky;
  top: 0;
}

.table-row {
  transition: background-color 0.2s;
}

.table-row:hover {
  background-color: #f8f9fa;
}

.table-row:nth-child(even) {
  background-color: #fdfdfd;
}

.table-cell {
  padding: 12px 16px;
  border-bottom: 1px solid #dee2e6;
  vertical-align: top;
}

.no-data-cell {
  padding: 40px 16px;
  text-align: center;
  color: #6c757d;
  font-style: italic;

}

/* Responsive design */
@media (max-width: 768px) {
  .search-input {
    max-width: 100%;
  }

  .table-header,
  .table-cell {
    padding: 8px 12px;
    font-size: 14px;
  }
}
</style>