import { Livewire, Alpine } from '../../vendor/livewire/livewire/dist/livewire.esm';
import 'animate.css';

import flatpickr from "flatpickr";
import 'flatpickr/dist/themes/material_blue.css'

import toast from './toast';

window.toast = toast

Alpine.directive('flatpickr', (el, { expression }, { evaluate }) => {
    const config = {};

    if (expression !== 'x-flatpickr') {
        const dynamicConfig = expression && evaluate(expression);
        Object.assign(config, dynamicConfig);
    }

    flatpickr(el, config);

})

Alpine.magic('clipboard', () => {
    return (subject, $el) => {
        navigator.clipboard.writeText(subject)
        toast.success('Copied.')
        $el.classList.remove('icon-copy')
        $el.classList.add('icon-check')
    }
})

Alpine.store('countries', {
    loading: false,
    countries: [],
    init() {
        this.loading = true
        var headers = new Headers();
        headers.append("X-CSCAPI-KEY", "dTl2SGE5NEo2bVBOWnRDV25OVERtTkdSWEsxRkxDVVJYYThMcWtyWg==");

        var requestOptions = {
            method: 'GET',
            headers,
            redirect: 'follow'
        };

        fetch("https://api.countrystatecity.in/v1/countries", requestOptions)
            .then(response => response.json())
            .then(data => {
                this.countries = data
                this.loading = false
            })
            .catch(error => {
                console.log('error', error)
                this.loading = false
                toast.fallback()
            });
    }
})

Alpine.data('toggle_password', () => ({
    showing: false,
    toggle(el) {
        if (el.value) {
            if (el.type == 'password') {
                el.type = 'text'
                return this.showing = true
            }

            if (el.type == 'text') {
                el.type = 'password'
                return this.showing = false
            }
        }
    }
}))

Alpine.data('delete_shipment', () => ({
    processing: false,
    shipment: {},

    async delete_single(id) {
        const headers = new Headers()
        const csrf = document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        headers.append('X-CSRF-TOKEN', csrf)

        const requestOptions = {
            method: "DELETE",
            headers
        }

        try {
            this.processing = true
            const data = await (await fetch(route('shipment.delete', id), requestOptions)).json()
            if(data.success) {
                Livewire.navigate(route('shipments'))
            }
            this.processing = false

        } catch (error) {
            this.processing = false
            console.log(error)
        }
    }
}))

Alpine.data('invoice', () => ({
    processing: false,
    tracking_code: '',

    async download() {
        toast.info('Downloading...')
        try {
            this.processing = true
            const data = await (await fetch(route('invoice.download', this.tracking_code))).json()
            if(data.success) {
                const downloadElement = document.createElement('a')
                downloadElement.href = data.download_url
                downloadElement.download = `Shipment Invoice - ${this.tracking_code}.pdf`
                document.body.appendChild(downloadElement)
                downloadElement.click()
            }
            this.processing = false

        } catch (error) {
            this.processing = false
            console.log(error)
            toast.fallback()
        }
    },

    stream() {
        toast.info('Streaming...')
        setTimeout(() => {
            window.open(route('invoice.stream', this.tracking_code), '_blank')
        }, 500);
    },
}))

Alpine.data('delete_tracking', () => ({
    processing: false,
    tracking: {},

    async delete_single(id) {
        const headers = new Headers()
        const csrf = document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        headers.append('X-CSRF-TOKEN', csrf)

        const requestOptions = {
            method: "DELETE",
            headers
        }

        try {
            this.processing = true
            const data = await (await fetch(route('tracking.delete', id), requestOptions)).json()
            if(data.success) {
                Livewire.navigate(route('trackings'))
            }
            this.processing = false

        } catch (error) {
            this.processing = false
            toast.fallback()
            console.log(error)
        }
    }
}))

Alpine.data('logout', () => ({
    processing: false,

    async logout() {
        this.processing = true
        const headers = new Headers()
        const csrf = document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        headers.append('X-CSRF-TOKEN', csrf)

        const requestOptions = {
            method: "POST",
            headers
        }
        try {
            toast.info('Logging out...')
            const data = await (await fetch(route('logout'), requestOptions)).json()
            if(data.success) {
                Livewire.navigate(route('login'))
            }
        } catch (error) {
            this.processing = false
            console.log(error)
            toast.fallback()
        }
    }
}))

Alpine.data('send_receiver_email', () => ({
    processing: false,
    errors: {},
    form: {},
    
    set(receiverDetails) {
        this.form.email = receiverDetails.receiver_email ?? receiverDetails.email;
        this.form.name = receiverDetails.receiver_name ?? receiverDetails.name;
    },


    async send() {
        this.processing = true

        this.form.content = document.getElementById('email-content').value;
        this.form.content = $('#email-content').summernote('code')

        const headers = new Headers()
        const csrf = document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        headers.append('X-CSRF-TOKEN', csrf)
        headers.append('Content-Type', 'application/json')

        const requestOptions = {
            method: 'POST',
            headers,
            body: JSON.stringify(this.form),
        }

        try {
            const { ok, data} = await (await fetch(route('send-notice'), requestOptions)).json()
            if(!ok) {
                console.log(data);
                this.errors = data

            } else {
                toast.success(data)
                this.$dispatch('email-sent')
            }
            this.processing = false
        } catch (error) {
            this.processing = false
            console.log(error)
            toast.fallback()
        }
    }
}))

Alpine.data('delete_contact', () => ({
    processing: false,

    async delete_single(id) {
        const headers = new Headers()
        const csrf = document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        headers.append('X-CSRF-TOKEN', csrf)

        const requestOptions = {
            method: "DELETE",
            headers
        }

        try {
            this.processing = true
            const { ok, data} = await (await fetch(route('contact-message.delete', id), requestOptions)).json()
            if(ok) {
                Livewire.navigate(route('contact-messages'))
            }else{
                toast.error(data)
            }
            this.processing = false

        } catch (error) {
            this.processing = false
            toast.fallback()
            console.log(error)
        }
    }

}))

Livewire.start()