<template>
  <div v-if="props.data.length > 0" class="q-mx-md q-mb-md">
    <div class="scroll-wrapper">
      <div class="scroll-track">
        <q-card
          v-for="item in props.data"
          :key="item.id"
          class="today-card card-border shadow-card bg-surface"
          :flat="false"
        >
          <q-card-section class="q-pa-md">
            <div class="row no-wrap items-start q-mb-xs">
              <div class="col-8 row">
                <q-avatar size="40px" class="flex-shrink-0 q-mr-sm">
                  <span
                    :style="avatarColors[item.id % avatarColors.length]"
                    class="text-weight-bold full-width full-height flex flex-center"
                    style="font-size:14px; border-radius:50%;"
                  >
                    {{ item.client_name?.slice(0, 2).toUpperCase() ?? '??' }}
                  </span>
                </q-avatar>

                <div class="col column no-wrap overflow-hidden justify-center">
                  <span class="text-caption text-text">
                    <template v-if="cardState(item) === 'finished'">
                      {{ $t('provider.dashboard.today_services.finished_label') }}
                      <span class="text-weight-bold"> {{ ' ' + item.client_name ?? '—' }}</span>
                      {{ ' ' + $t('provider.dashboard.today_services.finished_suffix') }}
                    </template>
                    <template v-else>
                      {{ $t('provider.dashboard.today_services.start_label') }}
                      <span class="text-weight-bold"> {{ ' ' + item.client_name ?? '—' }}</span>
                    </template>
                  </span>
                  <div class="row items-center q-mt-xs no-wrap">
                    <q-icon name="mdi-clock-outline" size="12px" class="q-mr-xs gradient-diarista" />
                    <span class="hours-font text-grey-5">
                      {{ $t('common.from') }} {{  item.start_time?.slice(0, 5) }} {{ $t('common.to') }} {{ item.end_time?.slice(0, 5) }}
                    </span>
                  </div>
                </div>
              </div>

              <div class="flex-shrink-0 row items-center justify-center col-4">
                <div v-if="cardState(item) === 'awaiting_code'" class="col-12 row items-center justify-center q-pb-sm q-px-sm">
                  <div class="hint-text text-caption text-text text-center q-mb-xs col-12">
                    {{ $t('provider.dashboard.today_services.code_hint') }}
                  </div>
                  <!-- <div class="hint-text text-caption text-text text-center q-mb-xs col-12">
                    {{ $t('provider.dashboard.today_services.code_hint2') }}
                  </div> -->
                  <div class="code-input-row col-12">
                    <input
                      v-for="(_, idx) in 4"
                      :key="idx"
                      :ref="el => setCodeRef(item.id, idx, el)"
                      v-model="codeInputs[item.id][idx]"
                      class="code-input-box"
                      type="tel"
                      maxlength="1"
                      inputmode="numeric"
                      @input="onCodeInput(item, idx)"
                      @keydown.delete="onCodeDelete(item.id, idx)"
                      @paste.prevent="onCodePaste(item, $event)"
                    />
                  </div>
                  <div v-if="codeError[item.id]" class="text-negative code-error-text q-mt-xs text-center">
                    {{ codeError[item.id] }}
                  </div>
                </div>

                <div v-else-if="cardState(item) === 'in_progress'" class="col-12 text-center q-mb-xs">
                  <div class="column items-center">
                    <span class="badge-status-text text-text text-weight-bold q-my-xs">
                      {{ $t('provider.dashboard.today_services.in_progress') }}
                    </span>
                    <div class="code-pill bg-positive row">
                      <q-icon
                        name="mdi-check" size="12px" class="q-mr-xs q-my-auto"
                      />
                      {{ item.code || localVerified[item.id] }}
                    </div>
                  </div>
                </div>

                <div v-else>
                  <div v-if="item.provider_reviewed" class="rate-btn reviewed-badge">
                    <q-icon name="mdi-star" size="14px" class="q-mr-xs" />
                    {{ $t('provider.dashboard.today_services.reviewed_badge') }}
                  </div>
                  <q-btn
                    v-else
                    unelevated no-caps
                    class="rate-btn"
                    @click.stop="emit('rate', item)"
                  >
                    <div class="column items-center">
                      <q-icon name="mdi-star-outline" size="12px" class="q-mr-xs" />
                      {{ $t('provider.dashboard.today_services.rate_btn') }}
                    </div>
                  </q-btn>
                </div>
              </div>
            </div>

            <div class="progress-track q-mb-sm">
              <div
                class="progress-fill"
                :class="cardState(item) === 'finished' ? 'progress-fill--finished' : ''"
                :style="{ width: progressByState(item) + '%' }"
              />
            </div>

            <div class="row items-center no-wrap">
              <q-btn
                flat no-caps dense
                :label="$t('provider.dashboard.today_services.help')"
                color="primary"
                size="sm"
                class="flex-shrink-0"
                @click.stop="openHelp"
              />
              <q-space />
              <template v-if="cardState(item) === 'in_progress'">
                <q-icon name="mdi-clock-outline" size="13px" class="q-mr-xs flex-shrink-0 gradient-diarista" />
                <span class="text-caption text-grey-6 text-right text-no-wrap">
                  {{ $t('provider.dashboard.today_services.end_time_label') }} 
                  <span class="gradient-diarista">{{ calculateTimeUntilEnd(item.end_time) }}</span>
                </span>
              </template>
              <template v-else-if="cardState(item) === 'awaiting_code'">
                <q-icon name="mdi-map-marker-outline" size="13px" color="grey-6" class="q-mr-xs flex-shrink-0" />
                <span class="text-caption text-grey-6 col ellipsis text-right">
                  {{ [item.address?.address, item.address?.number, item.address?.district].filter(Boolean).join(', ') || '—' }}
                </span>
              </template>
            </div>
          </q-card-section>
        </q-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive } from 'vue'
