<template>
  <BaseDialog
    :model-value="modelValue"
    @update:model-value="$emit('update:modelValue', $event)"
    :title="$t('accident.reportAccident')"
    size="medium"
    @close="handleClose"
  >
    <form @submit.prevent="handleSubmit" class="accident-form">
      <div class="form-group">
        <label for="memberId">{{ $t('accident.member') }}:</label>
        <select 
          id="memberId" 
          :key="`member-select-${availableMembers.length}-${availableMembers.map(m => m.id).join('-')}`"
          :value="localAccident.memberId" 
          @change="handleMemberIdChange"
          class="form-select"
        >
          <option value="">{{ $t('accident.pleaseSelect') }}</option>
          <option 
            v-for="member in availableMembers" 
            :key="member.id" 
            :value="member.id"
          >
            {{ member.firstName }} {{ member.lastName }}
          </option>
        </select>
      </div>
      <div class="form-group">
        <label for="accident">{{ $t('accident.accident') }}:</label>
        <textarea 
          id="accident" 
          v-model="localAccident.accident" 
          required 
          class="form-textarea"
          :placeholder="$t('accident.accidentDescription')"
        ></textarea>
      </div>
      
      <div v-if="accidents.length > 0" class="accidents-list">
        <h4>{{ $t('accident.reportedAccidents') }}</h4>
        <ul>
          <li v-for="accident in accidents" :key="accident.id" class="accident-item">
            <strong>{{ accident.firstName }} {{ accident.lastName }}:</strong> {{ accident.accident }}
          </li>
        </ul>
      </div>
    </form>
    
    <template #footer>
      <button type="button" @click="handleClose" class="btn-secondary">{{ $t('accident.close') }}</button>
      <button type="button" @click="handleSubmit" class="btn-primary" :disabled="!isValid">{{ $t('accident.submit') }}</button>
    </template>
  </BaseDialog>
</template>

<script>
import BaseDialog from './BaseDialog.vue';

