<template>
  <WidgetShell title="Quick-add contact" icon="mdi-account-plus-outline" :loading="saving" :editing="editing" @refresh="() => {}" @remove="$emit('remove')">
    <v-select v-model="form.type" :items="types" item-title="title" item-value="value" density="compact" label="Type" hide-details class="mb-2" />
    <div v-if="isOrg" class="mb-2"><v-text-field v-model="form.organization" density="compact" :label="form.type === 'work_location' ? 'Location name *' : 'Organization *'" hide-details /></div>
    <div v-else class="two mb-2">
      <v-text-field v-model="form.first_name" density="compact" label="First name" hide-details />
      <v-text-field v-model="form.last_name" density="compact" label="Last name *" hide-details />
    </div>
    <v-text-field v-model="form.email" density="compact" label="Email" hide-details class="mb-2" />
    <v-btn color="primary" size="small" :disabled="!valid" :loading="saving" prepend-icon="mdi-content-save" @click="save">Add contact</v-btn>
    <v-alert v-if="message" type="success" density="compact" class="mt-2">{{ message }}</v-alert>
    <v-alert v-if="error" type="error" density="compact" class="mt-2">{{ error }}</v-alert>
  </WidgetShell>
</template>
<script>
import WidgetShell from './WidgetShell.vue';
import { apiRequest } from '../../services/api';
function blank() { return { type: 'vendor', organization: '', first_name: '', last_name: '', email: '' }; }
export default {
  components: { WidgetShell },
  props: { token: { type: String, required: true }, editing: { type: Boolean, default: false }, config: { type: Object, default: () => ({}) } },
  emits: ['remove'],
  data() {
    return {
      form: blank(), saving: false, message: '', error: '',
      types: [
        { title: 'Vendor', value: 'vendor' }, { title: 'Service provider', value: 'service_provider' },
        { title: 'Employee', value: 'employee' }, { title: 'Contractor', value: 'contractor' },
        { title: 'Work location', value: 'work_location' }, { title: 'Other', value: 'other' }
      ]
    };
  },
  computed: {
    isOrg() { return ['vendor', 'service_provider', 'work_location'].includes(this.form.type); },
    valid() { return this.isOrg ? Boolean(this.form.organization) : Boolean(this.form.last_name); }
  },
  methods: {
    async save() {
      this.saving = true; this.message = ''; this.error = '';
      try {
        const contact = (await (await apiRequest('/api/contacts', this.token, { method: 'POST', body: JSON.stringify(this.form) })).json()).contact;
        this.message = `Added ${contact.organization || [contact.first_name, contact.last_name].filter(Boolean).join(' ')}.`;
        this.form = blank();
      } catch (e) { this.error = e.message; } finally { this.saving = false; }
    }
  }
};
</script>
<style scoped>
.two { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
</style>
