<template>
  <webmailing-template>
    <template #webmailing-header>
      <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
          <h3 class="mb-0">
            <i class="fas fa-envelope"></i> Webmailing
          </h3>
          <small class="text-muted">Gérez vos campagnes d'email marketing</small>
        </div>
      </div>
    </template>

    <template #webmailing-tabs>
      <ul class="nav nav-tabs" role="tablist">
        <li class="nav-item" role="presentation">
          <button
            class="nav-link"
            :class="{ active: activeTab === 'compose' }"
            @click="activeTab = 'compose'"
            type="button"
          >
            <i class="fas fa-pen"></i> Composer
          </button>
        </li>
        <li class="nav-item" role="presentation">
          <button
            class="nav-link"
            :class="{ active: activeTab === 'history' }"
            @click="activeTab = 'history'"
            type="button"
          >
            <i class="fas fa-history"></i> Historique
          </button>
        </li>
      </ul>
    </template>

    <template #webmailing-content>
      <div class="tab-content mt-4">
        <!-- Compose Tab -->
        <div v-if="activeTab === 'compose'" class="tab-pane active">
          <webmailing-form
            :initial-data="formData"
            @form-data-change="updateFormData"
          />
          <div class="mt-4 d-flex justify-content-end gap-2">
            <soft-button
              color="secondary"
              variant="outline"
              @click="resetForm"
            >
              <i class="fas fa-redo"></i> Réinitialiser
            </soft-button>
            <soft-button
              color="success"
              @click="sendEmail"
            >
              <i class="fas fa-paper-plane"></i> Envoyer
            </soft-button>
          </div>
        </div>

        <!-- History Tab -->
        <div v-if="activeTab === 'history'" class="tab-pane active">
          <webmailing-list
            :emails="emailHistory"
            @view-email="handleViewEmail"
            @delete-email="handleDeleteEmail"
          />
        </div>
      </div>
    </template>
  </webmailing-template>
</template>

<script setup>
import { ref } from "vue";
import WebmailingTemplate from "@/components/templates/Webmailing/WebmailingTemplate.vue";
import WebmailingForm from "@/components/molecules/Webmailing/WebmailingForm.vue";
import WebmailingList from "@/components/molecules/Webmailing/WebmailingList.vue";
import SoftButton from "@/components/SoftButton.vue";

const activeTab = ref("compose");

const formData = ref({
  recipients: "",
  subject: "",
  body: "",
  attachments: [],
  sendCopy: false,
  scheduled: false,
  scheduledDate: "",
});

// Sample email history data
const emailHistory = ref([
  {
    id: 1,
    recipients: "client1@example.com, client2@example.com",
    subject: "Bienvenue chez Thanasoft",
    sentDate: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000),
    status: "sent",
  },
  {
    id: 2,
    recipients: "client3@example.com",
    subject: "Rappel de rendez-vous",
    sentDate: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000),
    status: "sent",
  },
  {
    id: 3,
    recipients: "client4@example.com, client5@example.com",
    subject: "Nouvelle fonctionnalité disponible",
    sentDate: new Date(),
    status: "scheduled",
  },
  {
    id: 4,
    recipients: "client6@example.com",
    subject: "Documentation mise à jour",
    sentDate: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
    status: "sent",
  },
  {
    id: 5,
    recipients: "client7@example.com",
    subject: "Erreur d'envoi",
    sentDate: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000),
    status: "failed",
  },
]);

const updateFormData = (data) => {
  formData.value = data;
};

const resetForm = () => {
  formData.value = {
    recipients: "",
    subject: "",
    body: "",
    attachments: [],
    sendCopy: false,
    scheduled: false,
    scheduledDate: "",
  };
  alert("Formulaire réinitialisé");
};

const sendEmail = () => {
  // Validation
  if (!formData.value.recipients.trim()) {
    alert("Veuillez entrer au moins un destinataire");
    return;
  }
  if (!formData.value.subject.trim()) {
    alert("Veuillez entrer un sujet");
    return;
  }
  if (!formData.value.body.trim()) {
    alert("Veuillez entrer un contenu");
    return;
  }

  // Add new email to history
  const newEmail = {
    id: emailHistory.value.length + 1,
    recipients: formData.value.recipients,
    subject: formData.value.subject,
    sentDate: new Date(),
    status: formData.value.scheduled ? "scheduled" : "sent",
  };

  emailHistory.value.unshift(newEmail);
  alert(
    formData.value.scheduled
      ? "Email programmé avec succès!"
      : "Email envoyé avec succès!"
  );
  resetForm();
  activeTab.value = "history";
};

const handleViewEmail = (id) => {
  const email = emailHistory.value.find((e) => e.id === id);
  if (email) {
    alert(`Visualisation de l'email: ${email.subject}`);
  }
};

const handleDeleteEmail = (id) => {
  if (confirm("Êtes-vous sûr de vouloir supprimer cet email?")) {
    emailHistory.value = emailHistory.value.filter((e) => e.id !== id);
    alert("Email supprimé");
  }
};
</script>

<style scoped>
.nav-tabs .nav-link {
  color: #6c757d;
  cursor: pointer;
}

.nav-tabs .nav-link.active {
  color: #0d6efd;
  border-bottom: 3px solid #0d6efd;
}

.gap-2 {
  gap: 10px;
}
</style>