import { useQuasar } from 'quasar'
import { useI18n } from 'vue-i18n'
import ProfileHelpDialog from 'src/components/profile/ProfileHelpDialog.vue'
import { verifyScheduleCode } from 'src/api/schedule'

const props = defineProps({ data: { type: Array, default: () => [] } })
const emit = defineEmits(['rate', 'refresh'])

const $q = useQuasar()
const { t } = useI18n()

const codeInputs    = reactive({})
const codeRefs      = reactive({})
const codeError     = reactive({})
const localVerified = reactive({})

const ensureCode = (id) => {
  if (!codeInputs[id]) codeInputs[id] = ['', '', '', '']
  if (!codeRefs[id])   codeRefs[id]   = [null, null, null, null]
}

props.data.forEach(item => ensureCode(item.id))

const setCodeRef = (id, idx, el) => {
  ensureCode(id)
  codeRefs[id][idx] = el
}

const onCodeInput = async (item, idx) => {
  const id  = item.id
  const val = codeInputs[id][idx]
  if (!/^\d$/.test(val)) { codeInputs[id][idx] = ''; return }
  codeError[id] = null
  if (idx < 3) {
    codeRefs[id][idx + 1]?.focus()
  } else {
    await submitCode(item)
  }
}

const onCodeDelete = (id, idx) => {
  if (codeInputs[id][idx] === '' && idx > 0) {
    codeInputs[id][idx - 1] = ''
    codeRefs[id][idx - 1]?.focus()
  }
}

const onCodePaste = async (item, e) => {
  const text = e.clipboardData.getData('text').replace(/\D/g, '').slice(0, 4)
  if (text.length !== 4) return
  const id = item.id
  text.split('').forEach((ch, i) => { codeInputs[id][i] = ch })
  await submitCode(item)
}

const submitCode = async (item) => {
  const id   = item.id
  const code = codeInputs[id].join('')
  if (code.length < 4) return
  try {
    const response = await verifyScheduleCode(id, code)
    console.log(response)
    if (response?.payload) {
      localVerified[id] = code
      emit('refresh')
    } else {
      const msg = response?.data?.message || response?.message || t('provider.dashboard.today_services.code_error')
      codeError[id] = msg
      codeInputs[id] = ['', '', '', '']
      codeRefs[id][0]?.focus()
    }
  } catch (err) {
    const msg = err?.response?.data?.message || t('provider.dashboard.today_services.code_error')
    codeError[id] = msg
    codeInputs[id] = ['', '', '', '']
    codeRefs[id][0]?.focus()
  }
}

