<script setup>
import { FwbBadge } from 'flowbite-vue';
import { EditIcon, PlusIcon, UserEditIcon, TrashBinIcon } from '@/Utilities/Icons';
import CusTab from './CusTab.vue';
import CusTabs from './CusTabs.vue';
import { provide, ref, watch } from 'vue';
import axios from 'axios';
import PersonUpdateForm from './PersonUpdateForm.vue';
import AddressCreateForm from './AddressCreateForm.vue';
import PhoneCreateForm from './PhoneCreateForm.vue';
import EmailCreateForm from './EmailCreateForm.vue';
import EmailUpdateForm from './EmailUpdateForm.vue';
import TrrCreateForm from './TrrCreateForm.vue';
import TrrUpdateForm from './TrrUpdateForm.vue';
import ConfirmDialog from './ConfirmDialog.vue';


const props = defineProps({
    person: Object,
    edit: {
        type: Boolean,
        default: false
    },
    tabColor: {
        type: String,
        default: 'blue-600'
    },
    types: {
        type: Object,
        default: {
            address_types: [],
            phone_types: []
        }
    }

});

const drawerUpdatePerson = ref(false);
const drawerAddAddress = ref(false);
const drawerAddPhone = ref(false);
const drawerAddEmail = ref(false);
const drawerAddTrr = ref(false);

const editAddress = ref(false);
const editAddressId = ref(0);

const editPhone = ref(false);
const editPhoneId = ref(0);
const editEmail = ref(false);
const editEmailId = ref(0);
const editTrr = ref(false);
const editTrrId = ref(0);

// Confirm dialog state
const confirm = ref({
    show: false,
    title: 'Potrditev brisanja',
    message: '',
    type: '', // 'email' | 'trr' | 'address' | 'phone'
    id: 0,
});

const openConfirm = (type, id, label = '') => {
    confirm.value = {
        show: true,
        title: 'Potrditev brisanja',
        message: label ? `Ali res želite izbrisati “${label}”?` : 'Ali res želite izbrisati izbran element?',
        type,
        id,
    };
}
const closeConfirm = () => { confirm.value.show = false; };

const getMainAddress = (adresses) => {
    const addr = adresses.filter( a => a.type.id === 1 )[0] ?? '';
    if( addr !== '' ){
        const country = addr.country !== '' ? ` - ${addr.country}` : '';
        return addr.address !== '' ? addr.address + country : '';
    }
    
    return '';
}

const getMainPhone = (phones) => {
    const pho = phones.filter( a => a.type.id === 1 )[0] ?? '';
    if( pho !== '' ){
        const countryCode = pho.country_code !== null ? `+${pho.country_code} ` : '';
        return pho.nu !== '' ? countryCode + pho.nu: '';
    }

    return '';
    
}

const openDrawerUpdateClient = () => {
    drawerUpdatePerson.value = true;
}

const openDrawerAddAddress = (edit = false, id = 0) => {
    drawerAddAddress.value = true;
    editAddress.value = edit;
    editAddressId.value = id;
    
}

const operDrawerAddPhone = (edit = false, id = 0) => {
    drawerAddPhone.value = true;
    editPhone.value = edit;
    editPhoneId.value = id;
}

const openDrawerAddEmail = (edit = false, id = 0) => {
    drawerAddEmail.value = true;
    editEmail.value = edit;
    editEmailId.value = id;
}

const openDrawerAddTrr = (edit = false, id = 0) => {
    drawerAddTrr.value = true;
    editTrr.value = edit;
    editTrrId.value = id;
}

// Delete handlers (expects routes: person.email.delete, person.trr.delete)
const deleteEmail = async (emailId, label = '') => {
    if (!emailId) return;
    openConfirm('email', emailId, label || 'email');
}

const deleteTrr = async (trrId, label = '') => {
    if (!trrId) return;
    openConfirm('trr', trrId, label || 'TRR');
}

