<template>
  <BaseDialog
    :model-value="modelValue"
    @update:model-value="$emit('update:modelValue', $event)"
    :title="$t('courtDrawing.title')"
    size="large"
    width="92vw"
    :max-width="1500"
    :close-on-overlay="false"
    @close="handleClose"
  >
    <div class="drawing-dialog-body">
      <div class="drawing-tool-shell">
        <CourtDrawingTool
          ref="drawingTool"
          :drawing-data="initialDrawingData"
          :allow-image-upload="false"
          @update-drawing-data="handleDrawingDataUpdate"
          @update-fields="handleFieldsUpdate"
        />
      </div>

      <div v-if="showDiaryFields" class="diary-fields">
        <label v-if="showDurationFields" class="diary-field">
          <span>{{ $t('courtDrawing.durationText') }}</span>
          <input
            type="text"
            v-model="diaryFields.durationText"
            :placeholder="$t('courtDrawing.durationTextPlaceholder')"
            @input="calculateDurationFromText"
          />
        </label>
        <label v-if="showDurationFields" class="diary-field">
          <span>{{ $t('courtDrawing.durationMinutes') }}</span>
          <input type="number" min="0" :value="diaryFields.duration" readonly />
        </label>
        <label v-if="showGroupSelect" class="diary-field">
          <span>{{ $t('courtDrawing.group') }}</span>
          <select v-model="diaryFields.groupId">
            <option value="">{{ $t('courtDrawing.selectGroup') }}</option>
            <option v-for="group in groups" :key="group.id" :value="String(group.id)">
              {{ group.name }}
            </option>
          </select>
        </label>
      </div>
    </div>
    
    <template #footer>
      <button class="btn-secondary" @click="handleClose">{{ $t('courtDrawing.cancel') }}</button>
      <button 
        class="btn-primary" 
        @click="handleOk" 
        :disabled="!isValid"
      >
        {{ $t('courtDrawing.ok') }}
      </button>
    </template>
  </BaseDialog>
</template>

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

