<template>
  <div class="contact-management">
    <div class="card">
      <div class="flex justify-between items-center mb-4">
        <div class="font-semibold text-xl">Kontakte</div>
        <Button label="Neuer Kontakt" icon="pi pi-plus" @click="openNewContactDialog" />
      </div>

      <DataTable
        v-model:filters="filters"
        :value="contacts"
        :loading="loading"
        :paginator="true"
        :rows="10"
        :rowsPerPageOptions="[10, 25, 50, 100]"
        :rowHover="true"
        :globalFilterFields="['companyName', 'city', 'email', 'phone']"
        sortField="companyName"
        :sortOrder="1"
        dataKey="id"
        filterDisplay="menu"
        showGridlines
        paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
        currentPageReportTemplate="Zeige {first} bis {last} von {totalRecords} Einträgen"
      >
        <template #header>
          <div class="flex justify-between flex-wrap gap-2">
            <div class="flex gap-2">
              <Button
                label="Alle"
                :outlined="typeFilter !== 'all'"
                @click="filterByType('all')"
                size="small"
              />
              <Button
                label="Debitoren"
                :outlined="typeFilter !== 'debtor'"
                @click="filterByType('debtor')"
                size="small"
              />
              <Button
                label="Kreditoren"
                :outlined="typeFilter !== 'creditor'"
                @click="filterByType('creditor')"
                size="small"
              />
            </div>
            <IconField>
              <InputIcon>
                <i class="pi pi-search" />
              </InputIcon>
              <InputText
                v-model="filters['global'].value"
                placeholder="Suchen..."
              />
            </IconField>
          </div>
        </template>
        <template #empty>Keine Kontakte gefunden.</template>
        <template #loading>Lade Kontakte. Bitte warten...</template>

          <Column field="companyName" header="Firma" sortable style="min-width: 200px">
            <template #body="{ data }">
              <div class="font-semibold">{{ data.companyName }}</div>
              <div class="text-sm text-500" v-if="data.companyNumber">
                Nr: {{ data.companyNumber }}
              </div>
            </template>
            <template #filter="{ filterModel }">
              <InputText v-model="filterModel.value" type="text" placeholder="Suche nach Firma" />
            </template>
          </Column>

          <Column field="city" header="Ort" sortable style="min-width: 150px">
            <template #body="{ data }">
              <div v-if="data.zipCode || data.city">
                {{ data.zipCode }} {{ data.city }}
              </div>
              <div class="text-sm text-500" v-if="data.country">
                {{ data.country }}
              </div>
            </template>
            <template #filter="{ filterModel }">
              <InputText v-model="filterModel.value" type="text" placeholder="Suche nach Ort" />
            </template>
          </Column>

          <Column header="Ansprechpartner" style="min-width: 200px">
            <template #body="{ data }">
              <div v-if="data.contactPersons && data.contactPersons.length > 0">
                <div
                  v-for="person in data.contactPersons.slice(0, 2)"
                  :key="person.id"
                  class="mb-1"
                >
                  <div class="font-medium">
                    {{ person.firstName }} {{ person.lastName }}
                    <Tag v-if="person.isPrimary" value="Primär" severity="info" class="ml-1" />
                  </div>
                  <div class="text-sm text-500" v-if="person.email">
                    {{ person.email }}
                  </div>
                </div>
              </div>
              <span v-else class="text-500">Keine Ansprechpartner</span>
            </template>
          </Column>

          <Column header="Typ" style="min-width: 130px">
            <template #body="{ data }">
              <div class="flex gap-1">
                <Tag v-if="data.isDebtor" value="Debitor" severity="success" />
                <Tag v-if="data.isCreditor" value="Kreditor" severity="warning" />
              </div>
            </template>
          </Column>

          <Column field="isActive" header="Status" dataType="boolean" style="min-width: 100px">
            <template #body="{ data }">
              <Tag
                :value="data.isActive ? 'Aktiv' : 'Inaktiv'"
                :severity="data.isActive ? 'success' : 'danger'"
              />
            </template>
            <template #filter="{ filterModel }">
              <Select 
                v-model="filterModel.value" 
                :options="statusOptions" 
                optionLabel="label"
                optionValue="value"
                placeholder="Status wählen" 
                showClear
              >
                <template #option="slotProps">
                  <Tag :value="slotProps.option.label" :severity="slotProps.option.value ? 'success' : 'danger'" />
                </template>
              </Select>
            </template>
          </Column>

          <Column header="Kontakt" style="min-width: 200px">
            <template #body="{ data }">
              <div class="flex flex-column gap-1">
                <div v-if="data.phone" class="text-sm">
                  <i class="pi pi-phone mr-1"></i> {{ data.phone }}
                </div>
                <div v-if="data.email" class="text-sm">
                  <i class="pi pi-envelope mr-1"></i> {{ data.email }}
                </div>
                <div v-if="data.website" class="text-sm">
                  <i class="pi pi-globe mr-1"></i>
                  <a :href="data.website" target="_blank">{{ data.website }}</a>
                </div>
              </div>
            </template>
          </Column>

          <Column :exportable="false" style="min-width: 120px">
            <template #body="{ data }">
              <div class="flex gap-2">
                <Button
                  icon="pi pi-pencil"
                  outlined
                  rounded
                  @click="editContact(data)"
                  size="small"
                />
                <Button
                  icon="pi pi-trash"
                  outlined
                  rounded
                  severity="danger"
                  @click="confirmDelete(data)"
                  size="small"
                />
              </div>
            </template>
          </Column>

        </DataTable>
      </div>

    <!-- Contact Dialog -->
    <Dialog
      v-model:visible="contactDialog"
      :header="editingContact?.id ? 'Kontakt bearbeiten' : 'Neuer Kontakt'"
      :modal="true"
      :style="{ width: '1200px', maxHeight: '90vh' }"
      :closable="true"
    >
      <div v-if="editingContact">
        <!-- Basisdaten -->
        <Card class="mb-3">
          <template #title>
            <div class="flex items-center gap-2">
              <i class="pi pi-building text-primary"></i>
              <span>Basisdaten</span>
            </div>
          </template>
          <template #content>
            <div class="flex flex-col gap-4">
              <div class="flex flex-col md:flex-row gap-4">
                <div class="flex flex-col gap-2 w-full md:w-2/3">
                  <label for="companyName">Firmenname <span class="text-red-500">*</span></label>
                  <InputText
                    id="companyName"
                    v-model="editingContact.companyName"
                    :invalid="submitted && !editingContact.companyName"
                  />
                  <small v-if="submitted && !editingContact.companyName" class="text-red-500">
                    Firmenname ist erforderlich
                  </small>
                </div>

                <div class="flex flex-col gap-2 w-full md:w-1/3">
                  <label for="companyNumber">Kundennummer</label>
                  <InputText id="companyNumber" v-model="editingContact.companyNumber" />
                </div>
              </div>

              <div class="flex gap-4">
                <div class="flex items-center gap-2">
                  <Checkbox inputId="isDebtor" v-model="editingContact.isDebtor" :binary="true" />
                  <label for="isDebtor">Debitor</label>
                </div>
                <div class="flex items-center gap-2">
                  <Checkbox inputId="isCreditor" v-model="editingContact.isCreditor" :binary="true" />
                  <label for="isCreditor">Kreditor</label>
                </div>
                <div class="flex items-center gap-2">
                  <Checkbox inputId="isActive" v-model="editingContact.isActive" :binary="true" />
                  <label for="isActive">Aktiv</label>
                </div>
              </div>
            </div>
          </template>
        </Card>

        <!-- Adresse -->
        <Card class="mb-3">
          <template #title>
            <div class="flex items-center gap-2">
              <i class="pi pi-map-marker text-primary"></i>
              <span>Adresse</span>
            </div>
          </template>
          <template #content>
            <div class="flex flex-col gap-4">
              <div class="flex flex-col gap-2">
                <label for="street">Straße</label>
                <InputText id="street" v-model="editingContact.street" />
              </div>

              <div class="flex flex-col md:flex-row gap-4">
                <div class="flex flex-col gap-2 w-full md:w-1/4">
                  <label for="zipCode">PLZ</label>
                  <InputText id="zipCode" v-model="editingContact.zipCode" />
                </div>

                <div class="flex flex-col gap-2 w-full md:w-1/2">
                  <label for="city">Ort</label>
                  <InputText id="city" v-model="editingContact.city" />
                </div>

                <div class="flex flex-col gap-2 w-full md:w-1/4">
                  <label for="country">Land</label>
                  <InputText id="country" v-model="editingContact.country" />
                </div>
              </div>
            </div>
          </template>
        </Card>

        <!-- Kontaktdaten -->
        <Card class="mb-3">
          <template #title>
            <div class="flex items-center gap-2">
              <i class="pi pi-phone text-primary"></i>
              <span>Kontaktdaten</span>
            </div>
          </template>
          <template #content>
            <div class="flex flex-col gap-4">
              <div class="flex flex-col md:flex-row gap-4">
                <div class="flex flex-col gap-2 w-full">
                  <label for="phone">Telefon</label>
                  <InputText id="phone" v-model="editingContact.phone" />
                </div>

                <div class="flex flex-col gap-2 w-full">
                  <label for="fax">Fax</label>
                  <InputText id="fax" v-model="editingContact.fax" />
                </div>
              </div>

              <div class="flex flex-col md:flex-row gap-4">
                <div class="flex flex-col gap-2 w-full">
                  <label for="email">E-Mail</label>
                  <InputText id="email" v-model="editingContact.email" type="email" />
                </div>

                <div class="flex flex-col gap-2 w-full">
                  <label for="website">Website</label>
                  <InputText id="website" v-model="editingContact.website" />
                </div>
              </div>
            </div>
          </template>
        </Card>

        <!-- Steuerdaten -->
        <Card class="mb-3">
          <template #title>
            <div class="flex items-center gap-2">
              <i class="pi pi-calculator text-primary"></i>
              <span>Steuerdaten</span>
            </div>
          </template>
          <template #content>
            <div class="flex flex-col md:flex-row gap-4">
              <div class="flex flex-col gap-2 w-full">
                <label for="taxNumber">Steuernummer</label>
                <InputText id="taxNumber" v-model="editingContact.taxNumber" />
              </div>

              <div class="flex flex-col gap-2 w-full">
                <label for="vatNumber">USt-IdNr.</label>
                <InputText id="vatNumber" v-model="editingContact.vatNumber" />
              </div>
            </div>
          </template>
        </Card>

        <!-- Ansprechpartner -->
        <Card class="mb-3">
          <template #title>
            <div class="flex items-center justify-between">
              <div class="flex items-center gap-2">
                <i class="pi pi-users text-primary"></i>
                <span>Ansprechpartner</span>
              </div>
              <Button
                label="Hinzufügen"
                icon="pi pi-plus"
                size="small"
                outlined
                @click="addContactPerson"
                :disabled="editingContact.contactPersons.length >= 2"
              />
            </div>
          </template>
          <template #content>
            <div v-if="editingContact.contactPersons.length === 0" class="text-center py-4 text-500">
              <i class="pi pi-user-plus text-4xl mb-3"></i>
              <p>Noch keine Ansprechpartner hinzugefügt</p>
            </div>

            <div
              v-for="(person, index) in editingContact.contactPersons"
              :key="index"
              class="mb-4"
            >
              <Divider v-if="index > 0" />
              <div class="flex flex-col gap-4">
                <div class="flex justify-between items-center mb-3">
                  <h4 class="m-0 font-semibold">
                    <i class="pi pi-user mr-2"></i>
                    Ansprechpartner {{ index + 1 }}
                    <Tag v-if="person.isPrimary" value="Primär" severity="info" class="ml-2" />
                  </h4>
                  <Button
                    icon="pi pi-trash"
                    text
                    rounded
                    severity="danger"
                    @click="removeContactPerson(index)"
                    size="small"
                  />
                </div>

                <div class="flex flex-col md:flex-row gap-4">
                  <div class="flex flex-col gap-2 w-full md:w-1/4">
                    <label :for="'salutation-' + index">Anrede</label>
                    <Dropdown
                      :id="'salutation-' + index"
                      v-model="person.salutation"
                      :options="salutations"
                      placeholder="Wählen..."
                    />
                  </div>

                  <div class="flex flex-col gap-2 w-full md:w-1/4">
                    <label :for="'title-' + index">Titel</label>
                    <InputText :id="'title-' + index" v-model="person.title" />
                  </div>

                  <div class="flex flex-col gap-2 w-full md:w-1/4">
                    <label :for="'firstName-' + index">
                      Vorname <span class="text-red-500">*</span>
                    </label>
                    <InputText
                      :id="'firstName-' + index"
                      v-model="person.firstName"
                      :invalid="submitted && !person.firstName"
                    />
                  </div>

                  <div class="flex flex-col gap-2 w-full md:w-1/4">
                    <label :for="'lastName-' + index">
                      Nachname <span class="text-red-500">*</span>
                    </label>
                    <InputText
                      :id="'lastName-' + index"
                      v-model="person.lastName"
                      :invalid="submitted && !person.lastName"
                    />
                  </div>
                </div>

                <div class="flex flex-col md:flex-row gap-4">
                  <div class="flex flex-col gap-2 w-full">
                    <label :for="'position-' + index">Position</label>
                    <InputText :id="'position-' + index" v-model="person.position" />
                  </div>

                  <div class="flex flex-col gap-2 w-full">
                    <label :for="'department-' + index">Abteilung</label>
                    <InputText :id="'department-' + index" v-model="person.department" />
                  </div>
                </div>

                <div class="flex flex-col md:flex-row gap-4">
                  <div class="flex flex-col gap-2 w-full">
                    <label :for="'personPhone-' + index">Telefon</label>
                    <InputText :id="'personPhone-' + index" v-model="person.phone" />
                  </div>

                  <div class="flex flex-col gap-2 w-full">
                    <label :for="'mobile-' + index">Mobil</label>
                    <InputText :id="'mobile-' + index" v-model="person.mobile" />
                  </div>

                  <div class="flex flex-col gap-2 w-full">
                    <label :for="'personEmail-' + index">E-Mail</label>
                    <InputText
                      :id="'personEmail-' + index"
                      v-model="person.email"
                      type="email"
                    />
                  </div>
                </div>

                <div class="flex items-center gap-2">
                  <Checkbox
                    :inputId="'isPrimary-' + index"
                    v-model="person.isPrimary"
                    :binary="true"
                  />
                  <label :for="'isPrimary-' + index">Hauptansprechpartner</label>
                </div>
              </div>
            </div>
          </template>
        </Card>

        <!-- Notizen -->
        <Card>
          <template #title>
            <div class="flex items-center gap-2">
              <i class="pi pi-comment text-primary"></i>
              <span>Notizen</span>
            </div>
          </template>
          <template #content>
            <div class="flex flex-col gap-2">
              <label for="notes">Interne Notizen zu diesem Kontakt</label>
              <Textarea 
                id="notes" 
                v-model="editingContact.notes" 
                :rows="4"
                placeholder="Interne Notizen..."
              />
            </div>
          </template>
        </Card>
      </div>

      <template #footer>
        <Button label="Abbrechen" outlined @click="hideDialog" />
        <Button label="Speichern" @click="saveContact" :loading="saving" />
      </template>
    </Dialog>

    <!-- Delete Confirmation -->
    <Dialog
      v-model:visible="deleteDialog"
      header="Bestätigung"
      :modal="true"
      :style="{ width: '450px' }"
    >
      <div class="flex align-items-center">
        <i class="pi pi-exclamation-triangle mr-3" style="font-size: 2rem; color: var(--red-500)"></i>
        <span v-if="editingContact">
          Möchten Sie den Kontakt <b>{{ editingContact.companyName }}</b> wirklich löschen?
        </span>
      </div>
      <template #footer>
        <Button label="Nein" outlined @click="deleteDialog = false" />
        <Button label="Ja" severity="danger" @click="deleteContact" :loading="deleting" />
      </template>
    </Dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useToast } from 'primevue/usetoast'