export default {
  name: 'AccidentFormDialog',
  components: {
    BaseDialog
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    accident: {
      type: Object,
      default: () => ({ memberId: '', accident: '' })
    },
    members: {
      type: Array,
      default: () => []
    },
    participants: {
      type: Array,
      default: () => []
    },
    accidents: {
      type: Array,
      default: () => []
    }
  },
  emits: ['update:modelValue', 'close', 'submit', 'update:accident'],
  data() {
    return {
      localAccident: { ...this.accident }
    };
  },
  computed: {
    availableMembers() {
      console.log('[AccidentFormDialog] availableMembers computed - start');
      console.log('[AccidentFormDialog] participants:', this.participants);
      console.log('[AccidentFormDialog] members.length:', this.members?.length);
      
      // participants ist ein Array von IDs, nicht von Objekten
      const participantIds = Array.isArray(this.participants) 
        ? (this.participants.length > 0 && typeof this.participants[0] === 'object' 
            ? this.participants.map(p => p.id || p)
            : this.participants)
        : [];
      const participantSet = new Set(participantIds);
      console.log('[AccidentFormDialog] participantIds:', participantIds);
      
      if (!Array.isArray(this.members) || this.members.length === 0) {
        return [];
      }
      
      const filtered = this.members.filter(m => participantSet.has(m.id));
      console.log('[AccidentFormDialog] filtered.length:', filtered.length);
      
      // Alphabetisch sortieren nach Vorname, dann Nachname (entspricht der Anzeige)
      // Erstelle ein neues Array, um Reaktivitätsprobleme zu vermeiden
      const sorted = filtered.slice().sort((a, b) => {
        const firstNameA = (a.firstName || '').trim().toLowerCase();
        const firstNameB = (b.firstName || '').trim().toLowerCase();
        if (firstNameA !== firstNameB) {
          return firstNameA.localeCompare(firstNameB, 'de', { sensitivity: 'base' });
        }
        const lastNameA = (a.lastName || '').trim().toLowerCase();
        const lastNameB = (b.lastName || '').trim().toLowerCase();
        return lastNameA.localeCompare(lastNameB, 'de', { sensitivity: 'base' });
      });
      
      console.log('[AccidentFormDialog] availableMembers computed - end, result.length:', sorted.length);
      console.log('[AccidentFormDialog] First 3 sorted:', sorted.slice(0, 3).map(m => `${m.firstName} ${m.lastName}`));
      return sorted;
    },
    isValid() {
      return this.localAccident.memberId && this.localAccident.accident && this.localAccident.accident.trim() !== '';
    }
  },
  watch: {
    accident: {
      handler(newVal) {
        console.log('[AccidentFormDialog] accident watch triggered:', newVal);
        // Nur aktualisieren, wenn sich wirklich etwas geändert hat (verhindert Endlosschleife)
        if (newVal && (newVal.memberId !== this.localAccident.memberId || newVal.accident !== this.localAccident.accident)) {
          console.log('[AccidentFormDialog] Updating localAccident from prop');
          this.localAccident = { ...newVal };
        } else {
          console.log('[AccidentFormDialog] No update needed (values match)');
        }
      },
      immediate: true
    },
    'localAccident.memberId'(newVal, oldVal) {
      console.log('[AccidentFormDialog] localAccident.memberId changed:', oldVal, '->', newVal);
      if (newVal !== oldVal) {
        // Emit nur bei Änderung der memberId, nicht bei jeder tiefen Änderung
        console.log('[AccidentFormDialog] Emitting update:accident for memberId change');
        this.$emit('update:accident', { ...this.localAccident });
      }
    },
    'localAccident.accident'(newVal, oldVal) {
      console.log('[AccidentFormDialog] localAccident.accident changed:', oldVal?.substring(0, 20), '->', newVal?.substring(0, 20));
      if (newVal !== oldVal) {
        // Emit nur bei Änderung des accident-Textes
        console.log('[AccidentFormDialog] Emitting update:accident for accident text change');
        this.$emit('update:accident', { ...this.localAccident });
      }
    }
  },
  methods: {
    handleClose() {
      console.log('[AccidentFormDialog] handleClose called');
      this.$emit('update:modelValue', false);
      this.$emit('close');
    },
    handleSubmit() {
      console.log('[AccidentFormDialog] handleSubmit called, isValid:', this.isValid);
      if (this.isValid) {
        this.$emit('submit', this.localAccident);
      }
    },
    handleMemberIdChange(event) {
      const newMemberId = event.target.value || '';
      console.log('[AccidentFormDialog] handleMemberIdChange:', this.localAccident.memberId, '->', newMemberId);
      if (newMemberId !== this.localAccident.memberId) {
        this.localAccident.memberId = newMemberId;
        // Emit manuell, ohne Watch zu triggern
        this.$nextTick(() => {
          console.log('[AccidentFormDialog] Emitting update:accident after memberId change');
          this.$emit('update:accident', { ...this.localAccident });
        });
      }
    }
  }
};
</script>

<style scoped>
.accident-form {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.form-group label {
  font-weight: 600;
  color: var(--text-color);
}

.form-select,
.form-textarea {
  width: 100%;
  padding: 0.75rem 0.875rem;
  border: 1px solid var(--border-color);
  border-radius: 10px;
  font-family: inherit;
  background: var(--surface-muted);
  color: var(--text-color);
}

.form-textarea {
  resize: vertical;
  min-height: 100px;
}

.form-select:focus,
.form-textarea:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px var(--primary-light);
}

.accidents-list {
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px solid var(--border-color);
}

.accidents-list h4 {
  margin: 0 0 0.5rem 0;
  font-size: 1rem;
}

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

.accident-item {
  padding: 0.5rem;
  margin-bottom: 0.5rem;
  background: var(--surface-muted);
  border: 1px solid var(--border-color);
  border-radius: 10px;
  font-size: 0.9rem;
}

.btn-primary,
.btn-secondary {
  padding: 0.5rem 1.5rem;
  border: 1px solid transparent;
  border-radius: 10px;
  font-size: 0.875rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
}

.btn-primary {
  background: linear-gradient(135deg, var(--primary-color), var(--primary-hover));
  color: var(--text-on-primary);
}

.btn-primary:hover:not(:disabled) {
  opacity: 0.95;
  transform: translateY(-1px);
}

.btn-primary:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-secondary {
  background: var(--surface-color);
  color: var(--text-color);
  border-color: var(--border-color);
}

.btn-secondary:hover {
  background: var(--surface-muted);
  border-color: var(--primary-soft);
}
</style>
