<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { AlertTriangle } from "lucide-vue-next";
import { useSportsStore } from "../stores/sports";
import { useSportsEditBus } from "../composables/useSportsEditBus";
import {
  getIMCBgClass,
  getIMCInterpretation,
  getGradeBgClass,
  getAnxietyLabel,
  getAnxietyColor,
} from "../composables/useHelpers";

const store = useSportsStore();
const router = useRouter();
const editBus = useSportsEditBus();

const editingId = ref(null);
const form = ref(emptyForm());

onMounted(() => {
  const act = editBus.consume();
  if (act) startEdit(act);
});

function emptyForm() {
  return {
    studentId: "",
    type: "",
    durationInput: null,
    durationUnit: "min",
    intensity: "Moyenne",
    lifestyle: "Actif",
    anxiety: 0,
    grade: "Bien",
    date: new Date().toISOString().substr(0, 10),
  };
}

function startEdit(act) {
  editingId.value = act.id;
  form.value = JSON.parse(JSON.stringify(act));
  store.showNotification("Modification en cours...");
}

function cancelEdit() {
  editingId.value = null;
  form.value = emptyForm();
}

function saveActivity() {
  const v = form.value;
  if (!v.studentId || !v.type || !v.durationInput) return;
  store.saveActivity(v, editingId.value);
  editingId.value = null;
  form.value = emptyForm();
  router.push("/history");
}

const grades = ["Excellent", "Très bien", "Bien", "Assez bien", "Redouble"];
const lifestyles = ["Inactif", "Sédentaire", "Actif", "Très actif"];
</script>