import { FilterMatchMode, FilterOperator } from '@primevue/core/api'
import DataTable from 'primevue/datatable'
import Column from 'primevue/column'
import Button from 'primevue/button'
import InputText from 'primevue/inputtext'
import Textarea from 'primevue/textarea'
import Dialog from 'primevue/dialog'
import Card from 'primevue/card'
import Tag from 'primevue/tag'
import Checkbox from 'primevue/checkbox'
import Dropdown from 'primevue/dropdown'
import Divider from 'primevue/divider'
import IconField from 'primevue/iconfield'
import InputIcon from 'primevue/inputicon'
import Select from 'primevue/select'

const toast = useToast()

const contacts = ref([])
const loading = ref(false)
const contactDialog = ref(false)
const deleteDialog = ref(false)
const editingContact = ref(null)
const submitted = ref(false)
const saving = ref(false)
const deleting = ref(false)
const typeFilter = ref('all')
const filters = ref({
  global: { value: null, matchMode: FilterMatchMode.CONTAINS },
  companyName: { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.STARTS_WITH }] },
  city: { operator: FilterOperator.AND, constraints: [{ value: null, matchMode: FilterMatchMode.STARTS_WITH }] },
  isActive: { value: null, matchMode: FilterMatchMode.EQUALS }
})

