<template>
  <div>
    <div class="page-header">
      <h2>Support Teams</h2>
      <button class="btn btn-primary" @click="openTeamModal()">+ Add Support Team</button>
    </div>

    <div class="card">
      <div v-if="loading" class="loading">Loading...</div>

      <template v-else>
        <div class="table-container">
          <table>
            <thead>
              <tr>
                <th>Team Name</th>
                <th>Link</th>
                <th>Contacts</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="team in teams" :key="team.supportteamid">
                <td>{{ team.teamname }}</td>
                <td>
                  <a v-if="team.teamurl" :href="team.teamurl" target="_blank">Link</a>
                  <span v-else>-</span>
                </td>
                <td>
                  <button class="btn btn-secondary btn-sm" @click="openContactsModal(team)">
                    Contacts ({{ team.contacts ? team.contacts.length : 0 }})
                  </button>
                </td>
                <td class="actions">
                  <button class="btn btn-secondary btn-sm" @click="openTeamModal(team)">Edit</button>
                  <button class="btn btn-danger btn-sm" @click="confirmDeleteTeam(team)">Delete</button>
                </td>
              </tr>
              <tr v-if="teams.length === 0">
                <td colspan="4" style="text-align: center; color: var(--text-light);">
                  No support teams found
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </template>
    </div>

    <!-- Team Add/Edit Modal -->
    <div v-if="showTeamModal" class="modal-overlay">
      <div class="modal">
        <div class="modal-header">
          <h3>{{ editingTeam ? 'Edit Support Team' : 'Add Support Team' }}</h3>
        </div>
        <form @submit.prevent="saveTeam">
          <div class="modal-body">
            <div class="form-group">
              <label for="teamname">Team Name *</label>
              <input id="teamname" v-model="teamForm.teamname" type="text" class="form-control" required />
            </div>
            <div class="form-group">
              <label for="teamurl">Team URL</label>
              <input id="teamurl" v-model="teamForm.teamurl" type="text" class="form-control" placeholder="ServiceNow group link" />
            </div>
            <div class="form-group">
              <label for="webhookurl">Alert Webhook URL</label>
              <input id="webhookurl" v-model="teamForm.webhookurl" type="text" class="form-control" placeholder="Microsoft Teams webhook for this team's alerts" />
            </div>
            <div v-if="teamError" class="error-message">{{ teamError }}</div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" @click="showTeamModal = false">Cancel</button>
            <button type="submit" class="btn btn-primary" :disabled="saving">
              {{ saving ? 'Saving...' : 'Save' }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- Contacts List Modal (per team) -->
    <div v-if="showContactsModal && contactsTeam" class="modal-overlay" @click.self="showContactsModal = false">
      <div class="modal contacts-modal">
        <div class="modal-header">
          <h3>{{ contactsTeam.teamname }} - Contacts</h3>
        </div>
        <div class="modal-body">
          <div class="contacts-header">
            <strong>Contacts ({{ contactsTeam.contacts ? contactsTeam.contacts.length : 0 }})</strong>
            <button class="btn btn-primary btn-sm" @click="openContactModal(contactsTeam)">+ Add Contact</button>
          </div>
          <table class="contacts-table">
            <thead>
              <tr>
                <th>Name</th>
                <th>SSO</th>
                <th>Active</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="contact in contactsTeam.contacts" :key="contact.contactid">
                <td>
                  {{ contact.name }}
                  <template v-if="contact.sso && contactEmailDomain">
                    <a class="contact-action" :href="`mailto:${contactEmail(contact)}`" title="Email">Email</a>
                    <a class="contact-action" :href="`https://teams.microsoft.com/l/chat/0/0?users=${contactEmail(contact)}`" target="_blank" rel="noopener" title="Teams chat">Teams</a>
                  </template>
                </td>
                <td class="mono">{{ contact.sso || '-' }}</td>
                <td>{{ contact.isactive === false ? 'No' : 'Yes' }}</td>
                <td class="actions">
                  <button class="btn btn-secondary btn-sm" @click="openContactModal(contactsTeam, contact)">Edit</button>
                  <button class="btn btn-danger btn-sm" @click="deleteContact(contactsTeam, contact)">Delete</button>
                </td>
              </tr>
              <tr v-if="!contactsTeam.contacts || contactsTeam.contacts.length === 0">
                <td colspan="4" style="text-align: center; color: var(--text-light);">
                  No contacts yet
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" @click="showContactsModal = false">Close</button>
        </div>
      </div>
    </div>

    <!-- Contact Add/Edit Modal -->
    <div v-if="showContactModal" class="modal-overlay">
      <div class="modal">
        <div class="modal-header">
          <h3>{{ editingContact ? 'Edit Contact' : 'Add Contact' }}</h3>
        </div>
        <form @submit.prevent="saveContact">
          <div class="modal-body">
            <div class="form-group">
              <label for="name">Name *</label>
              <input id="name" v-model="contactForm.name" type="text" class="form-control" required />
            </div>
            <div class="form-group">
              <label for="sso">SSO</label>
              <input id="sso" v-model="contactForm.sso" type="text" class="form-control" />
            </div>
            <div class="form-group">
              <label for="sortorder">Sort Order</label>
              <input id="sortorder" v-model.number="contactForm.sortorder" type="number" class="form-control" />
            </div>
            <div v-if="contactError" class="error-message">{{ contactError }}</div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" @click="showContactModal = false">Cancel</button>
            <button type="submit" class="btn btn-primary" :disabled="saving">
              {{ saving ? 'Saving...' : 'Save' }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- Delete Team Modal -->
    <div v-if="showDeleteModal" class="modal-overlay" @click.self="showDeleteModal = false">
      <div class="modal">
        <div class="modal-header"><h3>Delete Support Team</h3></div>
        <div class="modal-body">
          <p>Are you sure you want to delete <strong>{{ toDelete?.teamname }}</strong>?</p>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="showDeleteModal = false">Cancel</button>
          <button class="btn btn-danger" @click="deleteTeam">Delete</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { supportteamsApi } from '../../api'
import { useToast } from '../../composables/toast'
import { apiError } from '../../utils/apiError'
import { getContactEmailDomain } from '../../utils/siteSettings'
const toast = useToast()

const teams = ref([])
const loading = ref(true)
const saving = ref(false)
const contactEmailDomain = ref('')

// Contacts list modal. Track the team id (not the object) so the computed
// re-resolves against the freshly loaded teams array after any CRUD reload.
const showContactsModal = ref(false)
const contactsTeamId = ref(null)
const contactsTeam = computed(() =>
  teams.value.find(t => t.supportteamid === contactsTeamId.value) || null
)

// Build sso@domain for a contact. Assumes contact.sso and domain are set.
function contactEmail(contact) {
  return `${contact.sso}@${contactEmailDomain.value}`
}

const showTeamModal = ref(false)
const editingTeam = ref(null)
const teamError = ref('')
const teamForm = ref({ teamname: '', teamurl: '', webhookurl: '' })

const showContactModal = ref(false)
const editingContact = ref(null)
const contactTeam = ref(null)
const contactError = ref('')
const contactForm = ref({ name: '', sso: '', sortorder: 0 })

const showDeleteModal = ref(false)
const toDelete = ref(null)

onMounted(async () => {
  contactEmailDomain.value = await getContactEmailDomain()
  loadData()
})

async function loadData() {
  loading.value = true
  try {
    const response = await supportteamsApi.list({ active: false })
    teams.value = response.data.data || []
  } catch (err) {
    console.error('Error loading support teams:', err)
  } finally {
    loading.value = false
  }
}

function openContactsModal(team) {
  contactsTeamId.value = team.supportteamid
  showContactsModal.value = true
}

function openTeamModal(team = null) {
  editingTeam.value = team
  teamForm.value = team
    ? { teamname: team.teamname || '', teamurl: team.teamurl || '', webhookurl: team.webhookurl || '' }
    : { teamname: '', teamurl: '', webhookurl: '' }
  teamError.value = ''
  showTeamModal.value = true
}

async function saveTeam() {
  teamError.value = ''
  saving.value = true
  try {
    const payload = {
      teamname: teamForm.value.teamname,
      teamurl: teamForm.value.teamurl || null,
      webhookurl: teamForm.value.webhookurl || null
    }
    if (editingTeam.value) {
      await supportteamsApi.update(editingTeam.value.supportteamid, payload)
    } else {
      await supportteamsApi.create(payload)
    }
    showTeamModal.value = false
    loadData()
  } catch (err) {
    teamError.value = apiError(err, 'Failed to save')
  } finally {
    saving.value = false
  }
}

function confirmDeleteTeam(team) {
  toDelete.value = team
  showDeleteModal.value = true
}

async function deleteTeam() {
  try {
    await supportteamsApi.remove(toDelete.value.supportteamid)
    showDeleteModal.value = false
    toDelete.value = null
    loadData()
  } catch (err) {
    toast.error(apiError(err, 'Failed to delete'))
    showDeleteModal.value = false
  }
}

function openContactModal(team, contact = null) {
  contactTeam.value = team
  editingContact.value = contact
  contactForm.value = contact
    ? { name: contact.name || '', sso: contact.sso || '', sortorder: contact.sortorder || 0 }
    : { name: '', sso: '', sortorder: 0 }
  contactError.value = ''
  showContactModal.value = true
}

async function saveContact() {
  contactError.value = ''
  saving.value = true
  try {
    const teamId = contactTeam.value.supportteamid
    const payload = {
      name: contactForm.value.name,
      sso: contactForm.value.sso || null,
      sortorder: contactForm.value.sortorder || 0
    }
    if (editingContact.value) {
      await supportteamsApi.contacts.update(teamId, editingContact.value.contactid, payload)
    } else {
      await supportteamsApi.contacts.add(teamId, payload)
    }
    showContactModal.value = false
    await loadData()
  } catch (err) {
    contactError.value = apiError(err, 'Failed to save')
  } finally {
    saving.value = false
  }
}

async function deleteContact(team, contact) {
  try {
    await supportteamsApi.contacts.remove(team.supportteamid, contact.contactid)
    await loadData()
  } catch (err) {
    toast.error(apiError(err, 'Failed to delete'))
  }
}
</script>

<style scoped>
.contacts-modal {
  max-width: 640px;
}

.contacts-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 0.75rem;
}

.contacts-table {
  width: 100%;
}
</style>
