<script setup>
import { toast } from 'bulma-toast'

const emailInvoice = useEmailInvoice()
const emailInvoiceParam = useEmailInvoiceParam()

const form = ref({
  toEmail: '',
  ccEmail: '',
  subject: '',
  message: '',
  sending: false
})

const closeModal = () => {
  emailInvoice.value = false
  form.value = {
    toEmail: '',
    ccEmail: '',
    subject: '',
    message: '',
    sending: false
  }
  emailInvoiceParam.value = {}
}

const partnerLanguage = ref('de_DE')

const fetchPartnerData = async () => {
  if (emailInvoiceParam.value?.partnerId) {
    try {
      const res = await $fetch('/api/partners/partners/' + emailInvoiceParam.value.partnerId, {
        headers: useRequestHeaders(['cookie'])
      })
      // Prefer the dedicated invoice email (C_BPartner.EMail_Invoice) when set,
      // otherwise fall back to the partner's general EMail (accept both casings —
      // iDempiere OData response casing varies by model)
      const invoiceEmail = String(res?.EMail_Invoice ?? res?.Email_Invoice ?? res?.eMail_Invoice ?? '').trim()
      if (invoiceEmail) {
        form.value.toEmail = invoiceEmail
      } else if (res?.EMail) {
        form.value.toEmail = res.EMail
      }
      // Get partner language
      partnerLanguage.value = res?.AD_Language?.id || 'de_DE'
      // Update message based on language
      updateMessageForLanguage()
    } catch (err) {
      console.error('Error fetching partner data:', err)
    }
  }
}

const isCreditMemo = computed(() => {
  const dbt = emailInvoiceParam.value?.docBaseType || ''
  return dbt === 'APC' || dbt === 'ARC'
})

const updateMessageForLanguage = () => {
  const documentNo = emailInvoiceParam.value?.documentNo || ''
  const partnerName = emailInvoiceParam.value?.partner || ''
  const isGerman = partnerLanguage.value.startsWith('de')

  if (isCreditMemo.value) {
    if (isGerman) {
      form.value.subject = `Gutschrift ${documentNo}`
      form.value.message = `Sehr geehrte Damen und Herren,

anbei erhalten Sie die Gutschrift ${documentNo}. Der Betrag wird auf die im System hinterlegte Zahlungsmethode überwiesen.`
    } else {
      form.value.subject = `Credit Memo ${documentNo}`
      form.value.message = `Dear Sir or Madam,

you have received a credit memo ${documentNo}. The amount will be transferred to the payment method saved in the system.`
    }
  } else {
    if (isGerman) {
      form.value.subject = `Rechnung ${documentNo}`
      form.value.message = `Sehr geehrte Damen und Herren,

anbei erhalten Sie die Rechnung ${documentNo}.`
    } else {
      form.value.subject = `Invoice ${documentNo}`
      form.value.message = `Dear Sir or Madam,

please find attached the invoice ${documentNo}.`
    }
  }
}

const initForm = () => {
  // Set default message (German)
  updateMessageForLanguage()
  // Fetch partner data (email and language)
  fetchPartnerData()
}

watch(emailInvoice, (newVal) => {
  if (newVal) {
    initForm()
  }
})

const sendEmail = async () => {
  if (!form.value.toEmail) {
    toast({
      message: 'Please enter a recipient email address',
      type: 'is-warning',
      duration: 2000
    })
    return
  }

  if (!form.value.subject) {
    toast({
      message: 'Please enter a subject',
      type: 'is-warning',
      duration: 2000
    })
    return
  }

  form.value.sending = true

  // Get current app URL for the invoice link
  const appUrl = window.location.origin

  try {
    const res = await $fetch('/api/invoices/' + emailInvoiceParam.value.id + '/send-email', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        toEmail: form.value.toEmail,
        ccEmail: form.value.ccEmail,
        subject: form.value.subject,
        message: form.value.message,
        appUrl: appUrl,
        isCreditMemo: isCreditMemo.value
      }
    })

    if (res?.status === 200) {
      toast({
        message: 'Email sent successfully!',
        type: 'is-success',
        duration: 2000
      })
      closeModal()
    } else {
      toast({
        message: res?.message || 'Failed to send email',
        type: 'is-danger',
        duration: 3000
      })
    }
  } catch (err) {
    console.error('Error sending email:', err)
    toast({
      message: 'Failed to send email',
      type: 'is-danger',
      duration: 3000
    })
  } finally {
    form.value.sending = false
  }
}
</script>

<template>
  <div class="email-modal-overlay" v-if="emailInvoice" @click.self="closeModal">
    <div class="email-modal-container" @click.stop>
      <div class="email-modal-header">
        <h3 class="email-modal-title">{{ isCreditMemo ? 'Send Credit Memo via Email' : 'Send Invoice via Email' }}</h3>
        <div class="cursor-pointer" @click="closeModal">
          <span class="tf-icon ti ti-x ti-sm"></span>
        </div>
      </div>
      <div class="email-modal-body">
        <div class="mb-3">
          <label class="form-label">Recipient Email *</label>
          <input
            type="email"
            v-model="form.toEmail"
            class="form-control"
            placeholder="Enter recipient email address"
          />
        </div>
        <div class="mb-3">
          <label class="form-label">CC Email</label>
          <input
            type="text"
            v-model="form.ccEmail"
            class="form-control"
            placeholder="Enter CC email address (comma-separated for multiple)"
          />
        </div>
        <div class="mb-3">
          <label class="form-label">Subject *</label>
          <input
            type="text"
            v-model="form.subject"
            class="form-control"
            placeholder="Enter email subject"
          />
        </div>
        <div class="mb-3">
          <label class="form-label">Message</label>
          <textarea
            v-model="form.message"
            class="form-control"
            rows="6"
            placeholder="Enter email message"
          ></textarea>
        </div>
        <div class="mb-3">
          <small class="text-muted">
            {{ isCreditMemo ? 'The credit memo PDF will be attached automatically.' : 'The invoice PDF will be attached automatically.' }}
          </small>
        </div>
      </div>
      <div class="email-modal-footer">
        <button type="button" class="button" @click="closeModal" :disabled="form.sending">Cancel</button>
        <button
          type="button"
          class="button button-primary"
          @click="sendEmail"
          :class="{'pointerEvents-none opacity-0.6': form.sending}"
          :disabled="form.sending"
        >
          <span v-if="form.sending">Sending...</span>
          <span v-else>
            <span class="tf-icon ti ti-send ti-xs me-1 color-inherit"></span> Send
          </span>
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.email-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100vw;
  height: 100vh;
  z-index: 9999;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  box-sizing: border-box;
}
.email-modal-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  width: 100%;
  max-width: 500px;
  max-height: calc(100vh - 40px);
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}
.email-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
}
.email-modal-title {
  margin: 0;
  font-size: 1.1rem;
  font-weight: 600;
}
.email-modal-body {
  padding: 20px;
  flex: 1;
  overflow-y: auto;
}
.email-modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 16px 20px;
  border-top: 1px solid #eee;
}
.form-label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
}
.form-control {
  width: 100%;
  padding: 0.5rem 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 0.875rem;
  box-sizing: border-box;
}
.form-control:focus {
  outline: none;
  border-color: #666;
}
textarea.form-control {
  resize: vertical;
}
.text-muted {
  color: #6c757d;
}
.button-primary {
  background-color: #0d6efd;
  color: white;
  border-color: #0d6efd;
}
.button-primary:hover {
  background-color: #0b5ed7;
}
.mb-3 {
  margin-bottom: 1rem;
}
.cursor-pointer {
  cursor: pointer;
}
</style>
