<template>
    <div>
        <ul class="flex space-x-2 rtl:space-x-reverse">
            <li>
                <a href="javascript:;" class="text-primary hover:underline">Contracts</a>
            </li>
            <li class="before:content-['/'] ltr:before:mr-2 rtl:before:ml-2">
                <span>Credit Card Contracts</span>
            </li>
        </ul>

        <div class="pt-5">


            <div class="panel pb-0 mt-6">
                <h5 class="font-semibold text-lg dark:text-white-light mb-5">Contract List</h5>
                <div class="datatable">
                    <vue3-datatable :rows="contracts" :columns="cols" :totalRows="contracts?.length"
                        :isServerMode="false" skin="whitespace-nowrap bh-table-hover" :columnFilter="true"
                        :sortDirection="params.sort_direction" :sortColumn="params.sort_column" :sorteable="true"
                        firstArrow='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="w-4.5 h-4.5 rtl:rotate-180"> <path d="M13 19L7 12L13 5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> <path opacity="0.5" d="M16.9998 19L10.9998 12L16.9998 5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> </svg>'
                        lastArrow='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="w-4.5 h-4.5 rtl:rotate-180"> <path d="M11 19L17 12L11 5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> <path opacity="0.5" d="M6.99976 19L12.9998 12L6.99976 5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> </svg> '
                        previousArrow='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="w-4.5 h-4.5 rtl:rotate-180"> <path d="M15 5L9 12L15 19" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> </svg>'
                        nextArrow='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="w-4.5 h-4.5 rtl:rotate-180"> <path d="M9 5L15 12L9 19" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/> </svg>'>
                        <template #actions="data">
                            <div class="flex gap-4">
                                <button
                                    v-if="data.value.status != 'Cancelled' && data.value.status != 'Signed' && data.value.status != 'Viewed'"
                                    type="button" class="btn btn-success !py-1" :disabled="isSending"
                                    @click="handleSendContract(data.value)">
                                    {{ isSending ? 'Sending...' : 'Send Contract' }}
                                </button>
                            </div>
                        </template>

                    </vue3-datatable>
                </div>
            </div>



        </div>
    </div>
</template>
<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import Multiselect from '@suadelabs/vue3-multiselect';
import '@suadelabs/vue3-multiselect/dist/vue3-multiselect.css';
import { router } from '@inertiajs/vue3'
import CountUp from 'vue-countup-v3';
import axios from 'axios';
import Swal from 'sweetalert2';
import { useAppStore } from '@/stores/index';
import { integer } from '@vuelidate/validators/index.js';
import Vue3Datatable from '@bhplugin/vue3-datatable';

const { contracts: initialContracts } = defineProps({
    contracts: Object,
});


const contracts = ref(initialContracts);
const store = useAppStore();
const refreshInterval = ref<NodeJS.Timeout | null>(null);

const params = ref({
    current_page: 1,
    pagesize: 10,
    sort_column: 'id',
    sort_direction: 'desc',

});

// Función para refrescar los datos
const refreshContracts = async () => {
    try {
        const response = await axios.get('/ccaf/contracts'); // Ajusta esta ruta a tu endpoint
        contracts.value = response.data.contracts;
    } catch (error) {
        console.error('Error refreshing contracts:', error);
    }
};

// Iniciar el intervalo cuando el componente se monta
onMounted(() => {
    refreshInterval.value = setInterval(refreshContracts, 30000); // 30 segundos

    // Opcional: refrescar inmediatamente al montar (quita esto si no lo necesitas)
    // refreshContracts();
});

// Limpiar el intervalo cuando el componente se desmonta
onUnmounted(() => {
    if (refreshInterval.value) {
        clearInterval(refreshInterval.value);
    }
});


const cols =
    ref([


        /*  {
  
              field: 'created_at', title: 'Created', cellRenderer: (item) => {
                  if (!item.created_at) return '';
  
                  try {
                      const date = new Date(item.created_at);
                      if (isNaN(date.getTime())) return item.created_at; // Si no es fecha válida
  
                      const options = { month: 'short', day: 'numeric', year: 'numeric' };
                      return new Intl.DateTimeFormat('en-US', options).format(date);
                  } catch {
                      return item.created_at; // Si hay error, devolver el valor original
                  }
              }
          },*/
        { field: 'order_id', title: 'Order', filter: true },
        { field: 'name', title: 'Customer', filter: true },

        {
            field: 'status', filter: true, title: 'Status',
            cellRenderer: (item) => {
                if (item.status === 'Signed') {
                    if (item.signed_at) {
                        try {
                            const date = new Date(item.signed_at);
                            if (!isNaN(date.getTime())) {
                                const options = { month: 'short', day: 'numeric', year: 'numeric' };
                                const formattedDate = new Intl.DateTimeFormat('en-US', options).format(date);
                                return `<span style="color: green; font-weight: bold;">${item.status}</span><br>On ${formattedDate}`;
                            }
                        } catch {
                            return `<span style="color: green; font-weight: bold;">${item.status}</span><br>On ${item.signed_at}`;
                        }
                    }
                    return `<span style="color: green; font-weight: bold;">${item.status}</span>`;
                }
                if (item.status == 'Sms' || item.status == 'Emailed') {
                    return "Sent"
                }



                return item.status;
            }
        },
        {
            field: 'is_ready', filter: false, title: 'Ready',
            cellRenderer: (item) => {
                if (item.is_ready == 1) {
                    return `
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="green">
            <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z"/>
          </svg>
        `;
                }
                return '';
            }
        },
        {
            field: 'actions',
            title: 'Actions',
            filter: false,

        },


    ]) || [];

const isSending = ref(false);

function handleSendContract(data: { id: number; status: string }): void {
    isSending.value = true;
    axios.post('/ccaf/sendContract/' + data.id)
        .then(() => {
            Swal.fire('Success', 'Contract sent successfully!', 'success');
        })
        .catch(() => {
            Swal.fire('Error', 'Failed to send contract.', 'error');
        })
        .finally(() => {
            isSending.value = false;
        });
}



</script>
