<!-- /src/views/sessions/SessionFormView.vue -->
<template>
  <div class="session-form-view w-full max-w-5xl mx-auto">
    <PageHeader
      :title="isEditMode ? $t('sessions.editSession') : $t('sessions.addSession')"
      :subtitle="isEditMode ? 'ویرایش اطلاعات جلسه آموزشی' : 'تعریف جلسه جدید'"
    >
      <Button label="انصراف" text severity="secondary" @click="$router.push('/sessions')" />
    </PageHeader>

    <div class="surface-card p-4 sm:p-5 border-round border-1 border-color shadow-sm relative overflow-hidden">
      <LoadingOverlay :loading="isFetching" message="در حال دریافت اطلاعات جلسه..." />
      <form @submit.prevent="handleSubmit" class="grid">
        <div class="col-12 md:col-6 flex flex-column gap-2">
          <label class="font-semibold text-sm">انتخاب دوره *</label>
          <Dropdown
            v-model="form.course"
            :options="courses"
            optionLabel="title"
            optionValue="_id"
            placeholder="دوره را انتخاب کنید"
            class="w-full text-sm"
            filter
            @change="onCourseChange"
          />
        </div>

        <div class="col-12 md:col-6 flex flex-column gap-2">
          <label class="font-semibold text-sm">کلاس *</label>
          <Dropdown
            v-model="form.class"
            :options="classes"
            optionLabel="name"
            optionValue="_id"
            placeholder="کلاس را انتخاب کنید"
            class="w-full text-sm"
            :disabled="!form.course"
            filter
          />
        </div>

        <div class="col-12 md:col-6 flex flex-column gap-2">
          <label class="font-semibold text-sm">استاد مدرس *</label>
          <Dropdown v-model="form.professor" :options="professors" optionLabel="name" optionValue="_id" placeholder="استاد را انتخاب کنید" class="w-full text-sm" filter />
        </div>

        <div class="col-12 md:col-6 flex flex-column gap-2">
          <label class="font-semibold text-sm">{{ $t('sessions.date') }} *</label>
          <DatePicker v-model="form.day" class="w-full text-sm" :placeholder="getTodayJalali()" />
        </div>

        <div class="col-12 md:col-3 flex flex-column gap-2">
          <label class="font-semibold text-sm">{{ $t('courses.startTime') }} *</label>
          <InputText v-model="form.startTime" class="w-full text-sm" dir="ltr" placeholder="19:00" />
        </div>

        <div class="col-12 md:col-3 flex flex-column gap-2">
          <label class="font-semibold text-sm">{{ $t('courses.endTime') }} *</label>
          <InputText v-model="form.endTime" class="w-full text-sm" dir="ltr" placeholder="20:30" />
        </div>

        <div class="col-12 md:col-6 flex flex-column gap-2">
          <label class="font-semibold text-sm">وضعیت جلسه</label>
          <Dropdown v-model="form.status" :options="statusOptions" optionLabel="label" optionValue="value" class="w-full text-sm" />
        </div>

        <div class="col-12 md:col-6 flex flex-column gap-2">
          <label class="font-semibold text-sm">مکان برگزاری</label>
          <InputText v-model="form.place" class="w-full text-sm" placeholder="کلاس / آنلاین / آدرس" />
        </div>

        <div class="col-12 flex flex-column gap-2">
          <label class="font-semibold text-sm">{{ $t('sessions.topic') }}</label>
          <InputText v-model="form.topic" class="w-full text-sm" placeholder="عنوان یا موضوع این جلسه" />
        </div>

        <div class="col-12 flex flex-column gap-2">
          <label class="font-semibold text-sm">یادداشت جلسه</label>
          <Textarea v-model="form.note" rows="3" class="w-full text-sm" placeholder="یادداشت داخلی درباره این جلسه…" />
        </div>

        <div class="col-12">
          <AdminNotesField v-model="form.adminNotes" />
        </div>

        <div class="col-12 flex justify-content-end gap-2 mt-4 pt-3 border-top-1 border-color">
          <Button label="انصراف" text severity="secondary" @click="$router.push('/sessions')" />
          <Button type="submit" :label="$t('app.save')" icon="pi pi-check" :loading="isSubmitting" />
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import moment from 'jalali-moment';
import { sessionApi } from '@/api/sessionApi';
import { courseApi } from '@/api/courseApi';
import { classApi } from '@/api/classApi';
import { professorApi } from '@/api/professorApi';
import { usePersianDate } from '@/composables/usePersianDate';
import { useToast } from '@/composables/useToast';
import PageHeader from '@/components/common/PageHeader.vue';
import LoadingOverlay from '@/components/common/LoadingOverlay.vue';
import AdminNotesField from '@/components/common/AdminNotesField.vue';
import InputText from 'primevue/inputtext';
import Textarea from 'primevue/textarea';
import Dropdown from 'primevue/select';
import DatePicker from 'vue3-persian-datetime-picker';
import Button from 'primevue/button';

