<template>
  <v-dialog v-model="dialogVisible" max-width="600px" persistent>
    <v-card class="pa-4">
      <v-btn
        icon
        class="position-absolute top-2 right-2"
        @click="fechar"
      >
        <v-icon>mdi-close</v-icon>
      </v-btn>
      
      <v-card-title class="text-h5 font-weight-bold pt-4">
        Adicionar Escala
      </v-card-title>
      <v-card-subtitle class="text-body-1 text-grey-darken-1 pb-4">
        Preencha os dados da nova escala e clique em adicionar.
      </v-card-subtitle>

      <v-card-text>
        <v-row>
          <v-col cols="12" md="6">
            <!-- Nome da Escala -->
            <div class="mb-3 font-weight-medium">Nome da Escala</div>
            <v-text-field
              v-model="form.nome"
              variant="outlined"
              class="mb-4"
              hide-details
            ></v-text-field>
          </v-col>
          
          <v-col cols="12" md="6">
            <!-- Tolerância -->
            <div class="mb-3 font-weight-medium">Tolerância (minutos)</div>
            <v-text-field
              v-model="form.tolerancia"
              type="number"
              variant="outlined"
              class="mb-4"
              hide-details
            ></v-text-field>
          </v-col>
        </v-row>

        <!-- Descrição -->
        <div class="mb-3 font-weight-medium">Descrição</div>
        <v-text-field
          v-model="form.descricao"
          variant="outlined"
          class="mb-4"
          hide-details
        ></v-text-field>

        <v-row>
          <v-col cols="12" md="6">
            <!-- Horário de Entrada -->
            <div class="mb-3 font-weight-medium">Horário de Entrada</div>
            <v-text-field
              v-model="form.entrada"
              type="time"
              variant="outlined"
              class="mb-4"
              hide-details
              prepend-inner-icon="mdi-clock-outline"
            ></v-text-field>
          </v-col>
          
          <v-col cols="12" md="6">
            <!-- Saída para Almoço -->
            <div class="mb-3 font-weight-medium">Saída para Almoço</div>
            <v-text-field
              v-model="form.saida_almoco"
              type="time"
              variant="outlined"
              class="mb-4"
              hide-details
              prepend-inner-icon="mdi-clock-outline"
            ></v-text-field>
          </v-col>
        </v-row>

        <v-row>
          <v-col cols="12" md="6">
            <!-- Retorno do Almoço -->
            <div class="mb-3 font-weight-medium">Retorno do Almoço</div>
            <v-text-field
              v-model="form.retorno_almoco"
              type="time"
              variant="outlined"
              class="mb-4"
              hide-details
              prepend-inner-icon="mdi-clock-outline"
            ></v-text-field>
          </v-col>
          
          <v-col cols="12" md="6">
            <!-- Horário de Saída -->
            <div class="mb-3 font-weight-medium">Horário de Saída</div>
            <v-text-field
              v-model="form.saida_final"
              type="time"
              variant="outlined"
              class="mb-4"
              hide-details
              prepend-inner-icon="mdi-clock-outline"
            ></v-text-field>
          </v-col>
        </v-row>

        <!-- Dias da Semana -->
        <div class="mb-3 font-weight-medium">Dias da Semana</div>
        <div class="mb-4">
          <v-checkbox
            v-model="form.dias_semana"
            :value="0"
            label="Domingo"
            hide-details
            class="d-inline-block mr-4"
          ></v-checkbox>
          <v-checkbox
            v-model="form.dias_semana"
            :value="1"
            label="Segunda"
            hide-details
            class="d-inline-block mr-4"
          ></v-checkbox>
          <v-checkbox
            v-model="form.dias_semana"
            :value="2"
            label="Terça"
            hide-details
            class="d-inline-block mr-4"
          ></v-checkbox>
          <v-checkbox
            v-model="form.dias_semana"
            :value="3"
            label="Quarta"
            hide-details
            class="d-inline-block mr-4"
          ></v-checkbox>
          <v-checkbox
            v-model="form.dias_semana"
            :value="4"
            label="Quinta"
            hide-details
            class="d-inline-block mr-4"
          ></v-checkbox>
          <v-checkbox
            v-model="form.dias_semana"
            :value="5"
            label="Sexta"
            hide-details
            class="d-inline-block mr-4"
          ></v-checkbox>
          <v-checkbox
            v-model="form.dias_semana"
            :value="6"
            label="Sábado"
            hide-details
            class="d-inline-block"
          ></v-checkbox>
        </div>

        <!-- Almoço Automático -->
        <v-checkbox
          v-model="form.almoco_automatico"
          label="Marcação automática de almoço"
          hide-details
          class="mb-1"
        ></v-checkbox>
        <div class="text-grey-darken-1 text-body-2 ml-7 mb-4">
          Se ativado, o sistema marcará automaticamente a saída e retorno do almoço nos horários definidos
        </div>
      </v-card-text>

      <v-card-actions class="pt-0">
        <v-spacer></v-spacer>
        <v-btn variant="outlined" class="mr-3" @click="fechar">Cancelar</v-btn>
        <v-btn color="primary" variant="elevated" @click="salvar" :loading="loading">
          Adicionar
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup>
import { ref, watch, computed } from 'vue';
import { useShiftStore } from '../../stores/shift';

const props = defineProps({
  modelValue: Boolean
});
const emit = defineEmits(['update:modelValue', 'saved']);

const resetForm = () => {
  form.value = {
    nome: '',
    descricao: '',
    tolerancia: '',
    entrada: '',
    saida_almoco: '',
    retorno_almoco: '',
    saida_final: '',
    dias_semana: [1, 2, 3, 4, 5],
    almoco_automatico: false
  };
};

const shiftStore = useShiftStore();
const dialogVisible = ref(props.modelValue);
const loading = ref(false);

// Sincroniza v-model com dialogVisible
watch(() => props.modelValue, (val) => {
  dialogVisible.value = val;
});
watch(dialogVisible, (val) => {
  emit('update:modelValue', val);
});

const form = ref({
  nome: '',
  descricao: '',
  tolerancia: 15,
  entrada: '',
  saida_almoco: '',
  retorno_almoco: '',
  saida_final: '',
  dias_semana: [1, 2, 3, 4, 5],
  almoco_automatico: false
});

const tipoIntervalo = computed(() => {
  return form.value.almoco_automatico ? 'automatic' : 'manual';
});

const mockTimeScheduleIds = {
  0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7
};

const fechar = () => {
  dialogVisible.value = false;
  resetForm(); 
};

const salvar = async () => {
  try {
    loading.value = true;
    const timeScheduleIds = form.value.dias_semana.map(dia => mockTimeScheduleIds[dia]);

    const shiftData = {
      name: form.value.nome,
      description: form.value.descricao,
      tolerance: parseInt(form.value.tolerancia, 10),
      start_time: form.value.entrada,
      end_time: form.value.saida_final,
      interval_start: form.value.saida_almoco || null,
      interval_end: form.value.retorno_almoco || null,
      type_interval: tipoIntervalo.value,
      days: form.value.dias_semana.map(valor => ({ id: mockTimeScheduleIds[valor] })),
      time_schedule_ids: timeScheduleIds
    };

    await shiftStore.createShift(shiftData);
    emit('saved', shiftData); // Notifica o pai
    fechar();      
    resetForm(); 
  } catch (error) {
    console.error('Erro ao salvar a escala:', error);
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.position-absolute { position: absolute; }
.top-2 { top: 8px; }
.right-2 { right: 8px; }
</style>