const onConfirmDelete = async () => {
    const { type, id } = confirm.value;
    try {
        if (type === 'email') {
            await axios.delete(route('person.email.delete', { person: props.person, email_id: id }));
            const list = props.person.emails || [];
            const idx = list.findIndex(e => e.id === id);
            if (idx !== -1) list.splice(idx, 1);
        } else if (type === 'trr') {
            await axios.delete(route('person.trr.delete', { person: props.person, trr_id: id }));
            let list = props.person.trrs || props.person.bank_accounts || props.person.accounts || props.person.bankAccounts || [];
            const idx = list.findIndex(a => a.id === id);
            if (idx !== -1) list.splice(idx, 1);
        } else if (type === 'address') {
            await axios.delete(route('person.address.delete', { person: props.person, address_id: id }));
            const list = props.person.addresses || [];
            const idx = list.findIndex(a => a.id === id);
            if (idx !== -1) list.splice(idx, 1);
        } else if (type === 'phone') {
            await axios.delete(route('person.phone.delete', { person: props.person, phone_id: id }));
            const list = props.person.phones || [];
            const idx = list.findIndex(p => p.id === id);
            if (idx !== -1) list.splice(idx, 1);
        }
        closeConfirm();
    } catch (e) {
        console.error('Delete failed', e?.response || e);
        closeConfirm();
    }
}

// Safe accessors for optional collections
const getEmails = (p) => Array.isArray(p?.emails) ? p.emails : []
const getTRRs = (p) => {
    if (Array.isArray(p?.trrs)) return p.trrs
    if (Array.isArray(p?.bank_accounts)) return p.bank_accounts
    if (Array.isArray(p?.accounts)) return p.accounts
    if (Array.isArray(p?.bankAccounts)) return p.bankAccounts
    return []
}

</script>

