<template>
  <div class="ssd">
    <BoxedIconTitleBlock
      class="ssd__heading"
      :title="session?.title || 'جزئیات جلسه'"
      :desc="session?.desc || 'اطلاعات کامل این جلسه را مشاهده کنید.'"
    >
      <template #icon>
        <SvgIcon name="book" :size="24" color="var(--color-primary)" />
      </template>
    </BoxedIconTitleBlock>

    <SkeletonLoaderBlock v-if="isLoading && !session" :rows="3" :cols-per-row="1" />
    <div v-else class="ssd__panel">
      <div class="ssd__prompt">
        <SvgIcon name="warning" :size="22" color="#b8b8b8" class="ssd__prompt-icon" />
        <p class="ssd__prompt-text">
          {{
            session?.homeworkPrompt || homework?.description || 'متنی برای این جلسه ثبت نشده است.'
          }}
        </p>
      </div>

      <div class="ssd__media">
        <div class="ssd__content">
          <div v-if="contentKind === 'video'" class="ssd__video">
            <VideoPlayerBlock
              :src="session?.videoUrl || ''"
              :poster="session?.poster || ''"
              :video-id="sessionId"
            />
          </div>
          <div v-else-if="contentKind === 'audio'" class="ssd__audio">
            <VoiceRecorder :model-value="session?.audioUrl" disabled />
          </div>
          <div v-else-if="contentKind === 'text'" class="ssd__text">
            <SvgIcon name="warning" :size="22" color="#b8b8b8" class="ssd__text-icon" />
            <p class="ssd__text-body">{{ session.text }}</p>
          </div>
          <div v-else-if="contentKind === 'link'" class="ssd__link">
            <div class="ssd__link__box">
              <span>https://link</span>
              <SvgIcon name="link" :size="22" class="ssd__link-icon" />
            </div>
            <BaseButton text="ورود به جلسه " custom-class="ssd__link-btn">
              <template #appendIcon>
                <SvgIcon name="arrow-left" :size="18" color="#fff" />
              </template>
            </BaseButton>
          </div>
          <div v-else class="ssd__empty">
            <SvgIcon name="warning" :size="32" color="#bcbcbc" />
            <p>محتوایی برای این جلسه ثبت نشده است.</p>
          </div>
        </div>

        <div class="ssd__uploads" v-if="contentKind !== 'link'">
          <VoiceRecorder
            class="ssd__uploads-recorder"
            v-model="homeworkAudio"
            :error="errors.audio"
          />
          <ImageUploader
            class="ssd__uploads-uploader"
            v-model="homeworkImage"
            :error="errors.image"
          />
        </div>
      </div>

      <div class="ssd__hint">
        <SvgIcon name="warning" :size="22" color="#b8b8b8" />
        <p class="ssd__hint-text">
          {{ session?.homeworkHint || homework?.title || '' }}
        </p>
      </div>

      <div class="ssd__footer">
        <BaseButton
          text="ارسال تکلیف"
          :loading="submitMutation.isPending.value"
          :disabled="!canSubmit"
          custom-class="ssd__submit-btn"
          @click="onSubmit"
        >
          <template #appendIcon>
            <SvgIcon name="arrow-left" :size="18" color="#fff" />
          </template>
        </BaseButton>
      </div>
    </div>
  </div>
</template>

<script setup>
import { toast } from 'vue3-toastify'
import { useRoute } from 'vue-router'
import { computed, reactive, ref } from 'vue'
import SvgIcon from '@/components/icons/SvgIcon.vue'
import BaseButton from '@/components/BaseButton.vue'
import { objectToFormData } from '@/utils/object-to-formdata'
import { useUploadMediaMutation } from '@/services/query/auth'
import VoiceRecorder from '@/components/form/VoiceRecorder.vue'
import ImageUploader from '@/components/form/ImageUploader.vue'
import VideoPlayerBlock from '@/components/blocks/VideoPlayerBlock.vue'
import BoxedIconTitleBlock from '@/components/blocks/BoxedIconTitleBlock.vue'
import SkeletonLoaderBlock from '@/components/blocks/SkeletonLoaderBlock.vue'
import { useStudentHomeworksListQuery } from '@/services/query/student-homeworks'
import {
  useStudentSessionQuery,
  useSubmitStudentHomeworkMutation,
} from '@/services/query/student-sessions'

const route = useRoute()

const sessionId = computed(() => route.params.id)

const { data: session, isLoading } = useStudentSessionQuery(sessionId, {
  enabled: () => !!sessionId.value,
})

