<template>
  <div class="tarea-form-container" :style="{ backgroundColor: uiStore.tableBgColorTareas }">
    <h2>{{ formTitle }}</h2>
    <form @submit.prevent="handleSubmit">
      <div class="form-group">
        <label for="titulo">Título:</label>
        <input type="text" id="titulo" v-model="formData.titulo" />
        <span v-if="formErrors.titulo" class="error-message">{{ formErrors.titulo }}</span>
      </div>

      <div class="form-group">
        <label for="empleado_id">Empleado ID:</label>
        <input type="number" id="empleado_id" v-model.number="formData.empleado_id" />
        <span v-if="formErrors.empleado_id" class="error-message">{{ formErrors.empleado_id }}</span>
      </div>
      
      <div class="form-group">
        <label for="fecha">Fecha:</label>
        <input type="date" id="fecha" v-model="formData.fecha" />
        <span v-if="formErrors.fecha" class="error-message">{{ formErrors.fecha }}</span>
      </div>

      <div class="form-group">
        <label for="estado">Estado:</label>
        <select id="estado" v-model="formData.estado">
          <option value="pendiente">Pendiente</option>
          <option value="en progreso">En Progreso</option>
          <option value="completada">Completada</option>
          <option value="cancelada">Cancelada</option>
        </select>
        <span v-if="formErrors.estado" class="error-message">{{ formErrors.estado }}</span>
      </div>

      <div class="form-group">
        <label for="tipo">Tipo:</label>
        <input type="text" id="tipo" v-model="formData.tipo" />
        <span v-if="formErrors.tipo" class="error-message">{{ formErrors.tipo }}</span>
      </div>

      <div class="form-group">
        <label for="precio">Precio (Opcional):</label>
        <input type="number" step="any" id="precio" v-model.number="formData.precio" />
        <span v-if="formErrors.precio" class="error-message">{{ formErrors.precio }}</span>
      </div>

      <div class="form-group">
        <label for="planilla_id">Planilla ID (Opcional):</label>
        <input type="number" id="planilla_id" v-model.number="formData.planilla_id" />
        <span v-if="formErrors.planilla_id" class="error-message">{{ formErrors.planilla_id }}</span>
      </div>

      <div class="form-group">
        <label for="observacion">Observación (Opcional):</label>
        <textarea id="observacion" v-model="formData.observacion" rows="3"></textarea>
      </div>

      <div class="form-actions">
        <button type="submit" :disabled="isSubmitting">{{ isSubmitting ? 'Guardando...' : 'Guardar' }}</button>
        <button type="button" @click="handleCancel" :disabled="isSubmitting">Cancelar</button>
      </div>
    </form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed, watch } from 'vue';
import { useTareasStore } from '../../stores/useTareas';
import { useUi } from '@/stores/useUi'; // Corrected UI store import
import { useRouter, useRoute } from 'vue-router';

const props = defineProps({
  id: String, 
});

const router = useRouter();
const route = useRoute(); 
const tareasStore = useTareasStore();
const uiStore = useUi(); // Corrected UI store instantiation

const formatDateForInput = (dateString) => {
  const date = dateString ? new Date(dateString) : new Date();
  // Apply timezone offset correction to ensure the date displayed is the intended "local" date
  const userTimezoneOffset = date.getTimezoneOffset() * 60000;
  const correctedDate = new Date(date.getTime() - userTimezoneOffset);
  return correctedDate.toISOString().split('T')[0];
};

const getDefaultFormData = () => ({
  titulo: '',
  empleado_id: null,
  planilla_id: null,
  precio: null,
  estado: 'pendiente',
  observacion: '',
  fecha: formatDateForInput(null), 
  tipo: '',
});

const formData = reactive(getDefaultFormData());
const formErrors = reactive({
  titulo: '',
  empleado_id: '',
  fecha: '',
  estado: '',
  tipo: '',
  precio: '',
  planilla_id: '',
});

const isSubmitting = ref(false);
const editingId = ref(route.params.id || props.id || null); 

const formTitle = computed(() => (editingId.value ? 'Editar Tarea' : 'Crear Nueva Tarea'));

const loadTareaForEditing = async (id) => {
  try {
    await tareasStore.fetchTareaById(id);
    if (tareasStore.currentTarea && String(tareasStore.currentTarea.id) === String(id)) {
      Object.assign(formData, {
        ...tareasStore.currentTarea,
        fecha: formatDateForInput(tareasStore.currentTarea.fecha),
        empleado_id: tareasStore.currentTarea.empleado_id ? Number(tareasStore.currentTarea.empleado_id) : null,
        planilla_id: tareasStore.currentTarea.planilla_id ? Number(tareasStore.currentTarea.planilla_id) : null,
        precio: tareasStore.currentTarea.precio ? parseFloat(tareasStore.currentTarea.precio) : null,
      });
    } else {
      console.error(`Failed to load tarea data for ID: ${id} or ID mismatch.`);
      router.push({ name: 'TareasIndex' }); 
    }
  } catch (error) {
    console.error(`Error fetching tarea ${id} for editing:`, error);
    router.push({ name: 'TareasIndex' }); 
  }
};

