<template>
  <div class="container py-4">
    <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
      <div class="text-start">
        <h3 class="mb-1">Entity Headers</h3>
        <p class="text-muted mb-0">Manage one printable header per entity.</p>
      </div>
      <button
        class="btn btn-primary"
        @click="openCreate"
        :disabled="isAdmin || availableEntitiesForCreate.length === 0"
      >
        Add New Header
      </button>
    </div>

    <div class="alert alert-warning text-start" v-if="isAdmin">
      Admin users can view headers but cannot create, update, or delete them.
    </div>

    <div class="card shadow-sm border-0">
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-striped table-hover mb-0 align-middle">
            <thead class="table-dark">
              <tr>
                <th class="text-start">Entity Name</th>
                <th class="text-start">Logo Image</th>
                <th class="text-start">Header Type</th>
                <th class="text-start">Custom Text</th>
                <th class="text-start">Actions</th>
              </tr>
            </thead>
            <tbody>
              <tr v-if="!loading && rows.length === 0">
                <td colspan="5" class="text-center text-muted py-4">No entities available.</td>
              </tr>
              <tr v-for="row in rows" :key="row.entity_id">
                <td class="text-start">{{ row.entity_name }}</td>
                <td class="text-start">
                  <img
                    v-if="row.header"
                    :src="getLogoUrl(row.header.id)"
                    alt="Entity Header Logo"
                    class="header-logo"
                  />
                  <span v-else class="text-muted">No header</span>
                </td>
                <td class="text-start">
                  {{ row.header ? headerTypeLabel(row.header.header_type) : '-' }}
                </td>
                <td class="text-start">
                  {{ row.header?.custom_text || '-' }}
                </td>
                <td class="text-start">
                  <div class="btn-group btn-group-sm" role="group" v-if="row.header">
                    <button class="btn btn-outline-primary" @click="openEdit(row)" :disabled="isAdmin">Update</button>
                    <button class="btn btn-outline-danger" @click="deleteHeader(row)" :disabled="isAdmin">Delete</button>
                  </div>
                  <button
                    v-else
                    class="btn btn-outline-success btn-sm"
                    @click="openCreate(row.entity_id)"
                    :disabled="isAdmin"
                  >
                    Add Header
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <div v-if="showForm" class="card shadow-sm border-0 mt-4">
      <div class="card-body text-start">
        <h5 class="mb-3">{{ editing ? 'Update Header' : 'Add Header' }}</h5>
        <form @submit.prevent="submitForm">
          <div class="row g-3">
            <div class="col-md-4">
              <label class="form-label">Entity</label>
              <select class="form-select" v-model.number="form.ent_id" :disabled="editing">
                <option :value="null" disabled>Select entity</option>
                <option v-for="entity in entityOptions" :key="entity.entity_id" :value="entity.entity_id">
                  {{ entity.entity_name }}
                </option>
              </select>
            </div>

            <div class="col-md-4">
              <label class="form-label">Header Type</label>
              <select class="form-select" v-model="form.header_type">
                <option value="logo_only">Logo Only</option>
                <option value="logo_entity_name">Logo + Entity name</option>
                <option value="logo_custom_text">Logo + Custom Text</option>
                <option value="entity_name_only">Entity Name Only</option>
                <option value="custom_text_only">Custom Text Only</option>
              </select>
            </div>

            <div class="col-md-4" v-if="requiresCustomText(form.header_type)">
              <label class="form-label">Custom Text</label>
              <input type="text" class="form-control" maxlength="150" v-model.trim="form.custom_text" />
            </div>

            <div class="col-md-8" v-if="requiresLogo(form.header_type) || editing">
              <label class="form-label">Logo Image {{ requiresLogo(form.header_type) && !editing ? '(Required)' : '(Optional)' }}</label>
              <input
                class="form-control"
                type="file"
                accept="image/png,image/jpeg,image/webp,image/gif"
                @change="onFileChange"
              />
              <small class="text-muted d-block mt-1">Max size: 5MB. Supported: PNG, JPG, WEBP, GIF.</small>
            </div>

            <div class="col-md-4" v-if="editing && editRow?.header && editRow.header.logo_url">
              <label class="form-label">Current Logo</label>
              <img :src="getLogoUrl(editRow.header.id)" alt="Current Header Logo" class="header-logo d-block" />
            </div>
          </div>

          <div class="mt-3 d-flex gap-2">
            <button type="submit" class="btn btn-success">{{ editing ? 'Update' : 'Create' }}</button>
            <button type="button" class="btn btn-secondary" @click="closeForm">Cancel</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import { entityHeaderLinks } from '@/cd-links';