const route = useRoute();
const router = useRouter();
const { showSuccess, showError } = useToast();
const { toLatinDigits, toJalaliPickerValue, toGregorianIso, getTodayJalali } = usePersianDate();

const sessionId = route.params.id;
const isEditMode = computed(() => !!sessionId);

const isFetching = ref(false);
const isSubmitting = ref(false);
const courses = ref([]);
const classes = ref([]);
const professors = ref([]);

const statusOptions = [
  { label: 'طبق برنامه', value: 'scheduled' },
  { label: 'برگزارشده', value: 'held' },
  { label: 'لغوشده', value: 'cancelled' }
];

const form = reactive({
  course: null,
  class: null,
  professor: null,
  day: getTodayJalali(),
  startTime: '19:00',
  endTime: '20:30',
  status: 'scheduled',
  topic: '',
  place: '',
  note: '',
  adminNotes: []
});

const loadClasses = async (courseId) => {
  if (!courseId) {
    classes.value = [];
    return;
  }
  try {
    const res = await classApi.getAll({ limit: 100, courseId });
    const data = res.data || res;
    classes.value = Array.isArray(data) ? data : (data.items || data.data || []);
  } catch (err) {
    console.warn('Failed to load classes for course:', err);
    classes.value = [];
  }
};

const onCourseChange = async () => {
  form.class = null;
  await loadClasses(form.course);
};

const fetchData = async () => {
  isFetching.value = true;
  try {
    const [cResult, pResult] = await Promise.allSettled([
      courseApi.getAll({ limit: 100 }),
      professorApi.getAll({ limit: 100 })
    ]);

    if (cResult.status === 'fulfilled') {
      const cRes = cResult.value;
      const cData = cRes.data || cRes;
      courses.value = Array.isArray(cData) ? cData : (cData.items || cData.courses || cData.data || []);
    }

    if (pResult.status === 'fulfilled') {
      const pRes = pResult.value;
      const pData = pRes.data || pRes;
      professors.value = (Array.isArray(pData) ? pData : (pData.items || pData.professors || pData.data || [])).map((p) => ({
        ...p,
        name: `${p.name || ''} ${p.surname || ''}`.trim()
      }));
    }

    if (sessionId) {
      const res = await sessionApi.getOne(sessionId);
      const data = res.data || res;
      const courseId = data.course?._id || data.course || null;
      await loadClasses(courseId);
      Object.assign(form, {
        course: courseId,
        class: data.class?._id || data.class || null,
        professor: data.professor?._id || data.professor || null,
        day: toJalaliPickerValue(data.day || data.date) || getTodayJalali(),
        startTime: data.startTime || '19:00',
        endTime: data.endTime || '20:30',
        status: data.status || 'scheduled',
        topic: data.topic || '',
        place: data.place || '',
        note: data.note || '',
        adminNotes: Array.isArray(data.adminNotes) ? [...data.adminNotes] : []
      });
    }
  } catch (err) {
    showError(err);
  } finally {
    isFetching.value = false;
  }
};

const handleSubmit = async () => {
  if (!form.course) { showError('لطفا دوره را انتخاب کنید'); return; }
  if (!form.class) { showError('لطفا کلاس را انتخاب کنید'); return; }
  if (!form.professor) { showError('لطفا استاد را انتخاب کنید'); return; }
  if (!form.day) { showError('لطفا تاریخ جلسه را وارد کنید'); return; }
  if (!form.startTime || !form.endTime) { showError('ساعت شروع و پایان الزامی است'); return; }

  const dayIso = toGregorianIso(form.day);
  if (!dayIso) { showError('تاریخ جلسه نامعتبر است'); return; }

  isSubmitting.value = true;
  try {
    const payload = {
      course: form.course,
      class: form.class,
      professor: form.professor,
      day: dayIso,
      startTime: form.startTime,
      endTime: form.endTime,
      status: form.status,
      topic: form.topic,
      place: form.place,
      note: form.note,
      adminNotes: (form.adminNotes || []).map((n) => String(n).trim()).filter(Boolean)
    };

    if (isEditMode.value) {
      await sessionApi.update(sessionId, payload);
      showSuccess('جلسه با موفقیت ویرایش شد');
    } else {
      await sessionApi.create(payload);
      showSuccess('جلسه جدید با موفقیت ایجاد شد');
    }
    router.push('/sessions');
  } catch (err) {
    showError(err);
  } finally {
    isSubmitting.value = false;
  }
};

onMounted(fetchData);
</script>
