<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>

    <TabsBlock :tabs="tabs" v-model="activeTab" @change-tab="onTabChange">
      <template #homework>
        <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 || 'متنی برای این جلسه ثبت نشده است.' }}
            </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">
                <SvgIcon name="paper-plane-right" :size="40" color="rgba(0, 112, 116, 0.31)" />
                <audio :src="session.audioUrl" controls class="ssd__audio-player" />
              </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 || '' }}
            </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>
      </template>

      <template #exam>
        <NoItems title="در حال انتقال" desc="در حال انتقال به صفحه آزمون..." />
      </template>
    </TabsBlock>
  </div>
</template>

<script setup>
import { toast } from 'vue3-toastify'
import { computed, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import SvgIcon from '@/components/icons/SvgIcon.vue'
import BaseButton from '@/components/BaseButton.vue'
import NoItems from '@/components/blocks/NoItems.vue'
import TabsBlock from '@/components/blocks/TabsBlock.vue'
import { objectToFormData } from '@/utils/object-to-formdata'
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 {
  useStudentSessionQuery,
  useSubmitStudentSessionHomeworkMutation,
} from '@/services/query/student-sessions'

const route = useRoute()
const router = useRouter()

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

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

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

const tabs = [
  { name: 'homework', label: 'ارسال تکلیف', icon: 'list-bullets' },
  { name: 'exam', label: 'آزمـــــون', icon: 'file' },
]
const activeTab = ref('homework')

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

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

const submitMutation = useSubmitStudentSessionHomeworkMutation()

const onSubmit = async () => {
  if (!canSubmit.value) {
    errors.audio = 'حداقل یک فایل صوتی یا تصویر ارسال کنید.'
    return
  }
  errors.audio = ''
  errors.image = ''
  try {
    const payload = { subType: 'homework' }
    if (homeworkAudio.value) payload.audio = homeworkAudio.value
    if (homeworkImage.value) payload.image = homeworkImage.value
    const fd = objectToFormData(payload)
    await submitMutation.mutateAsync({ id: sessionId.value, payload: fd })
    toast.success('تکلیف با موفقیت ارسال شد.')
    homeworkAudio.value = null
    homeworkImage.value = null
  } catch {
    toast.error('ارسال تکلیف با خطا مواجه شد.')
  }
}

const onTabChange = (name) => {
  if (name !== 'exam') return
  const examId = session.value?.examId
  if (examId) {
    router.push({ name: 'student-exam', params: { id: examId } }).catch(() => {})
  } else {
    toast.info('آزمونی برای این جلسه ثبت نشده است.')
    activeTab.value = 'homework'
  }
}
</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: center;
    margin-top: 0.5rem;
  }

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