const salutations = ref(['Herr', 'Frau', 'Divers'])
const statusOptions = ref([
  { label: 'Aktiv', value: true },
  { label: 'Inaktiv', value: false }
])
const typeOptions = ref(['Debitor', 'Kreditor'])

const emptyContact = () => ({
  companyName: '',
  companyNumber: '',
  street: '',
  zipCode: '',
  city: '',
  country: 'Deutschland',
  phone: '',
  fax: '',
  email: '',
  website: '',
  taxNumber: '',
  vatNumber: '',
  isDebtor: false,
  isCreditor: false,
  isActive: true,
  notes: '',
  contactPersons: []
})

const emptyContactPerson = () => ({
  salutation: null,
  title: '',
  firstName: '',
  lastName: '',
  position: '',
  department: '',
  phone: '',
  mobile: '',
  email: '',
  isPrimary: false
})

onMounted(() => {
  loadContacts()
})

const loadContacts = async () => {
  loading.value = true
  try {
    // Alle Kontakte laden - API Platform unterstützt itemsPerPage Parameter
    let url = '/api/contacts'
    const params = new URLSearchParams()
    
    // Große Anzahl setzen, um alle Kontakte zu erhalten
    params.append('itemsPerPage', '5000')
    
    if (typeFilter.value === 'debtor') {
      params.append('isDebtor', 'true')
    } else if (typeFilter.value === 'creditor') {
      params.append('isCreditor', 'true')
    }
    
    url += '?' + params.toString()
    
    const response = await fetch(url, {
      credentials: 'include'
    })
    if (!response.ok) throw new Error('Fehler beim Laden der Kontakte')
    const data = await response.json()
    
    // API Platform gibt hydra:member zurück
    contacts.value = data['hydra:member'] || data.member || []
    
    console.log('Loaded contacts:', contacts.value.length, 'with filter:', typeFilter.value)
  } catch (error) {
    console.error('Error loading contacts:', error)
    toast.add({
      severity: 'error',
      summary: 'Fehler',
      detail: 'Kontakte konnten nicht geladen werden',
      life: 3000
    })
  } finally {
    loading.value = false
  }
}

