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

const paymentReminder = usePaymentReminder()
const paymentReminderParam = usePaymentReminderParam()

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

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

const partnerLanguage = ref('de_DE')

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' })
}

const formatCurrency = (amount, currency = 'EUR') => {
  return new Intl.NumberFormat('de-DE', {
    style: 'currency',
    currency: currency
  }).format(amount || 0)
}

const getMonthName = (dateStr, lang) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const isGerman = lang.startsWith('de')
  return date.toLocaleDateString(isGerman ? 'de-DE' : 'en-US', { month: 'long', year: 'numeric' })
}

const calculateDueDate = (dateInvoiced, netDays) => {
  if (!dateInvoiced) return null
  const invoiceDate = new Date(dateInvoiced)
  const dueDate = new Date(invoiceDate)
  dueDate.setDate(dueDate.getDate() + (netDays || 0))
  return dueDate
}

const fetchPartnerData = async () => {
  if (paymentReminderParam.value?.partnerId) {
    try {
      const res = await $fetch('/api/partners/partners/' + paymentReminderParam.value.partnerId, {
        headers: useRequestHeaders(['cookie'])
      })
      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 updateMessageForLanguage = () => {
  const data = paymentReminderParam.value
  const documentNo = data?.documentNo || ''
  const dateInvoiced = data?.dateInvoiced
  const netDays = data?.netDays || 0
  const grandTotal = data?.grandTotal || 0
  const currency = data?.currency || 'EUR'
  const isGerman = partnerLanguage.value.startsWith('de')

  const monthName = getMonthName(dateInvoiced, partnerLanguage.value)
  const dueDate = calculateDueDate(dateInvoiced, netDays)
  const formattedDueDate = dueDate ? formatDate(dueDate.toISOString()) : ''
  const formattedAmount = formatCurrency(grandTotal, currency)

  if (isGerman) {
    form.value.subject = `Zahlungserinnerung: Ihre Rechnung ${documentNo} ist überfällig`
    form.value.message = `Sehr geehrte Damen und Herren,

wir möchten Sie daran erinnern, dass die Zahlung für Ihre Rechnung ${documentNo} (Fälligkeitsdatum: ${formattedDueDate}) überfällig ist. Leider ist noch ein Betrag in Höhe von ${formattedAmount} offen geblieben.

Wir bitten Sie, den ausstehenden Betrag umgehend zu begleichen.

Sollten Sie die Zahlung bereits veranlasst haben, betrachten Sie diese Erinnerung bitte als gegenstandslos.

Mit freundlichen Grüßen`
  } else {
    form.value.subject = `Payment Reminder: Your invoice ${documentNo} is overdue`
    form.value.message = `Dear Sir or Madam,

we would like to remind you that the payment for your invoice ${documentNo} (due date: ${formattedDueDate}) is overdue. Unfortunately, an amount of ${formattedAmount} is still outstanding.

We kindly ask you to settle the outstanding amount as soon as possible.

If you have already initiated the payment, please disregard this reminder.

Best regards`
  }
}

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

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

const sendReminder = 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/' + paymentReminderParam.value.id + '/send-payment-reminder', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        toEmail: form.value.toEmail,
        ccEmail: form.value.ccEmail,
        subject: form.value.subject,
        message: form.value.message,
        appUrl: appUrl
      }
    })

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

<template>
  <div class="email-modal-overlay" v-if="paymentReminder" @click.self="closeModal">
    <div class="email-modal-container" @click.stop>
      <div class="email-modal-header">
        <h3 class="email-modal-title">Send Payment Reminder</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</label>
          <input
            type="email"
            v-model="form.ccEmail"
            class="form-control"
            placeholder="Enter CC email address (optional)"
          />
        </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="10"
            placeholder="Enter email message"
          ></textarea>
        </div>
        <div class="mb-3">
          <small class="text-muted">
            The invoice PDF and payment details will be included in the email.
          </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-danger"
          @click="sendReminder"
          :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 Reminder
          </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-danger {
  background-color: #dc3545;
  color: white;
  border-color: #dc3545;
}
.button-danger:hover {
  background-color: #c82333;
}
.mb-3 {
  margin-bottom: 1rem;
}
.cursor-pointer {
  cursor: pointer;
}
</style>
