<template>
  <v-dialog :model-value="modalValue" @update:model-value="updateModalValue" max-width="600px">
    <v-form ref="form" v-model="formValid">
      <v-card class="pa-6 rounded-xl elevation-2 card-modal">
        <v-card-title class="pb-1">
          <span class="modal-title">Adicionar Feriado</span>
        </v-card-title>

        <v-card-subtitle class="modal-subtitle mb-6">
          Gerencie os feriados e dias especiais do sistema
        </v-card-subtitle>

        <v-card-text>
          <v-container>
            <v-row>
              <v-col cols="12">
                <div class="form-group">
                  <label class="form-label">Nome do Feriado</label>
                  <v-text-field v-model="localHoliday.name" variant="outlined" hide-details="auto" :rules="[rules.required]" clearable />
                </div>
              </v-col>

              <v-col cols="12">
                <div class="form-group">
                  <label class="form-label">Data</label>
                  <v-text-field v-model="localHoliday.date" type="date" variant="outlined" hide-details="auto" :rules="[rules.required]" clearable />
                </div>
              </v-col>

              <v-col cols="12" md="6">
                <div class="form-group">
                  <label class="form-label">Tipo</label>
                  <v-select v-model="localHoliday.type" :items="['Nacional', 'Estadual', 'Ponto Facultativo', 'Outro']" variant="outlined" hide-details="auto" />
                </div>
              </v-col>

              <v-col cols="12" md="6">
                <div class="form-group">
                  <label class="form-label">Adicional Hora Extra</label>
                  <v-select v-model="localHoliday.adicional_he" :items="['0%', '25%','50%','75%', '100%']" variant="outlined" hide-details="auto" />
                </div>
              </v-col>

              <v-col cols="12">
                <v-checkbox v-model="localHoliday.recorrente" label="Feriado recorrente (repete todos os anos)" color="primary" />
              </v-col>
            </v-row>
          </v-container>
        </v-card-text>
        <v-card-actions>
          <v-btn text 
          class="cancel-btn" @click="$emit('cancel')">Cancelar</v-btn>
          <v-btn color="primary"  @click="handleSave" :disabled="!formValid" class="add-btn">Adicionar</v-btn>
        </v-card-actions>
      </v-card>
    </v-form>
  </v-dialog>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import { useHolidayStore } from '../../stores/holiday';
import { useAuthStore } from '../../stores/auth';

const props = defineProps({
  modalValue: {
    type: Boolean,
    required: true
  }
});

const emit = defineEmits(['update:modalValue', 'save']);

const holidayStore = useHolidayStore();
const authStore = useAuthStore();

// Objeto de feriado padrão
const defaultHoliday = {
  name: '',
  type: '',
  date: '',
  estado: '',
  municipio: '',
  recorrente: true,
  adicional_he: 0,
  parent_id: authStore.userId,
  service_instance_id: authStore.service_instance_id || 2
};
const rules = {
  required: (value) => !!value || 'Campo obrigatório'
};

const form = ref(null);
const formValid = ref(false);

// Estado local do feriado
const localHoliday = ref({...defaultHoliday});

// Função para atualizar o estado do modal
const updateModalValue = (value) => {
  console.log('Dialog emitindo update:model-value:', value);
  emit('update:modalValue', value);
  
  if (!value) {
    resetLocalHoliday();
  }
};

// Resetar o feriado para o estado inicial
const resetLocalHoliday = () => {
  console.log('Resetando formulário de criação para valores padrão');
  for (const key in defaultHoliday) {
    localHoliday.value[key] = defaultHoliday[key];
  }
};

// Observar mudanças no modalValue
watch(() => props.modalValue, (newVal, oldVal) => {
  console.log(`CreateModal - modalValue mudou de ${oldVal} para ${newVal}`);
  
  if (newVal) {
    // Modal está sendo aberto - resetar formulário
    resetLocalHoliday();
  }
});

// Fechar o modal e limpar os dados
const closeModal = () => {
  console.log('Botão cancelar clicado - fechando modal de criação');
  // Emitir evento para fechar o modal
  emit('update:modalValue', false);
  // Resetar dados
  resetLocalHoliday();
};

// Salvar o novo feriado
const handleSave = async () => {
  const { valid } = await form.value.validate();
  if (!valid) {
    console.warn('Formulário inválido');
    return;
  }

  try {
    const data = {
      ...localHoliday.value,
      adicional_he: parseInt(localHoliday.value.adicional_he) || 0,
      parent_id: authStore.userId,
      date: typeof localHoliday.value.date === 'string'
        ? localHoliday.value.date
        : new Date(localHoliday.value.date).toISOString().split('T')[0],
      service_instance_id: authStore.service_instance_id
    };

    emit('save', data); // Quem chama decide quando fechar o modal
  } catch (error) {
    console.error('Erro ao salvar feriado:', error);
  }
};

// Inicialização do componente
onMounted(() => {
  console.log('Modal de criação montado - modalValue:', props.modalValue);
  if (props.modalValue) {
    resetLocalHoliday();
  }
});
</script>

<style scoped>
.v-card-text {
  padding-bottom: 0px !important; /* ou 0px */
}

.form-group {
  display: flex;
  flex-direction: column;
  margin-bottom: 16px;
}

.form-label {
  display: block;
  font-size: 18px;
  font-weight: 500;
  color: #1e293b;
  margin-bottom: 4px;
  margin-left: 4px;
}


.cancel-btn {
  border-radius: 8px;
  font-weight: 500;
  padding: 0 20px;
  height: 44px; 
  color: #1e293b;
  border: 1px solid #d1d5db;
  background-color: #fff;
}

.add-btn {
  border-radius: 8px;
  font-weight: 500;
  padding: 0 20px ;
  height: 44px;
  color: white !important;
  background-color: #2563eb;
}

.v-card-title,
.v-card-subtitle {
  padding-left: 24px !important;
  padding-right: 24px !important;
}
.modal-title {
  font-size: 25px;
  font-weight: 600;
  color: #1e293b;
}

.modal-subtitle {
  font-size: 14px;
  color: #64748b; /* Cinza mais escuro */

}
/* Borda azul ao passar o mouse */
::v-deep(.v-field.v-field--variant-outlined:hover) {
  border-color: #2eb6ff79 !important;
  box-shadow: 0 0 0 1px #54d2ff6b !important;
}


.card-modal {
  background-color: #ffffff;
  border-radius: 16px;
  max-height: 70 vh;  
  overflow-y: auto;
}

.salvar-btn {
  background: linear-gradient(to right, #6b4eff, #2eb6ff);
  border-radius: 999px;
  text-transform: none;
  font-weight: 500;
}

</style>