const filterByType = (type) => {
  typeFilter.value = type
  loadContacts()
}

const openNewContactDialog = () => {
  editingContact.value = emptyContact()
  submitted.value = false
  contactDialog.value = true
}

const editContact = (contact) => {
  editingContact.value = { ...contact }
  // Ensure contactPersons is initialized
  if (!editingContact.value.contactPersons) {
    editingContact.value.contactPersons = []
  }
  submitted.value = false
  contactDialog.value = true
}

const hideDialog = () => {
  contactDialog.value = false
  submitted.value = false
  editingContact.value = null
}

const addContactPerson = () => {
  if (editingContact.value.contactPersons.length < 2) {
    editingContact.value.contactPersons.push(emptyContactPerson())
  }
}

const removeContactPerson = (index) => {
  editingContact.value.contactPersons.splice(index, 1)
}

const validateContact = () => {
  if (!editingContact.value.companyName) {
    return false
  }
  
  // Validate contact persons
  for (const person of editingContact.value.contactPersons) {
    if (!person.firstName || !person.lastName) {
      return false
    }
  }
  
  return true
}

const saveContact = async () => {
  submitted.value = true
  
  if (!validateContact()) {
    toast.add({
      severity: 'warn',
      summary: 'Validierung fehlgeschlagen',
      detail: 'Bitte füllen Sie alle Pflichtfelder aus',
      life: 3000
    })
    return
  }

  saving.value = true
  try {
    const url = editingContact.value.id
      ? `/api/contacts/${editingContact.value.id}`
      : '/api/contacts'
    
    const method = editingContact.value.id ? 'PUT' : 'POST'
    
    const response = await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json'
      },
      credentials: 'include',
      body: JSON.stringify(editingContact.value)
    })

    if (!response.ok) {
      const error = await response.json()
      throw new Error(error.message || 'Fehler beim Speichern')
    }

    toast.add({
      severity: 'success',
      summary: 'Erfolg',
      detail: 'Kontakt wurde gespeichert',
      life: 3000
    })

    hideDialog()
    loadContacts()
  } catch (error) {
    console.error('Error saving contact:', error)
    toast.add({
      severity: 'error',
      summary: 'Fehler',
      detail: error.message || 'Kontakt konnte nicht gespeichert werden',
      life: 3000
    })
  } finally {
    saving.value = false
  }
}

const confirmDelete = (contact) => {
  editingContact.value = contact
  deleteDialog.value = true
}

const deleteContact = async () => {
  deleting.value = true
  try {
    const response = await fetch(`/api/contacts/${editingContact.value.id}`, {
      method: 'DELETE',
      credentials: 'include'
    })

    if (!response.ok) throw new Error('Fehler beim Löschen')

    toast.add({
      severity: 'success',
      summary: 'Erfolg',
      detail: 'Kontakt wurde gelöscht',
      life: 3000
    })

    deleteDialog.value = false
    editingContact.value = null
    loadContacts()
  } catch (error) {
    console.error('Error deleting contact:', error)
    toast.add({
      severity: 'error',
      summary: 'Fehler',
      detail: 'Kontakt konnte nicht gelöscht werden',
      life: 3000
    })
  } finally {
    deleting.value = false
  }
}
</script>

<style scoped>
.contact-management {
  padding: 1rem;
}

.p-invalid {
  border-color: var(--red-500);
}

.p-error {
  color: var(--red-500);
  font-size: 0.875rem;
}
</style>
