<template>
  <div class="w-full min-h-screen px-4 md:px-10 pb-10">

    <!-- Breadcrumb -->
    <div class="text-sm breadcrumbs mb-4 pt-4">
      <ul>
        <li><router-link :to="{ name: 'customer' }">Customers</router-link></li>
        <li v-if="customer">
          <router-link :to="{ name: 'customerProfile', params: { id: customerId } }">
            {{ customer.customer_first_name }} {{ customer.customer_last_name }}
          </router-link>
        </li>
        <li>Alert</li>
      </ul>
    </div>

    <!-- Header -->
    <div class="flex items-center gap-4 mb-6">
      <router-link :to="{ name: 'customerProfile', params: { id: customerId } }" class="btn btn-ghost btn-sm">
        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
        </svg>
        Back
      </router-link>
      <div>
        <h1 class="text-2xl font-bold">Customer Alert</h1>
        <p v-if="customer" class="text-sm opacity-60">
          {{ customer.customer_first_name }} {{ customer.customer_last_name }} — #{{ customer.account_number }}
        </p>
      </div>
    </div>

    <div v-if="isLoading" class="flex justify-center mt-20">
      <span class="loading loading-spinner loading-lg"></span>
    </div>

    <div v-else class="grid grid-cols-1 xl:grid-cols-2 gap-6">

      <!-- Form card -->
      <div class="card-glass p-6">
        <h2 class="text-lg font-semibold mb-5">
          {{ existingAlert ? 'Edit Alert' : 'Add Alert' }}
        </h2>

        <!-- Severity selector -->
        <div class="form-control mb-6">
          <label class="label pb-1">
            <span class="label-text font-medium">Severity Level</span>
          </label>
          <div class="flex flex-col gap-3">
            <label class="flex items-start gap-3 cursor-pointer p-3 rounded-lg border-2 transition-colors"
                   :class="form.severity === 0 ? 'border-info bg-info/10' : 'border-base-300 hover:border-info/40'">
              <input type="radio" v-model="form.severity" :value="0" class="radio radio-info mt-0.5" />
              <div>
                <p class="font-semibold text-info">Info</p>
                <p class="text-xs opacity-70">Simple popup with an X button. Dismisses quickly.</p>
              </div>
            </label>
            <label class="flex items-start gap-3 cursor-pointer p-3 rounded-lg border-2 transition-colors"
                   :class="form.severity === 1 ? 'border-warning bg-warning/10' : 'border-base-300 hover:border-warning/40'">
              <input type="radio" v-model="form.severity" :value="1" class="radio radio-warning mt-0.5" />
              <div>
                <p class="font-semibold text-warning">Notice</p>
                <p class="text-xs opacity-70">Orange background with siren icons. Must click X to close.</p>
              </div>
            </label>
            <label class="flex items-start gap-3 cursor-pointer p-3 rounded-lg border-2 transition-colors"
                   :class="form.severity === 2 ? 'border-error bg-error/10' : 'border-base-300 hover:border-error/40'">
              <input type="radio" v-model="form.severity" :value="2" class="radio radio-error mt-0.5" />
              <div>
                <p class="font-semibold text-error">Critical</p>
                <p class="text-xs opacity-70">Cannot be dismissed without typing "confirm". For serious issues only.</p>
              </div>
            </label>
          </div>
        </div>

        <!-- Message -->
        <div class="form-control mb-6">
          <label class="label pb-1">
            <span class="label-text font-medium">Alert Message</span>
          </label>
          <textarea v-model="form.message"
                    class="textarea textarea-bordered w-full"
                    :class="{ 'textarea-error': messageError }"
                    rows="4"
                    placeholder="Describe the issue or reason for this alert..." />
          <p v-if="messageError" class="text-error text-xs mt-1">{{ messageError }}</p>
        </div>

        <!-- Action buttons -->
        <div class="flex flex-wrap gap-2">
          <button @click="saveAlert" class="btn btn-primary" :disabled="isSaving">
            <span v-if="isSaving" class="loading loading-spinner loading-xs mr-1"></span>
            {{ existingAlert ? 'Update Alert' : 'Create Alert' }}
          </button>
          <button v-if="existingAlert" @click="confirmDelete = true" class="btn btn-error btn-outline">
            Delete Alert
          </button>
          <router-link :to="{ name: 'customerProfile', params: { id: customerId } }" class="btn btn-ghost">
            Cancel
          </router-link>
        </div>
      </div>

      <!-- Preview card -->
      <div class="card-glass p-6">
        <h2 class="text-lg font-semibold mb-4">Preview</h2>
        <p class="text-sm opacity-60 mb-4">This is how the popup will appear on the customer profile.</p>

        <!-- Info preview -->
        <div v-if="form.severity === 0" class="border-2 border-base-300 rounded-xl p-4 bg-base-100">
          <div class="flex items-center justify-between mb-2">
            <div class="flex items-center gap-2">
              <svg class="w-6 h-6 text-info" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
              </svg>
              <span class="font-bold">Customer Alert</span>
            </div>
            <button class="btn btn-xs btn-circle btn-ghost">✕</button>
          </div>
          <p class="text-sm whitespace-pre-wrap">{{ form.message || 'Your alert message will appear here...' }}</p>
        </div>

        <!-- Notice preview -->
        <div v-else-if="form.severity === 1"
             class="rounded-xl p-4 bg-orange-500 text-white border-4 border-orange-700">
          <div class="flex items-center justify-between mb-3">
            <div class="flex items-center gap-2">
              <span class="text-xl">🚨</span>
              <span class="font-bold text-xl tracking-widest">NOTICE</span>
              <span class="text-xl">🚨</span>
            </div>
            <button class="btn btn-xs btn-circle bg-transparent border-white text-white">✕</button>
          </div>
          <div class="bg-orange-600 rounded-lg p-3">
            <p class="text-sm font-medium text-center whitespace-pre-wrap">
              {{ form.message || 'Your alert message will appear here...' }}
            </p>
          </div>
        </div>

        <!-- Critical preview -->
        <div v-else class="rounded-xl p-4 border-4 border-red-500" style="background-color: #1a0000;">
          <div class="text-center mb-3">
            <div class="text-3xl mb-2">⛔</div>
            <span class="font-bold text-xl text-red-400 tracking-wider">CRITICAL ALERT</span>
          </div>
          <div class="rounded-lg p-3 mb-4 border border-red-700" style="background-color: #3b0000;">
            <p class="text-white text-sm text-center whitespace-pre-wrap">
              {{ form.message || 'Your alert message will appear here...' }}
            </p>
          </div>
          <div class="space-y-2">
            <p class="text-red-300 text-xs text-center">
              Type <span class="font-mono font-bold text-white bg-red-800 px-1.5 py-0.5 rounded">confirm</span> to acknowledge
            </p>
            <div class="flex gap-2">
              <input disabled placeholder="confirm" class="input input-sm flex-1 bg-red-900 text-white border-red-600 opacity-50" />
              <button disabled class="btn btn-sm btn-error opacity-30">Close</button>
            </div>
          </div>
        </div>

        <!-- Existing alert info -->
        <div v-if="existingAlert" class="mt-4 p-3 bg-base-200 rounded-lg text-xs opacity-70">
          <p>Alert created: {{ formatDate(existingAlert.created_at) }}</p>
        </div>
      </div>
    </div>

    <!-- Delete confirmation modal -->
    <div class="modal" :class="{ 'modal-open': confirmDelete }">
      <div class="modal-box">
        <h3 class="font-bold text-lg">Delete Alert?</h3>
        <p class="py-3">This will remove the alert for this customer. It will no longer appear when their profile is opened.</p>
        <div class="modal-action">
          <button @click="deleteAlert" class="btn btn-error" :disabled="isSaving">
            <span v-if="isSaving" class="loading loading-spinner loading-xs mr-1"></span>
            Delete
          </button>
          <button @click="confirmDelete = false" class="btn btn-ghost">Cancel</button>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { customerService } from '../../services/customerService';
