<template>
  <NucleoDataCard
    :title="`Tarea ID: ${tarea.id}`"
    :status="tarea.estado"
    :fields="cardFields"
    :accent-color="ui.accentColorTareas"
    :background-color="ui.tableBgColorTareas"
    :observation="tarea.observacion"
    @edit="editTarea"
    @delete="confirmDeleteTarea"
  >
    <template #header>
      <div class="flex items-center justify-between w-full">
        <h2 class="text-xl font-semibold" :style="{ color: ui.accentColorTareas }">Tarea ID: {{ tarea.id }}</h2>
        <span :class="['px-2 py-1 text-xs font-bold text-white rounded-full', getStatusClass(tarea.estado)]">
          {{ tarea.estado || 'N/A' }}
        </span>
      </div>
    </template>
  </NucleoDataCard>
</template>

<script setup>
import { defineProps, defineEmits, computed } from 'vue';
import { useTareasStore } from '../../stores/useTareas';
import { useUi } from '../../stores/useUi.js';
import NucleoDataCard from '../ui/NucleoDataCard.vue';

const ui = useUi();

const props = defineProps({
  tarea: {
    type: Object,
    required: true,
  },
});

const emit = defineEmits(['edit']);

const tareasStore = useTareasStore();

const formatDate = (dateString) => {
  if (!dateString) return 'N/A';
  const date = new Date(dateString);
  return date.toLocaleString('es-HN', { timeZone: 'America/Tegucigalpa', year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', hour12: true });
};

const formatCurrency = (value) => {
  if (value == null) return ''; // Return empty string if no price, so label doesn't show with 'N/A'
  return Number(value).toLocaleString('es-PY', {
    style: 'currency',
    currency: 'PYG',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  });
};

const cardFields = computed(() => {
  const fields = [
    { label: 'Título', value: props.tarea.titulo },
    { label: 'Empleado ID', value: props.tarea.empleado_id },
    { label: 'Fecha', value: formatDate(props.tarea.fecha) },
    { label: 'Tipo', value: props.tarea.tipo || 'N/A' },
  ];
  if (props.tarea.precio != null) {
    fields.push({ label: 'Precio', value: formatCurrency(props.tarea.precio) });
  }
  return fields;
});

const editTarea = () => {
  emit('edit', props.tarea.id);
};

const confirmDeleteTarea = () => {
  if (confirm(`¿Está seguro de que desea eliminar la tarea "${props.tarea.titulo}" (ID: ${props.tarea.id})?`)) {
    deleteTareaInternal();
  }
};

const deleteTareaInternal = async () => {
  try {
    await tareasStore.deleteTarea(props.tarea.id);
  } catch (error) {
    console.error('Error deleting tarea:', error);
    alert('Ocurrió un error al eliminar la tarea. Por favor, intente de nuevo.');
  }
};

const getStatusClass = (status) => {
  if (!status) return 'bg-gray-400 text-white';
  const statusNormalized = status.toLowerCase().replace(/\s+/g, '-');
  switch (statusNormalized) {
    case 'pendiente': return 'bg-yellow-500 text-gray-800';
    case 'realizada':
    case 'completada':
    case 'hecho': return 'bg-green-500 text-white';
    case 'en-progreso': return 'bg-blue-500 text-white';
    case 'anulada':
    case 'cancelada': return 'bg-red-500 text-white';
    case 'archivada': return 'bg-gray-500 text-white';
    default: return 'bg-gray-400 text-white';
  }
};
// buttonHover removed
</script>

<style scoped>
/* Scoped styles can be removed if NucleoDataCard's observation styling is acceptable.
   The .border-l-3 class is for the old observation styling.
*/
</style>
