<template>
  <v-dialog v-model="isOpen" max-width="500px" @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">Adicionar Nova Empresa</span>
        </v-card-title>
        <v-card-text>
          <v-container>
            <v-row>
              <v-text class="text-h7">Dados básicos</v-text>
              <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">
                <v-text-field
                  v-model="localCompany.cnpj"
                  label="CNPJ *"
                  clearable
                  :rules="[rules.required]"
                  required
                />
              </v-col>
              <v-col cols="12">
                <v-text-field
                  v-model="localCompany.type"
                  label="Tipo *"
                  clearable
                  :rules="[rules.required]"
                  required
                />
              </v-col>
              <v-text class="text-h7">Contato</v-text>
              <v-col cols="12">
                <v-text-field
                  v-model="localCompany.email"
                  label="Email *"
                  clearable
                  :rules="[rules.required, rules.email]"
                  required
                />
              </v-col>
              <v-col cols="12">
                <v-text-field
                  v-model="localCompany.phone"
                  label="Telefone *"
                  clearable
                  :rules="[rules.required]"
                  required
                />
              </v-col>
              <v-text class="text-h7">Endereço</v-text>
              <v-col cols="12">
                <v-text-field
                  v-model="localCompany.cep"
                  label="CEP *"
                  clearable
                  :rules="[rules.required]"
                  required
                />
              </v-col>
              <v-col cols="12">
                <v-text-field
                  v-model="localCompany.rua"
                  label="Rua *"
                  clearable
                  :rules="[rules.required]"
                  required
                />
              </v-col>
              <v-col cols="12">
                <v-text-field
                  v-model="localCompany.numero"
                  label="Número *"
                  clearable
                  :rules="[rules.required]"
                  required
                />
              </v-col>
              <v-col cols="12">
                <v-text-field
                  v-model="localCompany.bairro"
                  label="Bairro *"
                  clearable
                  :rules="[rules.required]"
                  required
                />
              </v-col>
              <v-col cols="12">
                <v-text-field
                  v-model="localCompany.estado"
                  label="Estado *"
                  clearable
                  :rules="[rules.required]"
                  required
                />
              </v-col>
              <v-col cols="12">
                <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';

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

const isOpen = ref(false);
const companyStore = useCompanyStore();
const authStore = useAuthStore();

const localCompany = ref({
  name: '',
  fantasy_name: '',
  type: '',
  cnpj: '',
  email: '',
  phone: '',
  estado: '',
  cidade: '',
  bairro: '',
  rua: '',
  numero: '',
  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, {
      name: '',
      fantasy_name: '',
      type: '',
      cnpj: '',
      email: '',
      phone: '',
      estado: '',
      cidade: '',
      bairro: '',
      rua: '',
      numero: '',
      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 validateAndSave = async () => {
  if (form.value.validate()) {
    try {
      await companyStore.createCompany(localCompany.value);
      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>