<template>
  <div class="max-w-3xl mx-auto space-y-6">
    <!-- No students warning -->
    <div
      v-if="store.students.length === 0"
      class="bg-orange-100 p-6 rounded-3xl border border-orange-200 text-orange-800 flex gap-4 items-center italic"
    >
      <AlertTriangle class="w-5 h-5 shrink-0" />
      Inscrire d'abord des étudiants.
    </div>

    <div
      v-else
      class="bg-white p-8 rounded-3xl card-shadow border-t-8 transition-all"
      :class="editingId ? 'border-amber-500' : 'border-sky-400'"
    >
      <header class="mb-6 flex justify-between items-center">
        <h4 class="text-xl font-bold text-blue-900 italic">
          {{ editingId ? "Modifier l'Activité" : "Nouveau Log d'Activité" }}
        </h4>
        <button
          v-if="editingId"
          @click="cancelEdit"
          class="text-xs font-black text-rose-500 uppercase border border-rose-200 px-3 py-1 rounded-full hover:bg-rose-50 transition-colors"
        >
          Annuler l'édition
        </button>
      </header>

      <form @submit.prevent="saveActivity" class="space-y-6">
        <!-- Student selector -->
        <div>
          <label
            class="block text-sm font-black text-blue-900 mb-2 uppercase italic"
            >Étudiant concerné</label
          >
          <select
            v-model="form.studentId"
            :disabled="!!editingId"
            class="w-full p-4 rounded-2xl bg-blue-50 border-none outline-none font-bold text-blue-900"
          >
            <option value="">Sélectionnez un étudiant</option>
            <option v-for="s in store.students" :key="s.id" :value="s.id">
              {{ s.lastName }} {{ s.firstName }}
            </option>
          </select>

          <!-- Student quick stats -->
          <div v-if="form.studentId" class="mt-4 grid grid-cols-2 gap-3">
            <div class="p-4 bg-blue-50 border border-blue-100 rounded-2xl">
              <p class="text-[9px] font-black text-blue-400 uppercase mb-1">
                Moyenne Académique
              </p>
              <span
                :class="[
                  'px-2 py-0.5 rounded-full text-[10px] font-black uppercase text-white',
                  getGradeBgClass(
                    store.getStudentAverageLiteral(form.studentId),
                  ),
                ]"
              >
                {{ store.getStudentAverageLiteral(form.studentId) }}
              </span>
            </div>
            <div
              class="p-4 bg-gray-50 border border-gray-100 rounded-2xl text-right"
            >
              <p class="text-[9px] font-black text-gray-400 uppercase mb-1">
                Statut Physique
              </p>
              <span
                :class="[
                  'px-2 py-0.5 rounded-full text-[10px] font-black uppercase text-white',
                  getIMCBgClass(store.getSelectedStudentIMC(form.studentId)),
                ]"
              >
                {{
                  getIMCInterpretation(
                    store.getSelectedStudentIMC(form.studentId),
                  )
                }}
              </span>
            </div>
          </div>
        </div>

        <!-- Grade buttons -->
        <div class="bg-indigo-50/50 p-6 rounded-2xl border border-indigo-100">
          <label
            class="block text-sm font-black text-indigo-900 mb-4 uppercase italic"
            >Saisie de l'Évaluation</label
          >
          <div class="grid grid-cols-2 md:grid-cols-5 gap-2">
            <button
              v-for="g in grades"
              :key="g"
              type="button"
              @click="form.grade = g"
              :class="[
                'py-2 px-1 rounded-xl text-[9px] font-black uppercase transition-all border-2',
                form.grade === g
                  ? 'bg-indigo-600 text-white border-transparent shadow-md'
                  : 'bg-white text-indigo-400 border-indigo-100 hover:bg-indigo-50',
              ]"
            >
              {{ g }}
            </button>
          </div>
        </div>

        <!-- Lifestyle buttons -->
        <div>
          <label
            class="block text-sm font-black text-blue-900 mb-3 uppercase italic"
            >Profil de Sédentarisme</label
          >
          <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
            <button
              v-for="level in lifestyles"
              :key="level"
              type="button"
              @click="form.lifestyle = level"
              :class="[
                'py-3 px-2 rounded-xl text-[10px] font-black uppercase transition-all border-2',
                form.lifestyle === level
                  ? 'gradient-brand text-white border-transparent shadow-md'
                  : 'bg-blue-50 text-blue-400 border-transparent hover:bg-blue-100',
              ]"
            >
              {{ level }}
            </button>
          </div>
        </div>

        <!-- Anxiety slider -->
        <div class="bg-blue-50/50 p-6 rounded-2xl border border-blue-100">
          <div class="flex justify-between items-center mb-4">
            <label class="text-sm font-black text-blue-900 uppercase italic"
              >Anxiété (0–21)</label
            >
            <span
              :class="[
                'px-3 py-1 rounded-full text-xs font-black uppercase border shadow-sm',
                getAnxietyColor(form.anxiety),
              ]"
            >
              {{ getAnxietyLabel(form.anxiety) }}
            </span>
          </div>
          <input
            v-model.number="form.anxiety"
            type="range"
            min="0"
            max="21"
            class="w-full"
          />
        </div>

        <!-- Date -->
        <div>
          <label
            class="block text-sm font-black text-blue-900 mb-2 uppercase italic"
            >Date</label
          >
          <input
            v-model="form.date"
            type="date"
            class="w-full p-4 rounded-2xl bg-blue-50 border-none outline-none font-bold"
          />
        </div>

        <!-- Activity type -->
        <div>
          <label
            class="block text-sm font-black text-blue-900 mb-2 uppercase italic"
            >Type d'activité physique</label
          >
          <select
            v-model="form.type"
            class="w-full p-4 rounded-2xl bg-blue-50 border-none outline-none focus:ring-2 focus:ring-blue-500 font-bold"
          >
            <option value="">Quelle activité ?</option>
            <optgroup label="Sports Marocains">
              <option value="Football">Football</option>
              <option value="Course de durée">Course de durée</option>
              <option value="Course de vitesse">Course de vitesse</option>
              <option value="Basketball">Basketball</option>
              <option value="Boxe">Boxe</option>
              <option value="Tennis">Tennis</option>
              <option value="Badminton">Badminton</option>
              <option value="Pétanque">Pétanque</option>
            </optgroup>
            <optgroup label="Autres">
              <option value="Marche">Marche</option>
              <option value="Cyclisme">Cyclisme</option>
              <option value="Natation">Natation</option>
              <option value="Yoga">Yoga</option>
              <option value="Musculation">Musculation</option>
            </optgroup>
          </select>
        </div>

        <!-- Intensity + Duration -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div>
            <label
              class="block text-sm font-black text-blue-900 mb-2 uppercase italic"
              >Intensité</label
            >
            <select
              v-model="form.intensity"
              class="w-full p-4 rounded-2xl bg-blue-50 border-none font-bold text-sm"
            >
              <option value="Basse">Basse</option>
              <option value="Moyenne">Moyenne</option>
              <option value="Haute">Haute</option>
            </select>
          </div>
          <div>
            <label
              class="block text-sm font-black text-blue-900 mb-2 uppercase italic"
              >Durée</label
            >
            <div class="flex gap-2">
              <input
                v-model.number="form.durationInput"
                type="number"
                placeholder="30"
                class="w-full p-4 rounded-2xl bg-blue-50 border-none font-bold text-sm"
              />
              <select
                v-model="form.durationUnit"
                class="p-4 rounded-2xl bg-blue-50 border-none font-black text-blue-900 text-xs"
              >
                <option value="sec">sec</option>
                <option value="min">min</option>
                <option value="h">h</option>
              </select>
            </div>
          </div>
        </div>

        <button
          type="submit"
          class="w-full py-4 rounded-2xl text-white font-black shadow-lg mt-4 uppercase tracking-widest transition-all"
          :class="
            editingId
              ? 'bg-amber-500 hover:bg-amber-600'
              : 'gradient-brand hover:opacity-90'
          "
        >
          {{
            editingId
              ? "Mettre à jour l'activité"
              : "Enregistrer Activité & Évaluation"
          }}
        </button>
      </form>
    </div>
  </div>
</template>
