<script setup lang="ts">
import { ref } from 'vue'
import { cn } from '@/lib/utils'
import { useLocalTranslation } from '@/lib/composables/useLocalTranslation'
import Rating from './Rating.vue'
import Button from '@/components/shared/Button.vue'
import PoweredBy from '@/ui/PoweredBy.vue'
import type { ReviewProps } from '@/lib/types'
import SolarCloseCircleLineDuotone from '~icons/solar/close-circle-line-duotone'

const COMMENT_MAX_LENGTH = 500

withDefaults(defineProps<{
  isSubmitting?: boolean
}>(), { isSubmitting: false })

const emit = defineEmits<{
  submit: [payload: ReviewProps]
  close: []
}>()

const { t } = useLocalTranslation()
const rating = ref(0)
const comment = ref('')
const error = ref<{ comment?: string; rating?: string }>({})

const hasRating = () => rating.value >= 1 && rating.value <= 5

function handleRatingChange(val: number) {
  rating.value = val
  if (error.value.rating && val >= 1 && val <= 5) {
    error.value = { ...error.value, rating: undefined }
  }
}

function handleCommentChange(e: Event) {
  const value = (e.target as HTMLTextAreaElement).value
  comment.value = value
  if (error.value.comment && value.length <= COMMENT_MAX_LENGTH) {
    error.value = { ...error.value, comment: undefined }
  }
}

function validateAndSubmit() {
  const newError: typeof error.value = {}
  const trimmedComment = comment.value.trim()
  if (!hasRating()) newError.rating = t('homeSdk.ReviewDialog.rating_error') || 'Rating must be between 1 and 5.'
  if (trimmedComment.length > COMMENT_MAX_LENGTH) newError.comment = t('homeSdk.ReviewDialog.comment_error') || 'Comment must be max 500 chars.'
  if (Object.keys(newError).length > 0) { error.value = newError; return }
  error.value = {}
  emit('submit', { rating: rating.value, comment: trimmedComment })
}
</script>

<template>
  <section class="babylai:absolute babylai:inset-0 babylai:z-50 babylai:flex babylai:items-end babylai:rounded-3xl babylai:overflow-hidden">
    <div class="babylai:absolute babylai:inset-0 babylai:bg-black/60" @click="$emit('close')" />
    <div class="babylai:flex babylai:flex-col babylai:bg-card babylai:rounded-2xl babylai:w-full babylai:z-50 babylai:shadow-lg">
      <div class="babylai:flex babylai:flex-col babylai:p-6 babylai:pb-5 babylai:w-full">
        <button class="babylai:border-0 babylai:p-0 babylai:flex babylai:bg-transparent babylai:cursor-pointer babylai:mb-6 babylai:ms-auto babylai:text-card-foreground" type="button" @click="$emit('close')">
          <SolarCloseCircleLineDuotone class="babylai:w-7 babylai:h-7" />
        </button>

        <section class="babylai:flex babylai:items-center babylai:justify-center babylai:border-b babylai:border-black-white-200 babylai:pb-6 babylai:mb-6">
          <Rating :value="rating" size="lg" @change="handleRatingChange" />
        </section>

        <h2 class="babylai:text-2xl! babylai:text-center babylai:font-bold! babylai:mb-2! babylai:text-card-foreground">{{ t('homeSdk.ReviewDialog.title') }}</h2>
        <p class="babylai:text-xs babylai:text-center babylai:text-muted-foreground babylai:mb-4 babylai:leading-snug">{{ t('homeSdk.ReviewDialog.description') }}</p>

        <div v-if="hasRating()" class="babylai:flex babylai:flex-col babylai:gap-6 babylai:mt-6">
          <p class="babylai:text-sm babylai:text-card-foreground babylai:leading-snug">{{ t('homeSdk.InChatReview.follow_up') }}</p>
          <div class="babylai:flex babylai:flex-col babylai:gap-2">
            <textarea
              :class="cn(
                'babylai:resize-none babylai:w-full babylai:bg-secondary babylai:border babylai:rounded-xl babylai:text-card-foreground babylai:text-sm babylai:p-3 babylai:min-h-20 babylai:disabled:opacity-50',
                error.comment ? 'babylai:border-destructive' : 'babylai:border-black-white-200'
              )"
              :rows="4"
              :max-length="COMMENT_MAX_LENGTH"
              :placeholder="t('homeSdk.InChatReview.note_placeholder')"
              :value="comment"
              :aria-invalid="!!error.comment"
              @input="handleCommentChange"
            />
            <p v-if="error.comment" class="babylai:text-sm babylai:text-destructive" role="alert">{{ error.comment }}</p>
            <p class="babylai:text-xs babylai:text-muted-foreground">{{ comment.length }}/{{ COMMENT_MAX_LENGTH }}</p>
          </div>
        </div>

        <footer class="babylai:flex babylai:justify-between babylai:gap-3 babylai:mt-6">
          <Button variant="secondary" :disabled="isSubmitting" @click="$emit('close')">{{ t('homeSdk.ReviewDialog.skip_button') }}</Button>
          <Button variant="default" :disabled="isSubmitting || !hasRating()" @click="validateAndSubmit">
            <span v-if="isSubmitting" class="babylai:inline-flex babylai:items-center babylai:gap-2">
              <span class="babylai:inline-block babylai:animate-spin babylai:rounded-full babylai:h-4 babylai:w-4 babylai:border-2 babylai:border-white babylai:border-t-transparent babylai:box-border" aria-hidden="true" />
              {{ t('homeSdk.ReviewDialog.submit_button') }}
            </span>
            <span v-else>{{ t('homeSdk.ReviewDialog.submit_button') }}</span>
          </Button>
        </footer>
      </div>
      <PoweredBy />
    </div>
  </section>
</template>
