// @ts-ignore
import {defineStore} from 'pinia'

// نوع داده مخاطب
interface Contact {
    name: string;
    phone: string;
}

export const useContactStore = defineStore('contacts', {
    state: () => ({
        // @ts-ignore
        contacts: [] as Contact[],
    }),

    getters: {
        // @ts-ignore
        getContacts: (state) => state.contacts,
    },

    actions: {
        initContacts() {
            const contacts = localStorage.getItem('user_contacts');
            if (contacts) {
                try {
                    // @ts-ignore
                    this.contacts = JSON.parse(contacts);
                } catch (error) {
                    console.error('Error parsing contacts from localStorage:', error);
                    // @ts-ignore
                    this.contacts = [];
                }
            }
        },

        /**
         * تابع تبدیل اعداد فارسی/عربی به انگلیسی
         */
        persianToEnglish(str: string): string {
            const persianNumbers = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
            const arabicNumbers = ['٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩'];
            const englishNumbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

            let result = str;

            // تبدیل اعداد فارسی
            persianNumbers.forEach((persianNum, index) => {
                // @ts-ignore
                result = result.replace(new RegExp(persianNum, 'g'), englishNumbers[index]);
            });

            // تبدیل اعداد عربی
            arabicNumbers.forEach((arabicNum, index) => {
                // @ts-ignore
                result = result.replace(new RegExp(arabicNum, 'g'), englishNumbers[index]);
            });

            return result;
        },

        /**
         * تابع نرمال سازی شماره تلفن
         */
        normalizePhoneNumber(phone: string): string {
            // تبدیل اعداد فارسی/عربی به انگلیسی
            let normalized = this.persianToEnglish(phone);

            // حذف همه کاراکترهای غیرعددی به جز +
            normalized = normalized.replace(/[^\d+]/g, '');

            // تبدیل +98 به 0
            if (normalized.startsWith('+98')) {
                normalized = '0' + normalized.substring(3);
            }

            // اگر با 0098 شروع شد
            if (normalized.startsWith('0098')) {
                normalized = '0' + normalized.substring(4);
            }

            return normalized;
        },

        /**
         * نرمال سازی و ذخیره مخاطبین
         */
        // @ts-ignore
        normalizeAndSaveContacts() {
            // نرمال سازی تمام مخاطبین با حفظ ساختار
            // @ts-ignore
            const normalizedContacts = this.contacts.map((contact: Contact) => ({
                ...contact,
                phone: this.normalizePhoneNumber(contact.phone)
            }));

            // به‌روزرسانی state
            // @ts-ignore
            this.contacts = normalizedContacts;

            // ذخیره در localStorage
            try {
                localStorage.setItem('user_contacts', JSON.stringify(normalizedContacts));
                console.log('Contacts normalized and saved to localStorage');

                // برگرداندن نتیجه برای استفاده در صورت نیاز
                return {
                    success: true,
                    message: 'Contacts normalized and saved successfully',
                    contacts: normalizedContacts
                };
            } catch (error) {
                console.error('Error saving contacts to localStorage:', error);
                return {
                    success: false,
                    message: 'Failed to save contacts to localStorage',
                    error: error
                };
            }
        },

        /**
         * متد ترکیبی: ابتدا مخاطبین را بارگذاری کرده سپس نرمال سازی می‌کند
         */
        // @ts-ignore
        loadAndNormalizeContacts() {
            this.initContacts();
            this.normalizeAndSaveContacts();
            // @ts-ignore
            this.checkContact();
        },

        /**
         * اضافه کردن مخاطب جدید
         */
        addContact(contact: Contact) {
            // نرمال سازی شماره قبل از ذخیره
            const normalizedContact = {
                ...contact,
                phone: this.normalizePhoneNumber(contact.phone)
            };

            // @ts-ignore
            this.contacts.push(normalizedContact);
            this.saveToLocalStorage();
        },

        /**
         * ذخیره مخاطبین در localStorage
         */
        saveToLocalStorage() {
            try {
                // @ts-ignore
                localStorage.setItem('user_contacts', JSON.stringify(this.contacts));
            } catch (error) {
                console.error('Error saving to localStorage:', error);
            }
        },

        async checkContact() {
            const {$api} = useNuxtApp();

            try {
                const res = await $api.post('/contact/check', {
                    items: localStorage.getItem('user_contacts')
                });

                const data = Array.isArray(res.data.data) ? res.data.data : [];

                // ✅ فیلتر ایمن
                this.contacts = data.map((c: any) => ({
                    name: c?.name ?? '',
                    phone: c?.phone ?? '',
                    check: c?.check ?? null,
                    source: c?.source ?? null
                }));

                localStorage.setItem('user_contacts', JSON.stringify(this.contacts));

            } catch (err) {
                console.error('checkContact error:', err);
                this.contacts = [];
            }
        },


        /**
         * دریافت مخاطبین با شماره نرمال شده
         */
        // @ts-ignore
        getNormalizedContacts() {
            // @ts-ignore
            return this.contacts.map(contact => ({
                ...contact,
                phone: this.normalizePhoneNumber(contact.phone)
            }));
        }
    },
});