import { notify } from '@kyvg/vue3-notification';
import dayjs from 'dayjs';

interface CustomerAlert {
  id: number;
  customer_id: number;
  severity: number;
  message: string;
  created_at: string | null;
}

const route = useRoute();
const router = useRouter();

const customerId = computed(() => Number(route.params.id));
const customer = ref<any>(null);
const existingAlert = ref<CustomerAlert | null>(null);
const isLoading = ref(true);
const isSaving = ref(false);
const confirmDelete = ref(false);
const messageError = ref('');

const form = ref({ severity: 0, message: '' });

onMounted(async () => {
  await Promise.all([loadCustomer(), loadAlert()]);
  isLoading.value = false;
});

const loadCustomer = async () => {
  try {
    const res = await customerService.getById(customerId.value);
    customer.value = res.data?.customer || res.data;
  } catch {
    // ignore
  }
};

const loadAlert = async () => {
  try {
    const res = await customerService.getAlert(customerId.value);
    const alert = res.data?.alert || null;
    existingAlert.value = alert;
    if (alert) {
      form.value.severity = alert.severity;
      form.value.message = alert.message;
    }
  } catch {
    existingAlert.value = null;
  }
};

const saveAlert = async () => {
  messageError.value = '';
  if (!form.value.message.trim()) {
    messageError.value = 'Please enter a message.';
    return;
  }
  isSaving.value = true;
  try {
    const payload = { severity: form.value.severity, message: form.value.message.trim() };
    if (existingAlert.value) {
      const res = await customerService.updateAlert(customerId.value, payload);
      existingAlert.value = res.data.alert;
    } else {
      const res = await customerService.createAlert(customerId.value, payload);
      existingAlert.value = res.data.alert;
    }
    notify({ title: 'Saved', text: 'Alert saved successfully.', type: 'success' });
    router.push({ name: 'customerProfile', params: { id: customerId.value } });
  } catch {
    notify({ title: 'Error', text: 'Failed to save alert.', type: 'error' });
  } finally {
    isSaving.value = false;
  }
};

const deleteAlert = async () => {
  isSaving.value = true;
  try {
    await customerService.deleteAlert(customerId.value);
    existingAlert.value = null;
    form.value = { severity: 0, message: '' };
    confirmDelete.value = false;
    notify({ title: 'Deleted', text: 'Alert removed.', type: 'success' });
    router.push({ name: 'customerProfile', params: { id: customerId.value } });
  } catch {
    notify({ title: 'Error', text: 'Failed to delete alert.', type: 'error' });
  } finally {
    isSaving.value = false;
  }
};

const formatDate = (dateStr: string | null) => {
  if (!dateStr) return 'Unknown';
  return dayjs(dateStr).format('MMM D, YYYY h:mm A');
};
</script>
