<template>
  <v-dialog v-model="isOpen" max-width="900px" @close="closeModal">
    <v-form @submit="handleSave">
      <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">{{ isEditMode ? 'Editar Empresa' : '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 required />
              </v-col>
              <v-col cols="12">
                <v-text-field v-model="localCompany.fantasy_name" label="Nome Fantasia" clearable />
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field v-model="localCompany.cnpj" label="CNPJ *" clearable required />
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field v-model="localCompany.type" label="Tipo" clearable />
              </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 />
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field v-model="localCompany.email_sec" label="Email Secundário" clearable />
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field v-model="localCompany.phone" label="Telefone *" clearable required />
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field v-model="localCompany.phone_sec" label="Telefone Secundário" clearable />
              </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 />
              </v-col>
              <v-col cols="12" md="8">
                <v-text-field v-model="localCompany.rua" label="Rua *" clearable />
              </v-col>
              <v-col cols="12" md="4">
                <v-text-field v-model="localCompany.numero" label="Número *" clearable />
              </v-col>
              <v-col cols="12"md="4">
                <v-text-field v-model="localCompany.bairro" label="Bairro *" clearable />
              </v-col>
              <v-col cols="12" md="4">
                <v-text-field v-model="localCompany.complemento" label="Complemento" clearable />
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field v-model="localCompany.estado" label="Estado" clearable />
              </v-col>
              <v-col cols="12" md="6">
                <v-text-field v-model="localCompany.cidade" label="Cidade" clearable />
              </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
            type="submit"
            text
            class="text-white salvar-btn"
            :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,
  isEditMode: Boolean,
  modalCompany: Object,
});
const emit = defineEmits(['update:isModalOpen', 'company-updated']);
const companyStore = useCompanyStore();
const authStore = useAuthStore();
const isOpen = ref(false);
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 resetLocalCompany = () => {
  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,
    parent_id: authStore.userId,
  };
};
const loadCompanyData = async () => {
  try {
    const data = await companyStore.fetchCompanyById(props.modalCompany.id);
    if (data) {
      Object.assign(localCompany.value, data);
    }
  } catch (error) {
    console.error('Erro ao carregar dados:', error);
  }
};
watch(() => props.isModalOpen, (newVal) => {
  isOpen.value = newVal;
  if (newVal) {
    if (props.isEditMode) {
      loadCompanyData();
    } else {
      resetLocalCompany();
    }
  }
});
watch(isOpen, (newVal) => {
  if (!newVal) {
    emit('update:isModalOpen', false);
  }
});
const closeModal = () => {
  isOpen.value = false;
};
const handleSave = async (e) => {
  e.preventDefault(); // Isso é um seguro extra
  try {
    const companyData = { ...localCompany.value };
    
    if (!props.isEditMode) {
      delete companyData.id;
      console.log('Dados da empresa:', companyData);
      await companyStore.createCompany(companyData);
    } else {
      await companyStore.updateCompany(companyData.id, companyData);
    }
    emit('company-updated');
    closeModal();
  } catch (error) {
    console.error('Erro ao salvar 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>