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

const marginReportEmail = useMarginReportEmail()
const marginReportEmailParam = useMarginReportEmailParam()

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

const partnerLanguage = ref('de_DE')

const closeModal = () => {
  marginReportEmail.value = false
  form.value = { toEmail: '', ccEmail: '', subject: '', message: '', attachmentType: 'pdf', sending: false }
  marginReportEmailParam.value = {}
}

const formatDate = (date) => date.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' })
const formatTime = (date) => date.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' })

const attachmentLabel = computed(() => form.value.attachmentType === 'pdf' ? 'PDF' : 'CSV')

const updateMessageForLanguage = () => {
  const orgName = marginReportEmailParam.value?.orgName || ''
  const recordCount = marginReportEmailParam.value?.records?.length || 0
  const dateRange = marginReportEmailParam.value?.dateRange || ''
  const isGerman = partnerLanguage.value.startsWith('de')
  const now = new Date()
  const today = formatDate(now)
  const time = formatTime(now)

  if (isGerman) {
    form.value.subject = `Margenanalyse - ${orgName} - ${dateRange || today}`
    form.value.message = `Sehr geehrte Damen und Herren,

anbei finden Sie die Margenanalyse fuer "${orgName}"${dateRange ? ` (Zeitraum: ${dateRange})` : ''}.

Der Bericht enthaelt ${recordCount} Positionen und wurde am ${today} um ${time} erstellt.

Mit freundlichen Gruessen`
  } else {
    form.value.subject = `Margin Analysis - ${orgName} - ${dateRange || today}`
    form.value.message = `Dear Sir or Madam,

Please find attached the margin analysis for "${orgName}"${dateRange ? ` (period: ${dateRange})` : ''}.

The report contains ${recordCount} line items and was generated on ${today} at ${time}.

Best regards`
  }
}

watch(marginReportEmail, (newVal) => {
  if (newVal) updateMessageForLanguage()
})

const sendReport = 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
  }
  const records = marginReportEmailParam.value?.records
  if (!records || records.length === 0) {
    toast({ message: 'No records to send', type: 'is-warning', duration: 2000 })
    return
  }

  form.value.sending = true
  try {
    const res = await $fetch('/api/bi/send-margin-report', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        toEmail: form.value.toEmail,
        ccEmail: form.value.ccEmail,
        subject: form.value.subject,
        message: form.value.message,
        attachmentType: form.value.attachmentType,
        records: records,
        summary: marginReportEmailParam.value?.summary || {},
        orgName: marginReportEmailParam.value?.orgName || '',
        dateRange: marginReportEmailParam.value?.dateRange || '',
        language: partnerLanguage.value
      }
    })

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

<template>
  <Teleport to="body">
    <div class="email-modal-overlay" v-if="marginReportEmail" @click.self="closeModal">
      <div class="email-modal-container" @click.stop>
        <div class="email-modal-header">
          <h3 class="email-modal-title">Send Margin Report</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">Organization</label>
            <input type="text" :value="marginReportEmailParam?.orgName || ''" class="form-control" disabled />
          </div>
          <div class="mb-3" v-if="marginReportEmailParam?.dateRange">
            <label class="form-label">Date Range</label>
            <input type="text" :value="marginReportEmailParam?.dateRange || ''" class="form-control" disabled />
          </div>
          <div class="mb-3">
            <label class="form-label">Lines Count</label>
            <input type="text" :value="marginReportEmailParam?.records?.length || 0" class="form-control" disabled />
          </div>
          <div class="mb-3">
            <label class="form-label">Attachment Type</label>
            <div class="attachment-type-selector">
              <button
                type="button"
                class="attachment-btn"
                :class="{ active: form.attachmentType === 'pdf' }"
                @click="form.attachmentType = 'pdf'"
              >
                <span class="tf-icon ti ti-file-type-pdf ti-sm me-1"></span>
                PDF
              </button>
              <button
                type="button"
                class="attachment-btn"
                :class="{ active: form.attachmentType === 'csv' }"
                @click="form.attachmentType = 'csv'"
              >
                <span class="tf-icon ti ti-file-type-csv ti-sm me-1"></span>
                CSV
              </button>
            </div>
          </div>
          <div class="mb-3">
            <label class="form-label">Language</label>
            <div class="select is-fullwidth">
              <select v-model="partnerLanguage" @change="updateMessageForLanguage">
                <option value="de_DE">German</option>
                <option value="en_US">English</option>
              </select>
            </div>
          </div>
          <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="8" placeholder="Enter email message"></textarea>
          </div>
          <div class="mb-3">
            <small class="text-muted">The margin report will be attached as a {{ attachmentLabel }} file to this 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-primary" @click="sendReport" :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 Report ({{ attachmentLabel }})</span>
          </button>
        </div>
      </div>
    </div>
  </Teleport>
</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; }
.form-control:disabled { background-color: #f5f5f5; cursor: not-allowed; }
textarea.form-control { resize: vertical; }
.text-muted { color: #6c757d; }
.button-primary { background-color: #3273dc; color: white; border-color: #3273dc; }
.button-primary:hover { background-color: #2366d1; }
.mb-3 { margin-bottom: 1rem; }
.cursor-pointer { cursor: pointer; }
.select { width: 100%; }
.select select { width: 100%; padding: 0.5rem 0.75rem; border: 1px solid #ddd; border-radius: 4px; font-size: 0.875rem; background-color: white; }
.attachment-type-selector { display: flex; gap: 8px; }
.attachment-btn { display: inline-flex; align-items: center; padding: 0.5rem 1rem; border: 2px solid #ddd; border-radius: 6px; background: white; cursor: pointer; font-size: 0.875rem; font-weight: 500; transition: all 0.15s ease; }
.attachment-btn:hover { border-color: #3273dc; color: #3273dc; }
.attachment-btn.active { border-color: #3273dc; background-color: #eef3fc; color: #3273dc; font-weight: 600; }
</style>