const avatarColors = [
  { background: '#ffd5df', color: '#932e57' },
  { background: '#d7e8ff', color: '#2158a8' },
  { background: '#dfd',    color: '#2a7a3b' },
  { background: '#ffe5cc', color: '#8a4500' },
]

const cardState = (item) => {
  const verified = item.code_verified || !!localVerified[item.id]
  if (!verified) return 'awaiting_code'
  const [h, m] = (item.end_time || '23:59').slice(0, 5).split(':').map(Number)
  const endTime = new Date()
  endTime.setHours(h, m, 0, 0)
  return new Date() >= endTime ? 'finished' : 'in_progress'
}

const progressByState = (item) => {
  const state = cardState(item)
  if (state === 'awaiting_code') return 60
  if (state === 'in_progress')   return 80
  return 100
}

const calculateTimeUntilEnd = (endTimeStr) => {
  const [h, m] = (endTimeStr || '23:59').slice(0, 5).split(':').map(Number)
  const now = new Date()
  const endTime = new Date()
  endTime.setHours(h, m, 0, 0)
  const diffMs = endTime - now
  if (diffMs <= 0) return '00:00'
  const diffH = Math.floor(diffMs / (1000 * 60 * 60))
  const diffM = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60))
  return `${String(diffH).padStart(2, '0')}h:${String(diffM).padStart(2, '0')}`
}

const openHelp = () => {
  $q.dialog({ component: ProfileHelpDialog })
}
</script>

<style scoped lang="scss">
.scroll-wrapper { overflow: hidden; }
.scroll-track {
  display: flex;
  flex-direction: row;
  gap: 12px;
  overflow-x: auto;
  overscroll-behavior-x: contain;
  scroll-snap-type: x proximity;
  padding-bottom: 8px;
  &::-webkit-scrollbar { display: none; }
  &::after { content: ''; flex: 0 0 1px; }
}

.today-card {
  min-width: 80%;
  scroll-snap-align: start;
  border-radius: 12px;
}

.hint-text {
  max-width: 100px;
  line-height: 1.3;
  font-size: 9px;
}

.code-input-row { 
  display: flex;
  align-items: center; 
  justify-content: center; 
  gap: 4px; background: #d1d5db; 
  border-radius: 999px; 
  padding: 4px 8px; 
  width: 110px; 
  height: 28px; 
  margin: 0 auto; 
}

.code-input-box { 
  width: 16px; 
  height: 18px; 
  background: transparent; 
  border: none; 
  border-bottom: 2px solid white; 
  border-radius: 0; 
  text-align: center; 
  font-size: 11px; 
  font-weight: 700; 
  color: #1a1a2e; 
  outline: none; 
  caret-color: transparent; 
  &:focus { 
    border-bottom: 2px solid #ffffff; 
    box-shadow: none; 
  } 
}

.code-error-text {
  font-size: 9px;
  max-width: 110px;
  line-height: 1.2;
}

.code-pill {
  color: white;
  font-weight: 800;
  font-size: 12px;
  letter-spacing: 2px;
  border-radius: 20px;
  padding: 1px 8px;
}

.badge-status-text {
  font-size: 11px;
  
}

.rate-btn {
  background: #EC4899;
  color: white;
  font-weight: 600;
  font-size: 11px;
  white-space: nowrap;
  border-radius: 10px !important;
  min-width: 45px;
  min-height: 40px;
  padding: 3px 5px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.reviewed-badge {
  cursor: default;
  opacity: 0.85;
  font-size: 11px;
}

.progress-track {
  width: 100%;
  height: 5px;
  background: #E2E8F0;
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  border-radius: 3px;
  background: linear-gradient(90deg, #8B5CF6, #EC4899);
  transition: width 0.4s ease;

  &--finished {
    background: #22c55e;
  }
}

.hours-font {
  font-size: 11px;
}
</style>