onMounted(() => {
  if (editingId.value) {
    loadTareaForEditing(editingId.value);
  }
  // else, new form uses default data, already set
});

watch(() => route.params.id, (newId) => {
  editingId.value = newId || null; // Update editingId when route changes
  if (newId) {
    loadTareaForEditing(newId);
  } else {
    // Navigated to create form from an edit form or similar scenario
    Object.assign(formData, getDefaultFormData());
  }
});

onUnmounted(() => {
  tareasStore.clearCurrentTarea(); 
});

const validateForm = () => {
  let isValid = true;
  Object.keys(formErrors).forEach(key => formErrors[key] = ''); 

  if (!formData.titulo?.trim()) {
    formErrors.titulo = 'El título es obligatorio.';
    isValid = false;
  }
  if (formData.empleado_id == null || isNaN(Number(formData.empleado_id)) || Number(formData.empleado_id) <= 0) {
    formErrors.empleado_id = 'El ID de empleado es obligatorio y debe ser un número positivo.';
    isValid = false;
  }
  if (!formData.fecha) {
    formErrors.fecha = 'La fecha es obligatoria.';
    isValid = false;
  }
  if (!formData.estado) {
    formErrors.estado = 'El estado es obligatorio.';
    isValid = false;
  }
   if (!formData.tipo?.trim()) { 
    formErrors.tipo = 'El tipo es obligatorio.';
    isValid = false;
  }
  if (formData.precio != null && (isNaN(parseFloat(formData.precio)) || parseFloat(formData.precio) < 0)) {
    formErrors.precio = 'El precio, si se ingresa, debe ser un número positivo.';
    isValid = false;
  }
  if (formData.planilla_id != null && (formData.planilla_id !== '' && (isNaN(Number(formData.planilla_id)) || Number(formData.planilla_id) <= 0))) {
    // Allow empty string for planilla_id, but if a value is present, it must be a positive number
    formErrors.planilla_id = 'El ID de planilla, si se ingresa, debe ser un número positivo.';
    isValid = false;
  }
  return isValid;
};

const handleSubmit = async () => {
  if (!validateForm()) return;

  isSubmitting.value = true;
  const payload = {
    ...formData,
    empleado_id: Number(formData.empleado_id),
    // Send null if planilla_id is empty or not a number, otherwise send the number
    planilla_id: (formData.planilla_id && !isNaN(Number(formData.planilla_id))) ? Number(formData.planilla_id) : null,
    precio: (formData.precio != null && formData.precio !== '') ? parseFloat(formData.precio) : null,
    // API expects date as YYYY-MM-DD string or full ISO. Input type="date" provides YYYY-MM-DD.
    // If API needs full DateTime, convert: new Date(formData.fecha + 'T00:00:00Z').toISOString()
  };

  try {
    if (editingId.value) {
      await tareasStore.updateTarea(editingId.value, payload);
    } else {
      await tareasStore.createTarea(payload);
    }
    router.push({ name: 'tareas-index' }); 
  } catch (error) {
    console.error('Error saving tarea:', error);
    alert(`Error al guardar la tarea: ${error}`);
  } finally {
    isSubmitting.value = false;
  }
};

const handleCancel = () => {
  router.go(-1); 
};
</script>

<style scoped>
.tarea-form-container {
  max-width: 650px;
  margin: 20px auto;
  padding: 25px;
  /* background-color: #f9f9f9; */ /* Removed to use dynamic background */
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

h2 {
  text-align: center;
  color: var(--accent-color-tareas); /* Accent color for form title */
  margin-bottom: 25px;
}

.form-group {
  margin-bottom: 18px;
}

.form-group label {
  display: block;
  margin-bottom: 6px;
  font-weight: bold;
  color: #555;
}

.form-group input[type="text"],
.form-group input[type="number"],
.form-group input[type="date"],
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  font-size: 1em;
}

.form-group textarea {
  resize: vertical; 
}

.error-message {
  display: block;
  color: #e74c3c; 
  font-size: 0.9em;
  margin-top: 5px;
}

.form-actions {
  margin-top: 25px;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.form-actions button {
  padding: 10px 18px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 1em;
  font-weight: 500;
  transition: background-color 0.2s ease, box-shadow 0.2s ease;
}

.form-actions button[type="submit"] {
  background-color: var(--accent-color-tareas);
  color: white;
}
.form-actions button[type="submit"]:hover {
  filter: brightness(0.9);
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.form-actions button[type="submit"]:disabled {
  background-color: var(--secondary-color); /* Use secondary for disabled */
  opacity: 0.7;
  cursor: not-allowed;
}

.form-actions button[type="button"] {
  background-color: var(--secondary-color); /* Use secondary for cancel */
  color: var(--text-color); /* Ensure text contrasts with secondary */
}
.form-actions button[type="button"]:hover {
  filter: brightness(0.9);
}
.form-actions button[type="button"]:disabled {
  background-color: var(--secondary-color);
  opacity: 0.5;
  cursor: not-allowed;
}

/* Also update input focus color if not already using a global variable */
.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  border-color: var(--accent-color-tareas);
  box-shadow: 0 0 0 2px var(--accent-color-tareas);
}
</style>