<template>
    <CusTabs :selected-color="tabColor">
        <CusTab name="person" title="Oseba">
            <div class="flex justify-end mb-2">
                <span class=" border-b-2 border-gray-500 hover:border-gray-800">
                    <button @click="openDrawerUpdateClient"><UserEditIcon size="lg" css="text-gray-500 hover:text-gray-800" /></button>
                </span>
            </div>
            <div class="grid grid-rows-* grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-2">
                <div class="rounded p-2 shadow">
                    <p class="text-xs leading-5 md:text-sm text-gray-500">Nu.</p>
                    <p class="text-sm md:text-base leading-7 text-gray-900">{{ person.nu }}</p>
                </div>
                <div class="rounded p-2 shadow">
                    <p class="text-sm leading-5 md:text-sm text-gray-500">Name.</p>
                    <p class="text-sm md:text-base leading-7 text-gray-900">{{ person.full_name }}</p>
                </div>
                <div class="rounded p-2 shadow">
                    <p class="text-sm leading-5 md:text-sm text-gray-500">Tax NU.</p>
                    <p class="text-sm md:text-base leading-7 text-gray-900">{{ person.tax_number }}</p>
                </div>
                <div class="rounded p-2 shadow">
                    <p class="text-sm leading-5 md:text-sm text-gray-500">Social security NU.</p>
                    <p class="text-sm md:text-base leading-7 text-gray-900">{{ person.social_security_number }}</p>
                </div>
            </div>
            <div class="grid grid-rows-* grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2 mt-1">
                <div class="rounded p-2 shadow">
                    <p class="text-sm leading-5 md:text-sm text-gray-500">Address</p>
                    <p class="text-sm md:text-base leading-7 text-gray-900">{{ getMainAddress(person.addresses) }}</p>
                </div>
                <div class="rounded p-2 shadow">
                    <p class="text-sm leading-5 md:text-sm text-gray-500">Phone</p>
                    <p class="text-sm md:text-base leading-7 text-gray-900">{{ getMainPhone(person.phones) }}</p>
                </div>
                <div class="md:col-span-full lg:col-span-1 rounded p-2 shadow">
                    <p class="text-sm leading-5 md:text-sm text-gray-500">Description</p>
                    <p class="text-sm md:text-base leading-7 text-gray-900">{{ person.description }}</p>
                </div>
            </div>
        </CusTab >
        <CusTab name="addresses" title="Naslovi">
            <div class="flex justify-end mb-2">
                <span class="border-b-2 border-gray-500 hover:border-gray-800">
                    <button><PlusIcon @click="openDrawerAddAddress(false, 0)" size="lg" css="text-gray-500 hover:text-gray-800" /></button>
                </span>
            </div>
            <div class="grid grid-rows-* grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2 mt-1">
                <div class="rounded p-2 shadow" v-for="address in person.addresses">
                    <div class="text-sm leading-5 md:text-sm text-gray-500 flex justify-between">
                        <div class="flex ">
                            <FwbBadge type="yellow">{{ address.country }}</FwbBadge>
                            <FwbBadge>{{ address.type.name }}</FwbBadge>
                        </div>
                        <div class="flex items-center gap-2">
                            <button><EditIcon @click="openDrawerAddAddress(true, address.id)" size="md" css="text-gray-500 hover:text-gray-800" /></button>
                            <button @click="openConfirm('address', address.id, address.address)"><TrashBinIcon size="md" css="text-red-600 hover:text-red-700" /></button>
                        </div>
                    </div>
                    <p class="text-sm md:text-base leading-7 text-gray-900">{{ address.address }}</p>
                </div>
            </div>
        </CusTab>
        <CusTab name="phones" title="Telefonske">
            <div class="flex justify-end mb-2">
                <span class="border-b-2 border-gray-500 hover:border-gray-800">
                    <button><PlusIcon @click="operDrawerAddPhone(false, 0)" size="lg" css="text-gray-500 hover:text-gray-800" /></button>
                </span>
            </div>
            <div class="grid grid-rows-* grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2 mt-1">
                <div class="rounded p-2 shadow" v-for="phone in person.phones">
                    <div class="text-sm leading-5 md:text-sm text-gray-500 flex justify-between">
                        <div class="flex ">
                            <FwbBadge title type="yellow">+{{ phone.country_code }}</FwbBadge>
                            <FwbBadge>{{ phone.type.name }}</FwbBadge>
                        </div>
                        <div class="flex items-center gap-2">
                            <button><EditIcon @click="operDrawerAddPhone(true, phone.id)" size="md" css="text-gray-500 hover:text-gray-800" /></button>
                            <button @click="openConfirm('phone', phone.id, phone.nu)"><TrashBinIcon size="md" css="text-red-600 hover:text-red-700" /></button>
                        </div>
                    </div>
                    <p class="text-sm md:text-base leading-7 text-gray-900">{{ phone.nu }}</p>
                </div>
            </div>
        </CusTab>
        <CusTab name="emails" title="Email">
            <div class="flex justify-end mb-2">
                <span class="border-b-2 border-gray-500 hover:border-gray-800">
                    <button><PlusIcon @click="openDrawerAddEmail(false, 0)" size="lg" css="text-gray-500 hover:text-gray-800" /></button>
                </span>
            </div>
            <div class="grid grid-rows-* grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2 mt-1">
                <template v-if="getEmails(person).length">
                    <div class="rounded p-2 shadow" v-for="(email, idx) in getEmails(person)" :key="idx">
                        <div class="text-sm leading-5 md:text-sm text-gray-500 flex justify-between">
                            <div class="flex gap-2">
                                <FwbBadge v-if="email?.label">{{ email.label }}</FwbBadge>
                                <FwbBadge v-else type="indigo">Email</FwbBadge>
                            </div>
                            <div class="flex items-center gap-2">
                                <button><EditIcon @click="openDrawerAddEmail(true, email.id)" size="md" css="text-gray-500 hover:text-gray-800" /></button>
                                <button @click="deleteEmail(email.id, email?.value || email?.email || email?.address)"><TrashBinIcon size="md" css="text-red-600 hover:text-red-700" /></button>
                            </div>
                        </div>
                        <p class="text-sm md:text-base leading-7 text-gray-900">
                            {{ email?.value || email?.email || email?.address || '-' }}
                        </p>
                        <p v-if="email?.note" class="mt-1 text-xs text-gray-500 whitespace-pre-wrap">{{ email.note }}</p>
                    </div>
                </template>
                <p v-else class="p-2 text-sm text-gray-500">Ni e-poštnih naslovov.</p>
            </div>
        </CusTab>
        <CusTab name="trr" title="TRR">
            <div class="flex justify-end mb-2">
                <span class="border-b-2 border-gray-500 hover:border-gray-800">
                    <button><PlusIcon @click="openDrawerAddTrr(false, 0)" size="lg" css="text-gray-500 hover:text-gray-800" /></button>
                </span>
            </div>
            <div class="grid grid-rows-* grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2 mt-1">
                <template v-if="getTRRs(person).length">
                    <div class="rounded p-2 shadow" v-for="(acc, idx) in getTRRs(person)" :key="idx">
                        <div class="text-sm leading-5 md:text-sm text-gray-500 flex justify-between">
                            <div class="flex gap-2">
                                <FwbBadge v-if="acc?.bank_name">{{ acc.bank_name }}</FwbBadge>
                                <FwbBadge v-if="acc?.holder_name" type="indigo">{{ acc.holder_name }}</FwbBadge>
                                <FwbBadge v-if="acc?.currency" type="yellow">{{ acc.currency }}</FwbBadge>
                            </div>
                            <div class="flex items-center gap-2">
                                <button><EditIcon @click="openDrawerAddTrr(true, acc.id)" size="md" css="text-gray-500 hover:text-gray-800" /></button>
                                <button @click="deleteTrr(acc.id, acc?.iban || acc?.account_number)"><TrashBinIcon size="md" css="text-red-600 hover:text-red-700" /></button>
                            </div>
                        </div>
                        <p class="text-sm md:text-base leading-7 text-gray-900">
                            {{ acc?.iban || acc?.account_number || acc?.account || acc?.nu || acc?.number || '-' }}
                        </p>
                        <p v-if="acc?.notes" class="mt-1 text-xs text-gray-500 whitespace-pre-wrap">{{ acc.notes }}</p>
                    </div>
                </template>
                <p v-else class="p-2 text-sm text-gray-500">Ni TRR računov.</p>
            </div>
        </CusTab>
        <CusTab name="other" title="Drugo"> 
            ssss4
        </CusTab>
    </CusTabs>
    <PersonUpdateForm 
        :show="drawerUpdatePerson"
        @close="drawerUpdatePerson = false"
        :person="person"
    />

    <AddressCreateForm 
        :show="drawerAddAddress"
        @close="drawerAddAddress = false"
        :person="person"
        :types="types.address_types"
        :id="editAddressId"
        :edit="editAddress"
    />

    <PhoneCreateForm 
        :show="drawerAddPhone"
        @close="drawerAddPhone = false"
        :person="person"
        :types="types.phone_types"
        :id="editPhoneId"
        :edit="editPhone"
    />
    <!-- Email dialogs -->
    <EmailCreateForm
        :show="drawerAddEmail && !editEmail"
        @close="drawerAddEmail = false"
        :person="person"
        :types="types.email_types ?? []"
        :is-client-context="!!person?.client"
    />
    <EmailUpdateForm
        :show="drawerAddEmail && editEmail"
        @close="drawerAddEmail = false"
        :person="person"
        :types="types.email_types ?? []"
        :id="editEmailId"
        :is-client-context="!!person?.client"
    />

    <!-- TRR dialogs -->
    <TrrCreateForm
        :show="drawerAddTrr && !editTrr"
        @close="drawerAddTrr = false"
        :person="person"
        :types="types.trr_types ?? []"
        :banks="types.banks ?? []"
        :currencies="types.currencies ?? ['EUR']"
    />
    <TrrUpdateForm
        :show="drawerAddTrr && editTrr"
        @close="drawerAddTrr = false"
        :person="person"
        :types="types.trr_types ?? []"
        :banks="types.banks ?? []"
        :currencies="types.currencies ?? ['EUR']"
        :id="editTrrId"
    />
    
    <!-- Confirm deletion dialog -->
    <ConfirmDialog
        :show="confirm.show"
        :title="confirm.title"
        :message="confirm.message"
        confirm-text="Izbriši"
        cancel-text="Prekliči"
        :danger="true"
        @close="closeConfirm"
        @confirm="onConfirmDelete"
    />
    
</template>