const homeworkFilters = computed(() => ({ sessionId: sessionId.value }))
const homeworkPagination = ref({ page: 1, perPage: 20 })
const { data: homeworksData } = useStudentHomeworksListQuery(homeworkFilters, homeworkPagination, {
  enabled: () => !!sessionId.value,
})
const homework = computed(() => (homeworksData.value?.data ?? [])[0] ?? null)

const contentKind = computed(() => {
  const s = session.value
  if (!s) return ''
  if (s.type === 'online') return 'link'
  if (s.videoUrl) return 'link'
  if (s.audioUrl) return 'audio'
  if (s.text) return 'text'
  return ''
})

const homeworkAudio = ref(null)
const homeworkImage = ref(null)
const errors = reactive({ audio: '', image: '' })

const canSubmit = computed(() => !!(homeworkAudio.value || homeworkImage.value))

const submitMutation = useSubmitStudentHomeworkMutation()
const uploadMediaMutation = useUploadMediaMutation()

const homeworkId = computed(
  () => homework.value?.id ?? session.value?.homeworkId ?? session.value?.homework?.id ?? null
)

const uploadHomeworkFile = async (file) => {
  // The backend validates allowed extensions per `purpose`: `homework_file`
  // accepts documents/images only, so a recorded voice must go up as `voice`.
  const isAudio = (file?.type || '').startsWith('audio/')
  const fd = objectToFormData({
    file,
    purpose: isAudio ? 'voice' : 'homework_file',
    context: 'homework',
  })
  const response = await uploadMediaMutation.mutateAsync(fd)
  const payload = response?.data ?? response
  return payload?.id ?? null
}

const onSubmit = async () => {
  if (!canSubmit.value) {
    errors.audio = 'حداقل یک فایل صوتی یا تصویر ارسال کنید.'
    return
  }
  if (!homeworkId.value) {
    toast.error('تکلیفی برای این جلسه ثبت نشده است.')
    return
  }
  errors.audio = ''
  errors.image = ''
  try {
    const files = [homeworkAudio.value, homeworkImage.value].filter(Boolean)
    for (const file of files) {
      const mediaId = await uploadHomeworkFile(file)
      if (!mediaId) throw new Error('upload failed')
      await submitMutation.mutateAsync({
        homeworkId: homeworkId.value,
        payload: { mediaId },
      })
    }
    toast.success('تکلیف با موفقیت ارسال شد.')
    homeworkAudio.value = null
    homeworkImage.value = null
  } catch {
    toast.error('ارسال تکلیف با خطا مواجه شد.')
  }
}
</script>

<style lang="scss" scoped>
.ssd {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;

  &__heading {
    margin-bottom: 0.75rem;
  }

  &__media {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  &__panel {
    display: flex;
    flex-direction: column;
    gap: 0.875rem;
  }

  &__prompt {
    display: flex;
    align-items: flex-start;
    gap: 0.625rem;
    padding: 0.75rem 1rem;
    background: rgba(255, 255, 255, 58%);
    box-shadow: 0 6.75px 19.425px rgba(0, 0, 0, 4%);
    border-radius: 1rem;
  }

  &__prompt-icon {
    flex-shrink: 0;
    margin-top: 0.125rem;
  }

  &__prompt-text {
    font-family: var(--font-family-fa);
    font-weight: 400;
    font-size: 0.875rem;
    line-height: 1.7;
    color: #5d5d5d;
    margin: 0;
    text-align: justify;
  }

  &__content {
    width: 100%;
  }

  &__uploads {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 0.875rem;
    height: -webkit-fill-available;

    &-uploader {
      height: stretch;
    }

    :global(.voice-recorder) {
      height: stretch;
      background-color: #eee !important;
    }
  }

  &__link {
    display: flex;
    align-items: center;
    gap: 1rem;

    &__box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 0.625rem;
      padding: 0.625rem 1rem;
      border: 1px solid #ddd;
      border-radius: 50px;
      width: 100%;
    }

    &__icon {
      flex-shrink: 0;
    }
  }

  &__hint {
    display: flex;
    align-items: center;
    gap: 0.625rem;
    padding: 0.625rem 1rem;
    background: #eee;
    border-radius: 1rem;
  }

  &__hint-text {
    font-family: var(--font-family-fa);
    font-weight: 400;
    font-size: 0.875rem;
    line-height: 1.7;
    color: #5d5d5d;
    margin: 0;
    text-align: justify;
    flex: 1;
  }

  &__footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 0.5rem;
  }

  &__submit-btn {
    min-width: 18rem;
    padding: 0 2rem;
  }
}
</style>
