<template>
  <v-dialog v-model="isOpen" max-width="900px" @close="closeModal">
    <v-form ref="form" v-model="formValid">
      <v-card class="pa-6 rounded-xl elevation-2 card-modal">
        <v-card-title class="text-h5 font-weight-bold pb-0">
          <span class="text-h5 font-weight-bold pb-0">Adicionar Nova Empresa</span>
        </v-card-title>
        <v-card-text>
          <v-container>
            <v-row>
              <v-col cols="12">
                <h3 class="text-body-1 text-grey-darken-1 pb-4">Dados Básicos</h3>
              </v-col>
              <v-col cols="12">
                <v-text-field v-model="localCompany.name" label="Nome da Empresa *" clearable :rules="[rules.required]" required />
              </v-col>
              <v-col cols="12">
                <v-text-field v-model="localCompany.fantasy_name" label="Nome Fantasia" clearable :rules="[rules.required]" required />
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field v-model="localCompany.cnpj" label="CNPJ *" clearable :rules="[rules.required]" required />
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field v-model="localCompany.type" label="Tipo" clearable :rules="[rules.required]" required />
              </v-col>
              <v-col cols="12">
              <h3 class="text-body-1 text-grey-darken-1 pb-4">Contato</h3>
            </v-col>
              <v-col cols="12" md="6">
                <v-text-field v-model="localCompany.email" label="Email *" clearable required :rules="[rules.required, rules.email]"/>
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field v-model="localCompany.email_sec" label="Email Secundário" clearable :rules="[rules.required, rules.email]" required/>
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field v-model="localCompany.phone" label="Telefone *" clearable required :rules="[rules.required]"  />
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field v-model="localCompany.phone_sec" label="Telefone Secundário" clearable :rules="[rules.required]" required />
              </v-col>
              <v-col cols="12">
                <h3 class="text-body-1 text-grey-darken-1 pb-4">Endereço</h3>
              </v-col>
              <v-col cols="12" md="4">
                <v-text-field v-model="localCompany.cep" label="CEP *" clearable :rules="[rules.required]" required />
              </v-col>
              <v-col cols="12" md="8">
                <v-text-field v-model="localCompany.rua" label="Rua *" clearable :rules="[rules.required]" required/>
              </v-col>
              <v-col cols="12" md="4">
                <v-text-field v-model="localCompany.numero" label="Número *" clearable :rules="[rules.required]" required />
              </v-col>
              <v-col cols="12"md="4">
                <v-text-field v-model="localCompany.bairro" label="Bairro *" clearable :rules="[rules.required]" required/>
              </v-col>
              <v-col cols="12" md="4">
                <v-text-field v-model="localCompany.complemento" label="Complemento" clearable :rules="[rules.required]" required/>
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field v-model="localCompany.estado" label="Estado" clearable :rules="[rules.required]" required/>
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field v-model="localCompany.cidade" label="Cidade" clearable :rules="[rules.required]" required />
              </v-col>
            </v-row>
          </v-container>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn text color="blue-darken-1" @click="closeModal">Cancelar</v-btn>
          <v-btn
            text
            class="text-white salvar-btn"
            :disabled="!formValid"
            @click="validateAndSave"
            :loading="companyStore.loading"
          >
            Salvar
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-form>
  </v-dialog>
</template>

<script setup>
import { ref, watch } from 'vue';
import { useCompanyStore } from '../../stores/company';
import { useAuthStore } from '../../stores/auth';
import {useServiceInstanceStore} from '../../stores/service_instance';

const props = defineProps({
  isModalOpen: Boolean,
});
const emit = defineEmits(['update:isModalOpen', 'company-created']);

const isOpen = ref(false);
const companyStore = useCompanyStore();
const authStore = useAuthStore();
const serviceInstanceStore = useServiceInstanceStore();
const localCompany = ref({
  id: null,
  name: '',
  fantasy_name: '',
  type: '',
  cnpj: '',
  email: '',
  email_sec: '',
  phone: '',
  phone_sec: '',
  estado: '',
  cidade: '',
  bairro: '',
  rua: '',
  numero: '',
  complemento: '',
  cep: '',
  service_instance_id: authStore.service_instance_id || 2,
  parent_id: authStore.userId,
});

const rules = {
  required: (value) => !!value || 'Campo obrigatório',
  email: (value) => /.+@.+\..+/.test(value) || 'E-mail inválido',
};

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


watch(() => props.isModalOpen, (newVal) => {
  isOpen.value = newVal;
  if (newVal) {
    Object.assign(localCompany.value, {
      id: null,
      name: '',
      fantasy_name: '',
      type: '',
      cnpj: '',
      email: '',
      email_sec: '',
      phone: '',
      phone_sec: '',
      estado: '',
      cidade: '',
      bairro: '',
      rua: '',
      numero: '',
      complemento: '',
      cep: '',
      service_instance_id: authStore.service_instance_id || 2,
      parent_id: authStore.userId,
    });
  }
});

watch(isOpen, (newVal) => {
  if (!newVal) {
    emit('update:isModalOpen', false);
  }
});

const closeModal = () => {
  isOpen.value = false;
};

const formatCompanyData = () => {
  const now = new Date().toISOString(); // gera data atual no formato ISO

  return {
    name: localCompany.value.name,
    description: localCompany.value.fantasy_name,
    service_id: 1,
  };
};

const validateAndSave = async () => {
  if (form.value.validate()) {
    try {
      const formattedCompany = formatCompanyData();
      await companyStore.createCompany(localCompany.value);
      await serviceInstanceStore.createServiceInstance(formattedCompany);
      emit('company-created');
      closeModal();
    } catch (error) {
      console.error('Erro ao criar empresa:', error);
    }
  }
};
</script>

<style scoped>
.card-modal {
  background-color: #FFFFFF;
  border-radius: 16px;
}
.salvar-btn {
  background: linear-gradient(to right, #6B4EFF, #2EB6FF);
  border-radius: 999px;
  text-transform: none;
  font-weight: 500;
}
</style>