export default {
  name: 'EntityHeadersView',
  data() {
    return {
      loading: false,
      rows: [],
      showForm: false,
      editing: false,
      editRow: null,
      form: {
        ent_id: null,
        header_type: 'logo_only',
        custom_text: '',
        logoFile: null
      }
    };
  },
  computed: {
    isAdmin() {
      return this.$store.getters.isAdmin;
    },
    availableEntitiesForCreate() {
      return this.rows.filter((row) => !row.header);
    },
    entityOptions() {
      return this.editing ? this.rows : this.availableEntitiesForCreate;
    }
  },
  methods: {
    requiresLogo(type) {
      return ['logo_only', 'logo_entity_name', 'logo_custom_text'].includes(type);
    },
    requiresCustomText(type) {
      return ['logo_custom_text', 'custom_text_only'].includes(type);
    },
    headerTypeLabel(type) {
      if (type === 'logo_only') return 'Logo Only';
      if (type === 'logo_entity_name') return 'Logo + Entity name';
      if (type === 'logo_custom_text') return 'Logo + Custom Text';
      if (type === 'entity_name_only') return 'Entity Name Only';
      if (type === 'custom_text_only') return 'Custom Text Only';
      return '-';
    },
    getLogoUrl(id) {
      return `${entityHeaderLinks.image}/${id}`;
    },
    async fetchRows() {
      this.loading = true;
      try {
        const res = await this.$store.getters.getAxios.get(entityHeaderLinks.table);
        if (!res.data.isLoggedIn) {
          this.$store.dispatch('loggedOut');
          return;
        }
        this.rows = Array.isArray(res.data.data) ? res.data.data : [];
      } catch (_err) {
        this.$store.commit('addAlert', {
          title: 'Error',
          message: 'Unable to load entity headers.',
          type: 'danger'
        });
      } finally {
        this.loading = false;
      }
    },
    resetForm() {
      this.form = {
        ent_id: null,
        header_type: 'logo_only',
        custom_text: '',
        logoFile: null
      };
    },
    openCreate(preselectedEntityId = null) {
      this.editing = false;
      this.editRow = null;
      this.resetForm();
      this.form.ent_id = preselectedEntityId || (this.availableEntitiesForCreate[0]?.entity_id ?? null);
      this.showForm = true;
    },
    openEdit(row) {
      this.editing = true;
      this.editRow = row;
      this.resetForm();
      this.form.ent_id = row.entity_id;
      this.form.header_type = row.header.header_type;
      this.form.custom_text = row.header.custom_text || '';
      this.showForm = true;
    },
    closeForm() {
      this.showForm = false;
      this.editing = false;
      this.editRow = null;
      this.resetForm();
    },
    onFileChange(event) {
      const file = event?.target?.files?.[0] || null;
      this.form.logoFile = file;
    },
    buildPayload() {
      const payload = new FormData();
      payload.append('ent_id', String(this.form.ent_id));
      payload.append('header_type', this.form.header_type);
      payload.append('custom_text', this.requiresCustomText(this.form.header_type) ? this.form.custom_text : '');
      if (this.form.logoFile) {
        payload.append('logo', this.form.logoFile);
      }
      return payload;
    },
    validateForm() {
      if (!this.form.ent_id) {
        this.$store.commit('addAlert', {
          title: 'Validation Error',
          message: 'Please select an entity.',
          type: 'danger'
        });
        return false;
      }

      if (this.requiresCustomText(this.form.header_type) && !this.form.custom_text) {
        this.$store.commit('addAlert', {
          title: 'Validation Error',
          message: 'Please provide custom text for this header type.',
          type: 'danger'
        });
        return false;
      }

      if (!this.editing && this.requiresLogo(this.form.header_type) && !this.form.logoFile) {
        this.$store.commit('addAlert', {
          title: 'Validation Error',
          message: 'Logo image is required to create a header.',
          type: 'danger'
        });
        return false;
      }

      return true;
    },
    async submitForm() {
      if (this.isAdmin) {
        return;
      }

      if (!this.validateForm()) {
        return;
      }

      try {
        const payload = this.buildPayload();
        const endpoint = this.editing ? entityHeaderLinks.put : entityHeaderLinks.post;
        const request = this.editing
          ? this.$store.getters.getAxios.put(endpoint, payload)
          : this.$store.getters.getAxios.post(endpoint, payload);

        const res = await request;
        this.$store.commit('addAlert', {
          title: res.data.title,
          message: res.data.msg,
          type: res.data.success ? 'success' : 'danger'
        });

        if (res.data.success) {
          this.closeForm();
          await this.fetchRows();
        }
      } catch (_err) {
        this.$store.commit('addAlert', {
          title: 'Error',
          message: this.editing ? 'Unable to update header.' : 'Unable to create header.',
          type: 'danger'
        });
      }
    },
    async deleteHeader(row) {
      if (this.isAdmin) {
        return;
      }

      const confirmed = window.confirm(`Delete header for ${row.entity_name}?`);
      if (!confirmed) return;

      try {
        const res = await this.$store.getters.getAxios.delete(entityHeaderLinks.delItem, {
          data: { ent_id: row.entity_id }
        });

        this.$store.commit('addAlert', {
          title: res.data.title,
          message: res.data.msg,
          type: res.data.success ? 'success' : 'danger'
        });

        if (res.data.success) {
          await this.fetchRows();
        }
      } catch (_err) {
        this.$store.commit('addAlert', {
          title: 'Error',
          message: 'Unable to delete header.',
          type: 'danger'
        });
      }
    }
  },
  async mounted() {
    await this.fetchRows();
  }
};
</script>

<style scoped>
.header-logo {
  width: 96px;
  height: 56px;
  object-fit: contain;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  background: #fff;
  padding: 4px;
}
</style>