export default {
  name: 'CourtDrawingDialog',
  components: {
    BaseDialog,
    CourtDrawingTool
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    initialDrawingData: {
      type: Object,
      default: null
    },
    initialCode: {
      type: String,
      default: null
    },
    initialName: {
      type: String,
      default: null
    },
    initialDescription: {
      type: String,
      default: null
    },
    showDiaryFields: {
      type: Boolean,
      default: false
    },
    showDurationFields: {
      type: Boolean,
      default: false
    },
    showGroupSelect: {
      type: Boolean,
      default: false
    },
    groups: {
      type: Array,
      default: () => []
    },
    initialDuration: {
      type: [Number, String, null],
      default: null
    },
    initialDurationText: {
      type: String,
      default: ''
    },
    initialGroupId: {
      type: [String, Number, null],
      default: ''
    }
  },
  emits: ['update:modelValue', 'close', 'ok'],
  data() {
    return {
      currentDrawingData: null,
      currentFields: null,
      diaryFields: {
        duration: null,
        durationText: '',
        groupId: ''
      }
    };
  },
  computed: {
    isValid() {
      // Mindestens Aufschlag und Zielposition müssen gesetzt sein
      const drawingValid = this.currentDrawingData && 
             this.currentDrawingData.selectedStartPosition && 
             this.currentDrawingData.strokeType && 
             this.currentDrawingData.spinType && 
             this.currentDrawingData.targetPosition;
      if (!drawingValid) return false;
      if (this.showGroupSelect) {
        return Boolean(this.diaryFields.groupId);
      }
      return true;
    }
  },
  watch: {
    initialDrawingData: {
      handler(newVal) {
        if (newVal) {
          this.currentDrawingData = { ...newVal };
        }
      },
      deep: true,
      immediate: true
    },
    modelValue(newVal) {
      // Wenn Dialog geöffnet wird, stelle sicher dass Tool neu gezeichnet wird
      if (newVal) {
        // Setze initiale Felder, falls vorhanden
        if (this.initialCode || this.initialName || this.initialDescription) {
          this.currentFields = {
            code: this.initialCode || '',
            name: this.initialName || '',
            description: this.initialDescription || ''
          };
        }
        this.diaryFields = {
          duration: this.initialDuration ?? null,
          durationText: this.initialDurationText || '',
          groupId: this.initialGroupId !== null && this.initialGroupId !== undefined ? String(this.initialGroupId) : ''
        };
        if (this.diaryFields.durationText) {
          this.calculateDurationFromText();
        }
        this.$nextTick(() => {
          // Warte bis der Dialog vollständig gerendert ist
          setTimeout(() => {
            if (this.$refs.drawingTool && this.$refs.drawingTool.drawCourt) {
              this.$refs.drawingTool.drawCourt(true);
            }
          }, 100);
        });
      } else {
        // Dialog wird geschlossen - Felder zurücksetzen
        this.currentFields = null;
        this.diaryFields = {
          duration: null,
          durationText: '',
          groupId: ''
        };
      }
    }
  },
  mounted() {
    // Wenn Dialog bereits beim Mount geöffnet ist
    if (this.modelValue) {
      this.$nextTick(() => {
        setTimeout(() => {
          if (this.$refs.drawingTool && this.$refs.drawingTool.drawCourt) {
            this.$refs.drawingTool.drawCourt(true);
          }
        }, 100);
      });
    }
  },
  methods: {
    calculateDurationFromText() {
      const input = this.diaryFields.durationText;
      if (!input || !input.trim()) {
        this.diaryFields.duration = null;
        return;
      }

      const normalized = input.replace(/\s+/g, '').replace(/\*/g, 'x');
      let total = 0;

      for (const part of normalized.split('+')) {
        if (!part) continue;
        if (part.includes('x')) {
          const [count, minutes] = part.split('x').map(Number);
          if (Number.isFinite(count) && Number.isFinite(minutes)) {
            total += count * minutes;
          }
        } else {
          const minutes = Number(part);
          if (Number.isFinite(minutes)) {
            total += minutes;
          }
        }
      }

      this.diaryFields.duration = total > 0 ? total : null;
    },
    handleDrawingDataUpdate(data) {
      this.currentDrawingData = { ...data };
    },
    handleFieldsUpdate(fields) {
      this.currentFields = { ...fields };
    },
    handleClose() {
      this.$emit('update:modelValue', false);
      this.$emit('close');
    },
    handleOk() {
      if (this.isValid && this.currentDrawingData) {
        // Sammle alle Daten zusammen
        const result = {
          drawingData: { ...this.currentDrawingData },
          fields: this.currentFields ? {
            ...this.currentFields,
            duration: this.diaryFields.duration,
            durationText: this.diaryFields.durationText,
            groupId: this.diaryFields.groupId
          } : {
            duration: this.diaryFields.duration,
            durationText: this.diaryFields.durationText,
            groupId: this.diaryFields.groupId
          },
          code: this.currentDrawingData.code || (this.currentFields ? this.currentFields.code : ''),
          name: this.currentFields ? this.currentFields.name : '',
          description: this.currentFields ? this.currentFields.description : ''
        };
        this.$emit('ok', result);
        this.handleClose();
      }
    }
  }
};
</script>

<style scoped>
:deep(.dialog-body) {
  overflow: hidden;
}

.drawing-dialog-body {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  height: min(78vh, calc(100vh - 170px));
  min-height: 0;
}

.drawing-tool-shell {
  flex: 1;
  min-height: 0;
}

.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);
}

.diary-fields {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
  gap: 0.75rem;
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px solid var(--border-color);
}

.diary-field {
  display: flex;
  flex-direction: column;
  gap: 0.35rem;
  color: var(--text-color);
  font-size: 0.875rem;
  font-weight: 600;
}

.diary-field input,
.diary-field select {
  width: 100%;
}
</style>
