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

const stockReportEmail = useStockReportEmail()
const stockReportEmailParam = useStockReportEmailParam()

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

const partnerLanguage = ref('de_DE')

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

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

const fetchPartnerData = async () => {
  const orgId = stockReportEmailParam.value?.organizationId
  if (!orgId) {
    updateMessageForLanguage()
    return
  }

  try {
    // Fetch organization's business partner email
    const res = await $fetch(`/api/admin/organizations/${orgId}/bpartner-email`, {
      headers: useRequestHeaders(['cookie'])
    })

    if (res?.email) {
      form.value.toEmail = res.email
    }
    // Get partner language
    partnerLanguage.value = res?.language || 'de_DE'
    // Update message based on language
    updateMessageForLanguage()
  } catch (err) {
    console.error('Error fetching partner data:', err)
    updateMessageForLanguage()
  }
}

// Format a 'YYYY-MM-DD' string to a localized date label
const formatAsOf = (ymd) => {
  if (!ymd) return ''
  const [y, m, d] = ymd.split('-')
  return `${d}.${m}.${y}`
}

const updateMessageForLanguage = () => {
  const organizationName = stockReportEmailParam.value?.organizationName || ''
  const recordCount = stockReportEmailParam.value?.records?.length || 0
  const asOfDate = stockReportEmailParam.value?.asOfDate || ''
  const asOf = formatAsOf(asOfDate)
  const isGerman = partnerLanguage.value.startsWith('de')
  const today = formatDate(new Date())

  if (isGerman) {
    form.value.subject = asOf
      ? `Bestandsbericht (Stichtag ${asOf}) - ${organizationName}`
      : `Bestandsbericht - ${organizationName} - ${today}`
    form.value.message = `Sehr geehrte Damen und Herren,

anbei finden Sie den ${asOf ? `Bestandsbericht zum Stichtag ${asOf}` : 'aktuellen Bestandsbericht'} fuer ${organizationName}.

Der Bericht enthaelt ${recordCount} Produkte.

Mit freundlichen Gruessen`
  } else {
    form.value.subject = asOf
      ? `Stock Report (as of ${asOf}) - ${organizationName}`
      : `Stock Report - ${organizationName} - ${today}`
    form.value.message = `Dear Sir or Madam,

Please find attached the ${asOf ? `stock report as of ${asOf}` : 'current stock report'} for ${organizationName}.

The report contains ${recordCount} products.

Best regards`
  }
}

const initForm = () => {
  // Fetch partner data (email and language) like payment reminder
  fetchPartnerData()
}

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

const formatLabel = computed(() => {
  return (stockReportEmailParam.value?.format || 'pdf').toUpperCase()
})

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 = stockReportEmailParam.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/materials/products/send-qty-report', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        toEmail: form.value.toEmail,
        ccEmail: form.value.ccEmail,
        subject: form.value.subject,
        message: form.value.message,
        records: records,
        organizationName: stockReportEmailParam.value?.organizationName || '',
        language: partnerLanguage.value,
        showByLocator: stockReportEmailParam.value?.showByLocator || false,
        asOfDate: stockReportEmailParam.value?.asOfDate || '',
        format: stockReportEmailParam.value?.format || 'pdf'
      }
    })

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

<template>
  <div class="email-modal-overlay" v-if="stockReportEmail" @click.self="closeModal">
    <div class="email-modal-container" @click.stop>
      <div class="email-modal-header">
        <h3 class="email-modal-title">Send Stock Report ({{ formatLabel }})</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="stockReportEmailParam?.organizationName || ''"
            class="form-control"
            disabled
          />
        </div>
        <div class="mb-3">
          <label class="form-label">Products Count</label>
          <input
            type="text"
            :value="stockReportEmailParam?.records?.length || 0"
            class="form-control"
            disabled
          />
        </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 stock report will be attached as a {{ formatLabel }} 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"
          :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 Report
          </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;
}
.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;
}
</style>