<template>
  <q-dialog ref="dialogRef" @hide="onDialogHide">
    <q-card class="q-dialog-plugin" style="width: 700px; max-width: 90vw">
      <DefaultDialogHeader :title="() => $t('schedules.schedule_details')" @close="onDialogCancel" />

      <q-card-section>
        <div class="row q-col-gutter-md">
          <div class="col-12 col-md-6">
            <div class="text-caption text-grey-7">{{ $t('schedules.client') }}</div>
            <div class="text-body1">{{ schedule?.client_name || 'N/A' }}</div>
          </div>

          <div class="col-12 col-md-6">
            <div class="text-caption text-grey-7">{{ $t('schedules.provider') }}</div>
            <div class="text-body1">{{ schedule?.provider_name || 'N/A' }}</div>
          </div>

          <div class="col-12">
            <div class="text-caption text-grey-7">{{ $t('schedules.address') }}</div>
            <div class="text-body1">{{ formatAddress(schedule?.address) }}</div>
          </div>

          <div class="col-12 col-md-6">
            <div class="text-caption text-grey-7">{{ $t('schedules.date') }}</div>
            <div class="text-body1">{{ schedule?.date }}</div>
          </div>

          <div class="col-12 col-md-6">
            <div class="text-caption text-grey-7">{{ $t('schedules.period') }}</div>
            <div class="text-body1">{{ schedule?.period_type }} {{ $t('schedules.hours') }}</div>
          </div>

          <div class="col-12 col-md-6">
            <div class="text-caption text-grey-7">{{ $t('schedules.start_time') }}</div>
            <div class="text-body1">{{ schedule?.start_time?.substring(0, 5) }}</div>
          </div>

          <div class="col-12 col-md-6">
            <div class="text-caption text-grey-7">{{ $t('schedules.end_time') }}</div>
            <div class="text-body1">{{ schedule?.end_time?.substring(0, 5) }}</div>
          </div>

          <div class="col-12 col-md-6">
            <div class="text-caption text-grey-7">{{ $t('schedules.total_amount') }}</div>
            <div class="text-body1 text-weight-bold text-positive">
              {{ formatToBRLCurrency(schedule?.total_amount) }}
            </div>
          </div>

          <div class="col-12 col-md-6">
            <div class="text-caption text-grey-7">{{ $t('schedules.status') }}</div>
            <q-badge :color="getStatusColor(schedule?.status)" class="q-pa-sm">
              {{ $t(`schedules.statuses.${schedule?.status}`) }}
            </q-badge>
          </div>

          <div class="col-6">
            <div class="text-caption text-grey-7">{{ $t('schedules.code') }}</div>
            <div class="text-body1">
              {{ schedule?.code }}
            </div>
          </div>
          <div class="col-6 col-md-6">
            <div class="text-caption text-grey-7">{{ $t('schedules.code_verified') }}</div>
            <q-icon
              :name="schedule.code_verified ? 'check_circle' : 'cancel'"
              :color="schedule.code_verified ? 'positive' : 'negative'"
              size="sm"
            />
          </div>
        </div>
      </q-card-section>

      <q-card-actions align="right" class="q-px-md q-pb-md">
        <q-btn
          :label="$t('common.actions.close')"
          flat
          color="primary"
          @click="onDialogCancel"
        />
        <q-btn
          v-if="schedule?.status === 'paid'"
          unelevated
          :label="$t('schedules.cancel_schedule')"
          color="negative"
          @click="handleCancel"
        />
        <template v-if="viewMode === 'provider'">
          <template v-if="schedule?.status === 'pending'">
            <q-btn
              unelevated
              :label="$t('schedules.reject')"
              color="negative"
              @click="handleReject"
            />
            <q-btn
              unelevated
              :label="$t('schedules.accept')"
              color="positive"
              @click="handleAccept"
            />
          </template>
          <q-btn
            v-if="schedule?.status === 'paid'"
            unelevated
            :label="$t('schedules.fill_code')"
            color="secondary"
            @click="fillCode"
          />
        </template>

        <template v-if="viewMode === 'client'">
          <q-btn
            v-if="schedule?.status === 'accepted'"
            unelevated
            :label="$t('schedules.mark_as_paid')"
            color="positive"
            @click="handleMarkAsPaid"
          />
        
        </template>
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup>
import { useDialogPluginComponent, useQuasar } from 'quasar'
import { verifyScheduleCode } from 'src/api/customSchedule'
import { useI18n } from 'vue-i18n'
import DefaultDialogHeader from 'src/components/defaults/DefaultDialogHeader.vue'
import { formatToBRLCurrency } from 'src/helpers/utils'

const props = defineProps({
  schedule: {
    type: Object,
    required: true
  },
  viewMode: {
    type: String,
    required: true,
    validator: (value) => ['client', 'provider'].includes(value)
  }
})

const emit = defineEmits([
  ...useDialogPluginComponent.emits,
  // 'accept',
  // 'reject',
  // 'mark-as-paid',
  // 'cancel'
])

const $q = useQuasar()
const { t } = useI18n()
const { dialogRef, onDialogHide, onDialogCancel, onDialogOK } = useDialogPluginComponent()

const formatAddress = (address) => {
  if (!address) return 'N/A'
  const parts = [
    address.address,
    address.complement,
    address.zip_code,
    address.city,
    address.state
  ].filter(Boolean)
  return parts.join(', ')
}

const getStatusColor = (status) => {
  const colors = {
    pending: 'warning',
    accepted: 'positive',
    rejected: 'negative',
    paid: 'info',
    cancelled: 'dark',
    started: 'primary',
    finished: 'positive'
  }
  return colors[status] || 'grey'
}

const handleAccept = () => {
    $q.dialog({
    title: t('schedules.accept'),
    message: t('common.ui.messages.confirm_action'),
    cancel: true,
    persistent: true
  }).onOk(async () => {
    emit('accept', props.schedule.id);
    onDialogOK();
  })
}

const handleReject = () => {
  $q.dialog({
    title: t('schedules.reject'),
    message: t('common.ui.messages.confirm_action'),
    cancel: true,
    persistent: true
  }).onOk(async () => {
    emit('reject', props.schedule.id);
    onDialogOK();
  })
}

const handleMarkAsPaid = () => {
  $q.dialog({
    title: t('schedules.mark_as_paid'),
    message: t('common.ui.messages.confirm_action'),
    cancel: true,
    persistent: true
  }).onOk(async () => {
    onDialogOK();
    emit('mark-as-paid', props.schedule.id);
  })
}

const handleCancel = () => {
  $q.dialog({
    title: t('schedules.cancel_schedule'),
    message: t('common.ui.messages.confirm_action'),
    cancel: true,
    persistent: true
  }).onOk(async () => {
    onDialogOK();
    emit('cancel', props.schedule.id);
  })
}

const fillCode = () => {
  $q.dialog({
    title: t('schedules.fill_code'),
    message: t('schedules.enter_code'),
    prompt: {
      model: '',
      type: 'text'
    },
    cancel: true,
    persistent: true
  }).onOk(async (code) => {
    const response = await verifyScheduleCode(props.schedule.id, code)
    if(response.data.success) {
      $q.notify({
        type: 'positive',
        message: t('schedules.code_verified_success'),
        position: 'top'
      })
    } else {
      $q.notify({
        type: 'negative',
        message: t('schedules.code_verified_failed'),
        position: 'top'
      })
    }
    emit('refreshData');
    onDialogOK();
  })
}
</script>
